From 083db6d2ea9a1f11857be18a61771f5dff4ff2e2 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 01:55:05 +0000 Subject: [PATCH 01/15] feat(app): add a duration heatmap view to trace search Adds a RED/Heatmap switch to the trace results chart area. Heatmap renders the duration distribution over time as the same tile the dashboard does. The mode is URL state, so a reload or a shared link reopens the same view, and it resets to RED when the source changes. The heatmap's bounds and bucket queries take the search's RED query-key prefix (DBHeatmapChart gains the queryKeyPrefix prop DBTimeChart already has; keys are unchanged for callers that don't pass one), so live tail waits on them instead of stacking a fresh pair each tick. Live tail is also pinned off while the heatmap is the visible chart: a tick moves the absolute time range, and the heatmap keys its uPlot instance on the chart config, so each refresh would otherwise tear the chart down and rebuild it. The switch, the chart branch and the live-tail pin share one derived source, so the heatmap renders (and pins live tail) only where the RED tiles would: a trace source with a duration column, a non-compact viewport, and no custom group-by. Co-Authored-By: Claude Opus 5.5 --- .changeset/trace-search-duration-heatmap.md | 5 + packages/app/src/DBSearchPage.tsx | 118 +++++++++++++++--- .../DBHeatmapChart/DBHeatmapChart.tsx | 9 ++ .../__tests__/useHeatmapData.test.ts | 33 +++++ .../DBHeatmapChart/useHeatmapData.ts | 13 +- .../Search/TraceRedMetricsChart.tsx | 65 +++++++++- 6 files changed, 225 insertions(+), 18 deletions(-) create mode 100644 .changeset/trace-search-duration-heatmap.md diff --git a/.changeset/trace-search-duration-heatmap.md b/.changeset/trace-search-duration-heatmap.md new file mode 100644 index 000000000..0d3278cc0 --- /dev/null +++ b/.changeset/trace-search-duration-heatmap.md @@ -0,0 +1,5 @@ +--- +'@hyperdx/app': minor +--- + +Add a RED/Heatmap switch to the trace search results view. Heatmap shows the duration distribution over time as the same tile the dashboard renders, and the choice is kept in the URL so a reload or a shared link reopens the same view. diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 841e88392..55e6d9041 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -61,6 +61,7 @@ import { Group, Modal, Paper, + SegmentedControl, Select, Stack, Text, @@ -163,7 +164,10 @@ import DBSqlRowTableWithSideBar from './components/DBSqlRowTableWithSidebar'; import PatternTable from './components/PatternTable'; import { DBSearchHeatmapChart } from './components/Search/DBSearchHeatmapChart'; import DirectTraceSidePanel from './components/Search/DirectTraceSidePanel'; -import { TraceRedMetricsChart } from './components/Search/TraceRedMetricsChart'; +import { + type TraceChartMode, + TraceRedMetricsChart, +} from './components/Search/TraceRedMetricsChart'; import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from './components/SourceSchemaPreview'; @@ -1126,6 +1130,14 @@ function DBSearchPageContent() { ]).withDefault('results'), ); + // RED metrics vs heatmap for the trace results chart area. URL state (like + // the other view toggles on this page) so a reload or shared link keeps the + // chosen view; the switch lives inline in the search stats row. + const [traceChartMode, setTraceChartMode] = useQueryState( + 'traceChartMode', + parseAsStringEnum(['red', 'heatmap']).withDefault('red'), + ); + // URL-only, not saved with the search: null uses the source default. const [groupByParam, setGroupByParam] = useQueryState( 'groupBy', @@ -2053,10 +2065,10 @@ function DBSearchPageContent() { const aliasWith = useMemo(() => aliasMapToWithClauses(aliasMap), [aliasMap]); - // The trace results chart shows RED metrics only for a trace source that - // exposes a duration column; otherwise the single histogram stays. Derived - // once, as the narrowed source or null, so the callers can't drift apart on - // which one renders. + // The trace results chart shows RED metrics (and a heatmap) only for a trace + // source that exposes a duration column; otherwise the single histogram + // stays. Derived once, as the narrowed source or null, so the callers can't + // drift apart on which one renders. const traceRedMetricsSource = searchedSource != null && isTraceSource(searchedSource) && @@ -2064,6 +2076,23 @@ function DBSearchPageContent() { ? searchedSource : null; + // Reset to the default RED view when the source actually changes, so + // returning to a trace source after viewing another one doesn't silently + // reopen in Heatmap. The ref starts undefined and is only compared once a + // real id has been seen, so the async source resolution on first load + // (undefined -> id) doesn't count as a change and a shared link that pins + // ?traceChartMode=heatmap survives. + const prevSourceIdRef = useRef(undefined); + useEffect(() => { + if ( + prevSourceIdRef.current !== undefined && + prevSourceIdRef.current !== searchedSource?.id + ) { + setTraceChartMode('red'); + } + prevSourceIdRef.current = searchedSource?.id; + }, [searchedSource?.id, setTraceChartMode]); + const histogramTimeChartConfig = useMemo(() => { if (chartConfig == null) { return undefined; @@ -2123,6 +2152,53 @@ function DBSearchPageContent() { [isCustomGroupBy, histogramTimeChartConfig, searchedSource], ); + // The RED/Heatmap chart area renders only where it fits: a trace source with + // a duration column, on a non-compact viewport (three side-by-side tiles + // would be unreadable on a phone), without a custom group-by (the RED tiles + // have fixed grouping, so a custom group-by falls back to the histogram, + // which honors it). Derived once, as the narrowed source or null, so the + // chart branch, the stats-row RED/Heatmap switch and the live-tail pin can't + // drift apart on which one renders. + const traceChartsSource = + traceRedMetricsSource != null && !isCompact && !isCustomGroupBy + ? traceRedMetricsSource + : null; + + // Base config for the trace heatmap tile, mirroring the delta-mode heatmap: + // the search's chart config over the searched range, carrying the source's + // select-alias definitions. Memoized so the tile's query stays stable across + // re-renders. + const traceHeatmapChartConfig = useMemo( + () => + chartConfig == null + ? undefined + : ({ + ...chartConfig, + dateRange: searchedTimeRange, + with: aliasWith, + } satisfies BuilderChartConfigWithDateRange), + [chartConfig, searchedTimeRange, aliasWith], + ); + + // Pin live tail off while the heatmap is the visible chart. A live tick + // moves the absolute time range, and the heatmap keys its uPlot instance on + // the chart config, so every refresh would tear the chart down and rebuild + // it with a recomputed y-axis instead of updating in place. Delta and + // pattern modes already pin it off, so the delta-view heatmap never hit + // this; results mode defaults to live, so the view has to opt out for + // itself. Only pinned while the heatmap is actually rendered, so a stale + // ?traceChartMode=heatmap on a source that shows the histogram can't disable + // live tail. + const isHeatmapChartVisible = + analysisMode === 'results' && + traceChartsSource != null && + traceChartMode === 'heatmap'; + useEffect(() => { + if (isHeatmapChartVisible) { + setIsLive(false); + } + }, [isHeatmapChartVisible, setIsLive]); + const histogramGroupBySelect = ( + {traceChartsSource != null && ( + + setTraceChartMode( + v === 'heatmap' ? 'heatmap' : 'red', + ) + } + data={[ + { label: 'RED', value: 'red' }, + { label: 'Heatmap', value: 'heatmap' }, + ]} + /> + )} {shouldShowLiveModeHint && denoiseResults != true && ( {!hasQueryError && - // The three side-by-side RED tiles need room, so on a - // compact (narrow/mobile) viewport fall back to the - // single histogram. The RED tiles also have fixed - // grouping (Throughput by status, Errors by status, - // Duration ungrouped), so when the user picks a custom - // group-by fall back to the histogram, which honors it. - (traceRedMetricsSource != null && - !isCompact && - !isCustomGroupBy ? ( + // RED/Heatmap where it fits, else the histogram; see + // traceChartsSource for when each one renders. + (traceChartsSource != null && + traceHeatmapChartConfig != null ? ( ); } diff --git a/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts b/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts index 87a5b3950..188fa929a 100644 --- a/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts +++ b/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts @@ -132,4 +132,37 @@ describe('useHeatmapData', () => { expect(boundsQuery.dateRange).toEqual(dateRange); expect(bucketQuery.dateRange).toEqual(dateRange); }); + + describe('queryKeyPrefix', () => { + const queryKeys = (queryKeyPrefix?: string) => { + const query = toHeatmapQuery(traceConfig); + if (query.mode !== 'distribution') { + throw new Error('Expected distribution'); + } + renderHook(() => + useHeatmapData({ + config: query.config, + scaleType: query.scaleType, + enabled: true, + queryKeyPrefix, + }), + ); + return mockUseQueriedChartConfig.mock.calls.map( + ([, options]) => options?.queryKey, + ); + }; + + it('leaves both query keys unchanged when omitted', () => { + const keys = queryKeys(); + expect(keys.map(key => key?.[0])).toEqual(['heatmap', 'heatmap_bucket']); + }); + + it('prepends the prefix to both query keys, like DBTimeChart', () => { + const keys = queryKeys('search-red'); + expect(keys.map(key => key?.slice(0, 2))).toEqual([ + ['search-red', 'heatmap'], + ['search-red', 'heatmap_bucket'], + ]); + }); + }); }); diff --git a/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts b/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts index b90345f8a..1e3b36da2 100644 --- a/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts +++ b/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts @@ -31,11 +31,20 @@ export function useHeatmapData({ config, scaleType, enabled, + queryKeyPrefix, }: { config: HeatmapChartConfig; scaleType: HeatmapScaleType; enabled: boolean; + /** + * Prepended to both query keys, matching `DBTimeChart`'s prop of the same + * name, so a caller that gates on `useIsFetching` for its sibling charts + * (the search page pausing live tail) also waits on these queries. Keys are + * unchanged when omitted. + */ + queryKeyPrefix?: string; }): HeatmapData { + const keyPrefix = queryKeyPrefix != null ? [queryKeyPrefix] : []; const { granularity, generatedTsBuckets } = useHeatmapTimeBuckets({ dateRange: config.dateRange, granularity: config.granularity, @@ -56,7 +65,7 @@ export function useHeatmapData({ isPlaceholderData: isMinMaxPlaceholderData, error: minMaxError, } = useQueriedChartConfig(minMaxConfig, { - queryKey: ['heatmap', minMaxConfig], + queryKey: [...keyPrefix, 'heatmap', minMaxConfig], enabled, placeholderData: prev => prev, }); @@ -81,7 +90,7 @@ export function useHeatmapData({ const { data, isLoading, isPlaceholderData, error } = useQueriedChartConfig( bucketConfig, { - queryKey: ['heatmap_bucket', bucketConfig], + queryKey: [...keyPrefix, 'heatmap_bucket', bucketConfig], // Wait for fresh bounds, so a refresh doesn't also query the new range // bucketed with the previous range's min/max. enabled: enabled && canQueryBuckets && !isMinMaxPlaceholderData, diff --git a/packages/app/src/components/Search/TraceRedMetricsChart.tsx b/packages/app/src/components/Search/TraceRedMetricsChart.tsx index 2ab161105..cd93109fd 100644 --- a/packages/app/src/components/Search/TraceRedMetricsChart.tsx +++ b/packages/app/src/components/Search/TraceRedMetricsChart.tsx @@ -8,7 +8,12 @@ import { Flex, SegmentedControl } from '@mantine/core'; import { IsolatedChartSyncProvider } from '@/chartSync'; import { ChartCard } from '@/components/charts/ChartCard'; +import DBHeatmapChart, { + HEATMAP_DURATION_NUMBER_FORMAT, + toHeatmapQuery, +} from '@/components/DBHeatmapChart'; import { DBTimeChart, type SeriesGroupFilter } from '@/components/DBTimeChart'; +import { getDurationMsExpression } from '@/source'; import { durationConfig, @@ -18,6 +23,8 @@ import { redBaseConfig, } from './traceRedMetrics'; +export type TraceChartMode = 'red' | 'heatmap'; + // Each RED tile is a ChartCard flex child that fills its column; ChartCard // supplies the dashboard-tile chrome (border, background, full-bleed header // divider) and the card-header context, so the three headers line up on their @@ -29,18 +36,27 @@ const RED_TILE_STYLE = { height: '100%', } satisfies CSSProperties; +const HEATMAP_TILE_STYLE = { + height: '100%', + minHeight: 0, +} satisfies CSSProperties; + /** * RED metrics (Throughput, Errors, Duration) for the trace search results view, * replacing the single count histogram. The three charts render side by side as * sibling DBTimeCharts under a shared sync scope, so hovering one shows a - * cross-chart cursor on all three at the same timestamp. + * cross-chart cursor on all three at the same timestamp. The RED/Heatmap switch + * lives in the search stats row (passed in as `mode`); the Heatmap view is the + * same bare heatmap tile the dashboard renders. * * The per-chart aggregations are built by ./traceRedMetrics from the same base * config the histogram uses, so all three honor the active WHERE filter and * selected time range. */ export function TraceRedMetricsChart({ + mode, histogramTimeChartConfig, + heatmapChartConfig, source, isReady, queryKeyPrefix, @@ -48,8 +64,12 @@ export function TraceRedMetricsChart({ onTimeRangeSelect, onFocusSeries, }: { + /** RED vs heatmap; owned by the search stats row so the switch sits inline. */ + mode: TraceChartMode; /** The count-histogram config; RED charts spread this and swap only select. */ histogramTimeChartConfig: BuilderChartConfigWithDateRange; + /** Base config for the heatmap tile, mirroring the delta-mode callsite. */ + heatmapChartConfig: BuilderChartConfigWithDateRange; source: TTraceSource; isReady: boolean; /** Query-key prefix for the auxiliary Errors/Duration tiles, kept separate so @@ -86,6 +106,35 @@ export function TraceRedMetricsChart({ [base, durationExpression], ); + // The heatmap plots getDurationMsExpression (the source's duration already + // scaled to ms by its durationPrecision), which is the value + // HEATMAP_DURATION_NUMBER_FORMAT is paired with. + const durationMsExpression = getDurationMsExpression(source); + /** + * Heatmap tile query (duration distribution over time), matching the + * dashboard heatmap tile: no significant-fields comparison panel. The value, + * count and scale are fixed here rather than read from the delta view's + * settings drawer, so this stays a plain duration heatmap independent of + * that view's query state. + * + * @source packages/app/src/components/Search/DBSearchHeatmapChart.tsx (tile query) + */ + const heatmapQuery = useMemo( + () => + toHeatmapQuery({ + ...heatmapChartConfig, + select: [ + { + valueExpression: durationMsExpression, + countExpression: 'count()', + heatmapScaleType: 'log', + }, + ], + numberFormat: HEATMAP_DURATION_NUMBER_FORMAT, + }), + [heatmapChartConfig, durationMsExpression], + ); + const errorsModeControl = ( + + + ); + } + return ( From 75c193c25fab2545ecd24d3e853596d3c517d32d Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:24:43 +0000 Subject: [PATCH 02/15] fix(app): keep live tail off under the trace heatmap The live-tail pin only ran when the heatmap first appeared, so Resume Live Tail (or the TimePicker's Live option) turned live tail back on while the heatmap was still showing, and every tick rebuilt the chart. - Hide the TimePicker's Live option and the Resume Live Tail button while the heatmap is the visible chart, the way delta and pattern modes hide them, and make the guard check isLive so any other path that turns live tail on (a relative range pick) is switched off again. - Move the source-change reset and the live-tail guard into useTraceChartModeGuards, with tests for first load, a real source switch, and resuming live tail under the heatmap. - Drop the @source tag on the heatmap query in favor of a plain note, and document that queryKeyPrefix only applies to distribution heatmaps. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 47 +++---- .../DBHeatmapChart/DBHeatmapChart.tsx | 2 + .../Search/TraceRedMetricsChart.tsx | 11 +- .../__tests__/useTraceChartModeGuards.test.ts | 133 ++++++++++++++++++ .../Search/useTraceChartModeGuards.ts | 50 +++++++ 5 files changed, 206 insertions(+), 37 deletions(-) create mode 100644 packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts create mode 100644 packages/app/src/components/Search/useTraceChartModeGuards.ts diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 55e6d9041..6f281c13d 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -168,6 +168,7 @@ import { type TraceChartMode, TraceRedMetricsChart, } from './components/Search/TraceRedMetricsChart'; +import { useTraceChartModeGuards } from './components/Search/useTraceChartModeGuards'; import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from './components/SourceSchemaPreview'; @@ -2076,23 +2077,6 @@ function DBSearchPageContent() { ? searchedSource : null; - // Reset to the default RED view when the source actually changes, so - // returning to a trace source after viewing another one doesn't silently - // reopen in Heatmap. The ref starts undefined and is only compared once a - // real id has been seen, so the async source resolution on first load - // (undefined -> id) doesn't count as a change and a shared link that pins - // ?traceChartMode=heatmap survives. - const prevSourceIdRef = useRef(undefined); - useEffect(() => { - if ( - prevSourceIdRef.current !== undefined && - prevSourceIdRef.current !== searchedSource?.id - ) { - setTraceChartMode('red'); - } - prevSourceIdRef.current = searchedSource?.id; - }, [searchedSource?.id, setTraceChartMode]); - const histogramTimeChartConfig = useMemo(() => { if (chartConfig == null) { return undefined; @@ -2180,24 +2164,24 @@ function DBSearchPageContent() { [chartConfig, searchedTimeRange, aliasWith], ); - // Pin live tail off while the heatmap is the visible chart. A live tick - // moves the absolute time range, and the heatmap keys its uPlot instance on - // the chart config, so every refresh would tear the chart down and rebuild - // it with a recomputed y-axis instead of updating in place. Delta and - // pattern modes already pin it off, so the delta-view heatmap never hit - // this; results mode defaults to live, so the view has to opt out for - // itself. Only pinned while the heatmap is actually rendered, so a stale + // Live tail stays off while the heatmap is the visible chart, the way delta + // and pattern modes keep it off: the guard below turns it off, and the + // TimePicker's Live option and the Resume Live Tail button are hidden. + // Results mode defaults to live, so this view has to opt out for itself. + // Only while the heatmap is actually rendered, so a stale // ?traceChartMode=heatmap on a source that shows the histogram can't disable // live tail. const isHeatmapChartVisible = analysisMode === 'results' && traceChartsSource != null && traceChartMode === 'heatmap'; - useEffect(() => { - if (isHeatmapChartVisible) { - setIsLive(false); - } - }, [isHeatmapChartVisible, setIsLive]); + useTraceChartModeGuards({ + sourceId: searchedSource?.id, + setTraceChartMode, + isHeatmapChartVisible, + isLive, + setIsLive, + }); const histogramGroupBySelect = ( )} {shouldShowLiveModeHint && - denoiseResults != true && ( + denoiseResults != true && + !isHeatmapChartVisible && ( diff --git a/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx b/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx index 29d24edd8..edc0d9f8a 100644 --- a/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx +++ b/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx @@ -28,6 +28,8 @@ type DistributionOnlyProps = { /** * Namespaces the distribution heatmap's bounds and bucket queries (see * `useHeatmapData`), matching `DBTimeChart`'s prop of the same name. + * Distribution mode only, like the drag-select props above: the series, + * calculated and histogram modes ignore it and keep their unprefixed keys. */ queryKeyPrefix?: string; }; diff --git a/packages/app/src/components/Search/TraceRedMetricsChart.tsx b/packages/app/src/components/Search/TraceRedMetricsChart.tsx index cd93109fd..71bdb6f08 100644 --- a/packages/app/src/components/Search/TraceRedMetricsChart.tsx +++ b/packages/app/src/components/Search/TraceRedMetricsChart.tsx @@ -112,12 +112,11 @@ export function TraceRedMetricsChart({ const durationMsExpression = getDurationMsExpression(source); /** * Heatmap tile query (duration distribution over time), matching the - * dashboard heatmap tile: no significant-fields comparison panel. The value, - * count and scale are fixed here rather than read from the delta view's - * settings drawer, so this stays a plain duration heatmap independent of - * that view's query state. - * - * @source packages/app/src/components/Search/DBSearchHeatmapChart.tsx (tile query) + * dashboard heatmap tile: no significant-fields comparison panel. It is the + * query the delta view's heatmap builds with its default settings, but the + * value, count and scale are fixed here rather than read from that view's + * settings drawer, so this stays a plain duration heatmap independent of the + * delta view's query state. */ const heatmapQuery = useMemo( () => diff --git a/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts b/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts new file mode 100644 index 000000000..15275e9fc --- /dev/null +++ b/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts @@ -0,0 +1,133 @@ +import { renderHook } from '@testing-library/react'; + +import { useTraceChartModeGuards } from '@/components/Search/useTraceChartModeGuards'; + +type Props = { + sourceId: string | undefined; + isHeatmapChartVisible: boolean; + isLive: boolean; +}; + +function renderGuards(initialProps: Props) { + // Stable setters, like the nuqs ones on the search page, so only the + // props under test retrigger the effects. + const setTraceChartMode = jest.fn(); + const setIsLive = jest.fn(); + const hook = renderHook( + (props: Props) => + useTraceChartModeGuards({ ...props, setTraceChartMode, setIsLive }), + { initialProps }, + ); + return { ...hook, setTraceChartMode, setIsLive }; +} + +describe('useTraceChartModeGuards', () => { + describe('source change', () => { + it('keeps the mode when the source first resolves', () => { + const { rerender, setTraceChartMode } = renderGuards({ + sourceId: undefined, + isHeatmapChartVisible: false, + isLive: false, + }); + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: false, + }); + + expect(setTraceChartMode).not.toHaveBeenCalled(); + }); + + it('resets to RED when the source changes', () => { + const { rerender, setTraceChartMode } = renderGuards({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: false, + }); + rerender({ + sourceId: 'logs', + isHeatmapChartVisible: false, + isLive: false, + }); + + expect(setTraceChartMode).toHaveBeenCalledTimes(1); + expect(setTraceChartMode).toHaveBeenCalledWith('red'); + }); + + it('does not reset on a re-render with the same source', () => { + const { rerender, setTraceChartMode } = renderGuards({ + sourceId: 'traces', + isHeatmapChartVisible: false, + isLive: true, + }); + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: true, + }); + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: false, + }); + + expect(setTraceChartMode).not.toHaveBeenCalled(); + }); + }); + + describe('live tail', () => { + it('turns live tail off when the heatmap becomes visible', () => { + const { rerender, setIsLive } = renderGuards({ + sourceId: 'traces', + isHeatmapChartVisible: false, + isLive: true, + }); + expect(setIsLive).not.toHaveBeenCalled(); + + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: true, + }); + expect(setIsLive).toHaveBeenCalledTimes(1); + expect(setIsLive).toHaveBeenCalledWith(false); + }); + + it('turns live tail off again when it is resumed under the heatmap', () => { + const { rerender, setIsLive } = renderGuards({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: false, + }); + expect(setIsLive).not.toHaveBeenCalled(); + + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: true, + isLive: true, + }); + expect(setIsLive).toHaveBeenCalledTimes(1); + expect(setIsLive).toHaveBeenCalledWith(false); + }); + + it('leaves live tail alone while the RED view is showing', () => { + const { rerender, setIsLive } = renderGuards({ + sourceId: 'traces', + isHeatmapChartVisible: false, + isLive: true, + }); + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: false, + isLive: false, + }); + rerender({ + sourceId: 'traces', + isHeatmapChartVisible: false, + isLive: true, + }); + + expect(setIsLive).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/app/src/components/Search/useTraceChartModeGuards.ts b/packages/app/src/components/Search/useTraceChartModeGuards.ts new file mode 100644 index 000000000..e2164963d --- /dev/null +++ b/packages/app/src/components/Search/useTraceChartModeGuards.ts @@ -0,0 +1,50 @@ +import { useEffect, useRef } from 'react'; + +import type { TraceChartMode } from './TraceRedMetricsChart'; + +/** + * Keeps the trace RED/Heatmap mode coherent with the rest of the search page. + * + * - Resets to the default RED view when the searched source actually changes, + * so returning to a trace source after viewing another one doesn't silently + * reopen in Heatmap. The ref starts undefined and is only compared once a + * real id has been seen, so the async source resolution on first load + * (undefined -> id) doesn't count as a change and a shared link that pins + * ?traceChartMode=heatmap survives. + * - Keeps live tail off while the heatmap is the visible chart. A live tick + * moves the absolute time range, and the heatmap keys its uPlot instance on + * the chart config, so every refresh would tear the chart down and rebuild + * it with a recomputed y-axis instead of updating in place. `isLive` is part + * of the check, not just the visibility, so live tail turned back on while + * the heatmap is showing (through any control) is switched off again. + */ +export function useTraceChartModeGuards({ + sourceId, + setTraceChartMode, + isHeatmapChartVisible, + isLive, + setIsLive, +}: { + sourceId: string | undefined; + setTraceChartMode: (mode: TraceChartMode) => unknown; + isHeatmapChartVisible: boolean; + isLive: boolean; + setIsLive: (isLive: boolean) => unknown; +}) { + const prevSourceIdRef = useRef(undefined); + useEffect(() => { + if ( + prevSourceIdRef.current !== undefined && + prevSourceIdRef.current !== sourceId + ) { + setTraceChartMode('red'); + } + prevSourceIdRef.current = sourceId; + }, [sourceId, setTraceChartMode]); + + useEffect(() => { + if (isHeatmapChartVisible && isLive) { + setIsLive(false); + } + }, [isHeatmapChartVisible, isLive, setIsLive]); +} From 4918bf561a6fb3dbec878c7b51ce819c66fe302d Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:34:39 +0000 Subject: [PATCH 03/15] fix(app): clear traceChartMode on a source change instead of writing red nuqs 1.x writes an explicitly set default into the URL, so resetting the trace chart mode with 'red' added ?traceChartMode=red on every source switch, log sources included. Clear the param instead; the mode still falls back to RED. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/useTraceChartModeGuards.test.ts | 6 ++++-- .../components/Search/useTraceChartModeGuards.ts | 15 +++++++++------ 2 files changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts b/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts index 15275e9fc..f0240aa93 100644 --- a/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts +++ b/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts @@ -38,7 +38,9 @@ describe('useTraceChartModeGuards', () => { expect(setTraceChartMode).not.toHaveBeenCalled(); }); - it('resets to RED when the source changes', () => { + // null clears the param, so the URL falls back to the RED default instead + // of carrying ?traceChartMode=red after every source switch. + it('resets to RED by clearing the param when the source changes', () => { const { rerender, setTraceChartMode } = renderGuards({ sourceId: 'traces', isHeatmapChartVisible: true, @@ -51,7 +53,7 @@ describe('useTraceChartModeGuards', () => { }); expect(setTraceChartMode).toHaveBeenCalledTimes(1); - expect(setTraceChartMode).toHaveBeenCalledWith('red'); + expect(setTraceChartMode).toHaveBeenCalledWith(null); }); it('does not reset on a re-render with the same source', () => { diff --git a/packages/app/src/components/Search/useTraceChartModeGuards.ts b/packages/app/src/components/Search/useTraceChartModeGuards.ts index e2164963d..f7416aff6 100644 --- a/packages/app/src/components/Search/useTraceChartModeGuards.ts +++ b/packages/app/src/components/Search/useTraceChartModeGuards.ts @@ -7,10 +7,13 @@ import type { TraceChartMode } from './TraceRedMetricsChart'; * * - Resets to the default RED view when the searched source actually changes, * so returning to a trace source after viewing another one doesn't silently - * reopen in Heatmap. The ref starts undefined and is only compared once a - * real id has been seen, so the async source resolution on first load - * (undefined -> id) doesn't count as a change and a shared link that pins - * ?traceChartMode=heatmap survives. + * reopen in Heatmap (and turn live tail off again). It clears the param + * rather than setting 'red', since nuqs 1.x writes an explicitly set default + * into the URL and every source switch would add ?traceChartMode=red. The + * ref starts undefined and is only compared once a real id has been seen, + * so the async source resolution on first load (undefined -> id) doesn't + * count as a change and a shared link that pins ?traceChartMode=heatmap + * survives. * - Keeps live tail off while the heatmap is the visible chart. A live tick * moves the absolute time range, and the heatmap keys its uPlot instance on * the chart config, so every refresh would tear the chart down and rebuild @@ -26,7 +29,7 @@ export function useTraceChartModeGuards({ setIsLive, }: { sourceId: string | undefined; - setTraceChartMode: (mode: TraceChartMode) => unknown; + setTraceChartMode: (mode: TraceChartMode | null) => unknown; isHeatmapChartVisible: boolean; isLive: boolean; setIsLive: (isLive: boolean) => unknown; @@ -37,7 +40,7 @@ export function useTraceChartModeGuards({ prevSourceIdRef.current !== undefined && prevSourceIdRef.current !== sourceId ) { - setTraceChartMode('red'); + setTraceChartMode(null); } prevSourceIdRef.current = sourceId; }, [sourceId, setTraceChartMode]); From 8b071586e90a7cd7061ed74ffe2fbc7ebfa87de1 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 02:45:33 +0000 Subject: [PATCH 04/15] fix(app): derive the trace chart mode type from one list of modes The mode union lived in TraceRedMetricsChart and a hand-written copy in the URL parser, so a mode added to the type alone would compile but parse back to RED. Export TRACE_CHART_MODES, derive TraceChartMode from it, and use it in the parser and the view switch. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 8 +++++--- .../app/src/components/Search/TraceRedMetricsChart.tsx | 8 +++++++- 2 files changed, 12 insertions(+), 4 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 6f281c13d..05b28024c 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -165,7 +165,7 @@ import PatternTable from './components/PatternTable'; import { DBSearchHeatmapChart } from './components/Search/DBSearchHeatmapChart'; import DirectTraceSidePanel from './components/Search/DirectTraceSidePanel'; import { - type TraceChartMode, + TRACE_CHART_MODES, TraceRedMetricsChart, } from './components/Search/TraceRedMetricsChart'; import { useTraceChartModeGuards } from './components/Search/useTraceChartModeGuards'; @@ -1136,7 +1136,7 @@ function DBSearchPageContent() { // chosen view; the switch lives inline in the search stats row. const [traceChartMode, setTraceChartMode] = useQueryState( 'traceChartMode', - parseAsStringEnum(['red', 'heatmap']).withDefault('red'), + parseAsStringEnum([...TRACE_CHART_MODES]).withDefault('red'), ); // URL-only, not saved with the search: null uses the source default. @@ -2984,7 +2984,9 @@ function DBSearchPageContent() { value={traceChartMode} onChange={v => setTraceChartMode( - v === 'heatmap' ? 'heatmap' : 'red', + TRACE_CHART_MODES.find( + mode => mode === v, + ) ?? 'red', ) } data={[ diff --git a/packages/app/src/components/Search/TraceRedMetricsChart.tsx b/packages/app/src/components/Search/TraceRedMetricsChart.tsx index 71bdb6f08..5a0092891 100644 --- a/packages/app/src/components/Search/TraceRedMetricsChart.tsx +++ b/packages/app/src/components/Search/TraceRedMetricsChart.tsx @@ -23,7 +23,13 @@ import { redBaseConfig, } from './traceRedMetrics'; -export type TraceChartMode = 'red' | 'heatmap'; +/** + * The trace results chart views, RED first as the default. The URL parser and + * the view switch both read this list, so a new mode can't be added to the type + * alone and silently parse back to RED. + */ +export const TRACE_CHART_MODES = ['red', 'heatmap'] as const; +export type TraceChartMode = (typeof TRACE_CHART_MODES)[number]; // Each RED tile is a ChartCard flex child that fills its column; ChartCard // supplies the dashboard-tile chrome (border, background, full-bleed header From cfcd014d7efef0f99b3d59c7db146c1ebefc09b7 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:18:08 +0000 Subject: [PATCH 05/15] fix(app): drop the heatmap query-key prefix The prefix let live tail wait on the heatmap queries, but live tail is always off while the heatmap is the visible chart, so it never changed anything. It did give these queries different keys from the identical delta-view heatmap. Without it, DBHeatmapChart and useHeatmapData go back to their current shape. Co-Authored-By: Claude Opus 5.5 --- .../DBHeatmapChart/DBHeatmapChart.tsx | 11 ------- .../__tests__/useHeatmapData.test.ts | 33 ------------------- .../DBHeatmapChart/useHeatmapData.ts | 13 ++------ .../Search/TraceRedMetricsChart.tsx | 1 - 4 files changed, 2 insertions(+), 56 deletions(-) diff --git a/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx b/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx index edc0d9f8a..1a95856dd 100644 --- a/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx +++ b/packages/app/src/components/DBHeatmapChart/DBHeatmapChart.tsx @@ -25,13 +25,6 @@ type DistributionOnlyProps = { * this is purely a visual mirror of that state. */ selectionBounds?: SelectionBounds | null; - /** - * Namespaces the distribution heatmap's bounds and bucket queries (see - * `useHeatmapData`), matching `DBTimeChart`'s prop of the same name. - * Distribution mode only, like the drag-select props above: the series, - * calculated and histogram modes ignore it and keep their unprefixed keys. - */ - queryKeyPrefix?: string; }; type DBHeatmapChartProps = HeatmapChartViewProps & @@ -44,7 +37,6 @@ function DistributionHeatmapChart({ query, enabled, onFilter, - queryKeyPrefix, ...viewProps }: HeatmapChartViewProps & DistributionOnlyProps & { query: DistributionQuery; enabled: boolean }) { @@ -52,7 +44,6 @@ function DistributionHeatmapChart({ config: query.config, scaleType: query.scaleType, enabled, - queryKeyPrefix, }); const { view } = data; @@ -147,7 +138,6 @@ function DBHeatmapChart({ onFilter, onClearFilter, selectionBounds, - queryKeyPrefix, ...viewProps }: DBHeatmapChartProps) { if (query.mode === 'series') { @@ -173,7 +163,6 @@ function DBHeatmapChart({ onFilter={onFilter} onClearFilter={onClearFilter} selectionBounds={selectionBounds} - queryKeyPrefix={queryKeyPrefix} /> ); } diff --git a/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts b/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts index 188fa929a..87a5b3950 100644 --- a/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts +++ b/packages/app/src/components/DBHeatmapChart/__tests__/useHeatmapData.test.ts @@ -132,37 +132,4 @@ describe('useHeatmapData', () => { expect(boundsQuery.dateRange).toEqual(dateRange); expect(bucketQuery.dateRange).toEqual(dateRange); }); - - describe('queryKeyPrefix', () => { - const queryKeys = (queryKeyPrefix?: string) => { - const query = toHeatmapQuery(traceConfig); - if (query.mode !== 'distribution') { - throw new Error('Expected distribution'); - } - renderHook(() => - useHeatmapData({ - config: query.config, - scaleType: query.scaleType, - enabled: true, - queryKeyPrefix, - }), - ); - return mockUseQueriedChartConfig.mock.calls.map( - ([, options]) => options?.queryKey, - ); - }; - - it('leaves both query keys unchanged when omitted', () => { - const keys = queryKeys(); - expect(keys.map(key => key?.[0])).toEqual(['heatmap', 'heatmap_bucket']); - }); - - it('prepends the prefix to both query keys, like DBTimeChart', () => { - const keys = queryKeys('search-red'); - expect(keys.map(key => key?.slice(0, 2))).toEqual([ - ['search-red', 'heatmap'], - ['search-red', 'heatmap_bucket'], - ]); - }); - }); }); diff --git a/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts b/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts index 1e3b36da2..b90345f8a 100644 --- a/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts +++ b/packages/app/src/components/DBHeatmapChart/useHeatmapData.ts @@ -31,20 +31,11 @@ export function useHeatmapData({ config, scaleType, enabled, - queryKeyPrefix, }: { config: HeatmapChartConfig; scaleType: HeatmapScaleType; enabled: boolean; - /** - * Prepended to both query keys, matching `DBTimeChart`'s prop of the same - * name, so a caller that gates on `useIsFetching` for its sibling charts - * (the search page pausing live tail) also waits on these queries. Keys are - * unchanged when omitted. - */ - queryKeyPrefix?: string; }): HeatmapData { - const keyPrefix = queryKeyPrefix != null ? [queryKeyPrefix] : []; const { granularity, generatedTsBuckets } = useHeatmapTimeBuckets({ dateRange: config.dateRange, granularity: config.granularity, @@ -65,7 +56,7 @@ export function useHeatmapData({ isPlaceholderData: isMinMaxPlaceholderData, error: minMaxError, } = useQueriedChartConfig(minMaxConfig, { - queryKey: [...keyPrefix, 'heatmap', minMaxConfig], + queryKey: ['heatmap', minMaxConfig], enabled, placeholderData: prev => prev, }); @@ -90,7 +81,7 @@ export function useHeatmapData({ const { data, isLoading, isPlaceholderData, error } = useQueriedChartConfig( bucketConfig, { - queryKey: [...keyPrefix, 'heatmap_bucket', bucketConfig], + queryKey: ['heatmap_bucket', bucketConfig], // Wait for fresh bounds, so a refresh doesn't also query the new range // bucketed with the previous range's min/max. enabled: enabled && canQueryBuckets && !isMinMaxPlaceholderData, diff --git a/packages/app/src/components/Search/TraceRedMetricsChart.tsx b/packages/app/src/components/Search/TraceRedMetricsChart.tsx index 5a0092891..689913e19 100644 --- a/packages/app/src/components/Search/TraceRedMetricsChart.tsx +++ b/packages/app/src/components/Search/TraceRedMetricsChart.tsx @@ -178,7 +178,6 @@ export function TraceRedMetricsChart({ From 21d2698b094e983932215335b708aa0e5a5bf77b Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:18:17 +0000 Subject: [PATCH 06/15] fix(app): reset the trace chart mode only when the user picks a source The reset ran in an effect on the searched source id, so it also fired when Back or Forward restored a URL with traceChartMode=heatmap, and rewrote that history entry back to RED. Clear the mode in the page's existing user-source-change branch instead, which catch-up (history navigation, a source name resolving) already skips. The hook keeps only the live-tail guard, renamed useHeatmapLiveTailGuard. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 18 +-- .../__tests__/useHeatmapLiveTailGuard.test.ts | 56 ++++++++ .../__tests__/useTraceChartModeGuards.test.ts | 135 ------------------ .../Search/useHeatmapLiveTailGuard.ts | 26 ++++ .../Search/useTraceChartModeGuards.ts | 53 ------- 5 files changed, 92 insertions(+), 196 deletions(-) create mode 100644 packages/app/src/components/Search/__tests__/useHeatmapLiveTailGuard.test.ts delete mode 100644 packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts create mode 100644 packages/app/src/components/Search/useHeatmapLiveTailGuard.ts delete mode 100644 packages/app/src/components/Search/useTraceChartModeGuards.ts diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 05b28024c..1c2e8dda4 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -168,7 +168,7 @@ import { TRACE_CHART_MODES, TraceRedMetricsChart, } from './components/Search/TraceRedMetricsChart'; -import { useTraceChartModeGuards } from './components/Search/useTraceChartModeGuards'; +import { useHeatmapLiveTailGuard } from './components/Search/useHeatmapLiveTailGuard'; import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from './components/SourceSchemaPreview'; @@ -1565,6 +1565,13 @@ function DBSearchPageContent() { // a freshly loaded page pushes its defaults into the search config. if (!isCatchingUpToConfig) { pendingGroupByReconcileRef.current = watchedSource ?? null; + // The RED/Heatmap choice was made for the previous source, so a source + // the user picks opens in the default RED view, and coming back to a + // trace source doesn't silently reopen the heatmap (and turn live tail + // off again). Cleared rather than set to 'red': nuqs 1.x writes an + // explicit default into the URL. Catch-up skips this branch, so + // Back/Forward keeps the mode the URL restores. + setTraceChartMode(null); // If the user isn't in a saved search (or the source is different from the saved search source), reset fields if (savedSearchId == null || savedSearch?.source !== watchedSource) { setValue('select', ''); @@ -1595,6 +1602,7 @@ function DBSearchPageContent() { searchedSource?.id, rawSearchedConfig.source, setSearchedConfig, + setTraceChartMode, ]); const retainCompatibleFiltersAndGroupBy = useStableCallback( @@ -2175,13 +2183,7 @@ function DBSearchPageContent() { analysisMode === 'results' && traceChartsSource != null && traceChartMode === 'heatmap'; - useTraceChartModeGuards({ - sourceId: searchedSource?.id, - setTraceChartMode, - isHeatmapChartVisible, - isLive, - setIsLive, - }); + useHeatmapLiveTailGuard({ isHeatmapChartVisible, isLive, setIsLive }); const histogramGroupBySelect = ( useHeatmapLiveTailGuard({ ...props, setIsLive }), + { initialProps }, + ); + return { ...hook, setIsLive }; +} + +describe('useHeatmapLiveTailGuard', () => { + it('turns live tail off when the heatmap becomes visible', () => { + const { rerender, setIsLive } = renderGuard({ + isHeatmapChartVisible: false, + isLive: true, + }); + expect(setIsLive).not.toHaveBeenCalled(); + + rerender({ isHeatmapChartVisible: true, isLive: true }); + expect(setIsLive).toHaveBeenCalledTimes(1); + expect(setIsLive).toHaveBeenCalledWith(false); + }); + + it('turns live tail off again when it is resumed under the heatmap', () => { + const { rerender, setIsLive } = renderGuard({ + isHeatmapChartVisible: true, + isLive: false, + }); + expect(setIsLive).not.toHaveBeenCalled(); + + rerender({ isHeatmapChartVisible: true, isLive: true }); + expect(setIsLive).toHaveBeenCalledTimes(1); + expect(setIsLive).toHaveBeenCalledWith(false); + }); + + it('leaves live tail alone while the RED view is showing', () => { + const { rerender, setIsLive } = renderGuard({ + isHeatmapChartVisible: false, + isLive: true, + }); + rerender({ isHeatmapChartVisible: false, isLive: false }); + rerender({ isHeatmapChartVisible: false, isLive: true }); + + expect(setIsLive).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts b/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts deleted file mode 100644 index f0240aa93..000000000 --- a/packages/app/src/components/Search/__tests__/useTraceChartModeGuards.test.ts +++ /dev/null @@ -1,135 +0,0 @@ -import { renderHook } from '@testing-library/react'; - -import { useTraceChartModeGuards } from '@/components/Search/useTraceChartModeGuards'; - -type Props = { - sourceId: string | undefined; - isHeatmapChartVisible: boolean; - isLive: boolean; -}; - -function renderGuards(initialProps: Props) { - // Stable setters, like the nuqs ones on the search page, so only the - // props under test retrigger the effects. - const setTraceChartMode = jest.fn(); - const setIsLive = jest.fn(); - const hook = renderHook( - (props: Props) => - useTraceChartModeGuards({ ...props, setTraceChartMode, setIsLive }), - { initialProps }, - ); - return { ...hook, setTraceChartMode, setIsLive }; -} - -describe('useTraceChartModeGuards', () => { - describe('source change', () => { - it('keeps the mode when the source first resolves', () => { - const { rerender, setTraceChartMode } = renderGuards({ - sourceId: undefined, - isHeatmapChartVisible: false, - isLive: false, - }); - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: false, - }); - - expect(setTraceChartMode).not.toHaveBeenCalled(); - }); - - // null clears the param, so the URL falls back to the RED default instead - // of carrying ?traceChartMode=red after every source switch. - it('resets to RED by clearing the param when the source changes', () => { - const { rerender, setTraceChartMode } = renderGuards({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: false, - }); - rerender({ - sourceId: 'logs', - isHeatmapChartVisible: false, - isLive: false, - }); - - expect(setTraceChartMode).toHaveBeenCalledTimes(1); - expect(setTraceChartMode).toHaveBeenCalledWith(null); - }); - - it('does not reset on a re-render with the same source', () => { - const { rerender, setTraceChartMode } = renderGuards({ - sourceId: 'traces', - isHeatmapChartVisible: false, - isLive: true, - }); - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: true, - }); - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: false, - }); - - expect(setTraceChartMode).not.toHaveBeenCalled(); - }); - }); - - describe('live tail', () => { - it('turns live tail off when the heatmap becomes visible', () => { - const { rerender, setIsLive } = renderGuards({ - sourceId: 'traces', - isHeatmapChartVisible: false, - isLive: true, - }); - expect(setIsLive).not.toHaveBeenCalled(); - - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: true, - }); - expect(setIsLive).toHaveBeenCalledTimes(1); - expect(setIsLive).toHaveBeenCalledWith(false); - }); - - it('turns live tail off again when it is resumed under the heatmap', () => { - const { rerender, setIsLive } = renderGuards({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: false, - }); - expect(setIsLive).not.toHaveBeenCalled(); - - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: true, - isLive: true, - }); - expect(setIsLive).toHaveBeenCalledTimes(1); - expect(setIsLive).toHaveBeenCalledWith(false); - }); - - it('leaves live tail alone while the RED view is showing', () => { - const { rerender, setIsLive } = renderGuards({ - sourceId: 'traces', - isHeatmapChartVisible: false, - isLive: true, - }); - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: false, - isLive: false, - }); - rerender({ - sourceId: 'traces', - isHeatmapChartVisible: false, - isLive: true, - }); - - expect(setIsLive).not.toHaveBeenCalled(); - }); - }); -}); diff --git a/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts b/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts new file mode 100644 index 000000000..db2b4b42e --- /dev/null +++ b/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts @@ -0,0 +1,26 @@ +import { useEffect } from 'react'; + +/** + * Keeps live tail off while the trace heatmap is the visible chart, the way + * delta and pattern modes keep it off. A live tick moves the absolute time + * range, and the heatmap keys its uPlot instance on the chart config, so every + * refresh would tear the chart down and rebuild it with a recomputed y-axis + * instead of updating in place. `isLive` is part of the check, not just the + * visibility, so live tail turned back on while the heatmap is showing + * (through any control) is switched off again. + */ +export function useHeatmapLiveTailGuard({ + isHeatmapChartVisible, + isLive, + setIsLive, +}: { + isHeatmapChartVisible: boolean; + isLive: boolean; + setIsLive: (isLive: boolean) => unknown; +}) { + useEffect(() => { + if (isHeatmapChartVisible && isLive) { + setIsLive(false); + } + }, [isHeatmapChartVisible, isLive, setIsLive]); +} diff --git a/packages/app/src/components/Search/useTraceChartModeGuards.ts b/packages/app/src/components/Search/useTraceChartModeGuards.ts deleted file mode 100644 index f7416aff6..000000000 --- a/packages/app/src/components/Search/useTraceChartModeGuards.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { useEffect, useRef } from 'react'; - -import type { TraceChartMode } from './TraceRedMetricsChart'; - -/** - * Keeps the trace RED/Heatmap mode coherent with the rest of the search page. - * - * - Resets to the default RED view when the searched source actually changes, - * so returning to a trace source after viewing another one doesn't silently - * reopen in Heatmap (and turn live tail off again). It clears the param - * rather than setting 'red', since nuqs 1.x writes an explicitly set default - * into the URL and every source switch would add ?traceChartMode=red. The - * ref starts undefined and is only compared once a real id has been seen, - * so the async source resolution on first load (undefined -> id) doesn't - * count as a change and a shared link that pins ?traceChartMode=heatmap - * survives. - * - Keeps live tail off while the heatmap is the visible chart. A live tick - * moves the absolute time range, and the heatmap keys its uPlot instance on - * the chart config, so every refresh would tear the chart down and rebuild - * it with a recomputed y-axis instead of updating in place. `isLive` is part - * of the check, not just the visibility, so live tail turned back on while - * the heatmap is showing (through any control) is switched off again. - */ -export function useTraceChartModeGuards({ - sourceId, - setTraceChartMode, - isHeatmapChartVisible, - isLive, - setIsLive, -}: { - sourceId: string | undefined; - setTraceChartMode: (mode: TraceChartMode | null) => unknown; - isHeatmapChartVisible: boolean; - isLive: boolean; - setIsLive: (isLive: boolean) => unknown; -}) { - const prevSourceIdRef = useRef(undefined); - useEffect(() => { - if ( - prevSourceIdRef.current !== undefined && - prevSourceIdRef.current !== sourceId - ) { - setTraceChartMode(null); - } - prevSourceIdRef.current = sourceId; - }, [sourceId, setTraceChartMode]); - - useEffect(() => { - if (isHeatmapChartVisible && isLive) { - setIsLive(false); - } - }, [isHeatmapChartVisible, isLive, setIsLive]); -} From d2040450fd476cf358d471da09d764b9b46a39b6 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Tue, 17 Nov 2026 03:23:31 +0000 Subject: [PATCH 07/15] fix(app): apply the trace chart mode reset to the new history entry Clearing the mode from the dropdown branch ran before the debounced search submit pushed the new source, so it rewrote the previous history entry, and Back still landed on RED. Mark the reset as pending there, like the filter and group-by reconciles, and clear the mode once the URL points at the new source. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 28 ++++++++++++++++++++-------- 1 file changed, 20 insertions(+), 8 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 1c2e8dda4..ac4ce62d4 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -1474,6 +1474,13 @@ function DBSearchPageContent() { // Same, for the histogram group by. Also set when a saved search switches the // source, since the group by isn't part of the saved search. const pendingGroupByReconcileRef = useRef(null); + // Same, for the trace RED/Heatmap choice, which was made for the previous + // source: a source the user picks opens in the default RED view, so coming + // back to a trace source doesn't silently reopen the heatmap (and turn live + // tail off again). The reset waits until the URL points at the new source, + // so it lands on the new history entry and leaves the previous one intact; + // Back/Forward never set this, so they keep the mode the URL restores. + const pendingTraceChartModeResetRef = useRef(null); const watchedSourceObj = useMemo( () => inputSourceObjs?.find(s => s.id === watchedSource), @@ -1565,13 +1572,7 @@ function DBSearchPageContent() { // a freshly loaded page pushes its defaults into the search config. if (!isCatchingUpToConfig) { pendingGroupByReconcileRef.current = watchedSource ?? null; - // The RED/Heatmap choice was made for the previous source, so a source - // the user picks opens in the default RED view, and coming back to a - // trace source doesn't silently reopen the heatmap (and turn live tail - // off again). Cleared rather than set to 'red': nuqs 1.x writes an - // explicit default into the URL. Catch-up skips this branch, so - // Back/Forward keeps the mode the URL restores. - setTraceChartMode(null); + pendingTraceChartModeResetRef.current = watchedSource ?? null; // If the user isn't in a saved search (or the source is different from the saved search source), reset fields if (savedSearchId == null || savedSearch?.source !== watchedSource) { setValue('select', ''); @@ -1602,9 +1603,20 @@ function DBSearchPageContent() { searchedSource?.id, rawSearchedConfig.source, setSearchedConfig, - setTraceChartMode, ]); + useEffect(() => { + if ( + pendingTraceChartModeResetRef.current != null && + pendingTraceChartModeResetRef.current === searchedSource?.id + ) { + pendingTraceChartModeResetRef.current = null; + // Cleared rather than set to 'red': nuqs 1.x writes an explicit default + // into the URL. + setTraceChartMode(null); + } + }, [searchedSource?.id, setTraceChartMode]); + const retainCompatibleFiltersAndGroupBy = useStableCallback( (columns: ColumnMeta[]) => { const allowed = new Set(columns.map(c => c.name)); From 2473a2e3a627bdcb14c82397efe2f884ea27abf0 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:44:16 +0000 Subject: [PATCH 08/15] fix(app): keep the trace heatmap in place when the results are sorted The heatmap config carried the results table's orderBy. The heatmap's own queries don't use it, but the chart keys its uPlot instance on the config, so sorting a column tore the heatmap down and rebuilt it. Drop the sort from the base config, as the histogram config does. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index ac4ce62d4..0527b52bc 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2171,13 +2171,16 @@ function DBSearchPageContent() { // Base config for the trace heatmap tile, mirroring the delta-mode heatmap: // the search's chart config over the searched range, carrying the source's // select-alias definitions. Memoized so the tile's query stays stable across - // re-renders. + // re-renders. The results table's sort is dropped, as for the histogram: the + // heatmap's own queries don't use it, but the chart keys its uPlot instance on + // the config, so sorting a column would otherwise rebuild the heatmap. const traceHeatmapChartConfig = useMemo( () => chartConfig == null ? undefined : ({ ...chartConfig, + orderBy: undefined, dateRange: searchedTimeRange, with: aliasWith, } satisfies BuilderChartConfigWithDateRange), From 5a4294c09120ea7e64aafdf56950386ca0416497 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:44:24 +0000 Subject: [PATCH 09/15] fix(app): hide the group-by picker while the trace heatmap shows The heatmap doesn't group, but the picker stayed in the stats row, and picking a custom group-by swapped the heatmap and the RED/Heatmap switch for the histogram with no hint why. Hide the picker while the heatmap is the visible chart; it comes back on the RED view. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 0527b52bc..cffbef19a 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2992,7 +2992,13 @@ function DBSearchPageContent() { totalCountConfig={totalCountConfig} enableParallelQueries > - {histogramGroupBySelect} + {/* The heatmap doesn't group, and a custom + group-by would swap it for the histogram (see + traceChartsSource), so the picker is hidden + while it shows. */} + {isHeatmapChartVisible + ? null + : histogramGroupBySelect} {traceChartsSource != null && ( From 520d3ef11ba44765b84d45baa039f7a3895844ad Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 02:56:31 +0000 Subject: [PATCH 10/15] fix(app): drop the pending trace chart mode reset when a pick is undone Picking a source arms a reset that fires once the URL points at it. If the user re-selected the searched source before that search ran, the reset stayed armed for the abandoned source, so a later navigation to it with traceChartMode=heatmap cleared the mode it meant to restore. Clear it whenever the form catches up to the searched source. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index cffbef19a..e56869585 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -1547,6 +1547,13 @@ function DBSearchPageContent() { const isCatchingUpToConfig = !!watchedSource && watchedSource === searchedSource?.id; + // Re-selecting the searched source before a pick's search ran undoes that + // pick, so drop the trace chart mode reset it armed. Left set, it would + // fire on a later navigation to the abandoned source. + if (isCatchingUpToConfig) { + pendingTraceChartModeResetRef.current = null; + } + if (isCatchingUpToConfig && savedSearchId == null) { prevSourceRef.current = watchedSource; if (rawSearchedConfig.source !== watchedSource) { From fa48608353262afe5e91ba7eba823125d97f9275 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:10:06 +0000 Subject: [PATCH 11/15] fix(app): treat the trace heatmap as visible only when it renders isHeatmapChartVisible ignored the chart branch's other conditions, so while the chart config was resolving or a query error hid the chart area, it still kept live tail off and hid the Live option, Resume Live Tail and the group-by picker. Derive it from the same conditions the chart branch uses. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index e56869585..8fcf4dff9 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2198,13 +2198,16 @@ function DBSearchPageContent() { // and pattern modes keep it off: the guard below turns it off, and the // TimePicker's Live option and the Resume Live Tail button are hidden. // Results mode defaults to live, so this view has to opt out for itself. - // Only while the heatmap is actually rendered, so a stale - // ?traceChartMode=heatmap on a source that shows the histogram can't disable - // live tail. + // Only while the heatmap is actually rendered (the same conditions as the + // chart branch below), so a stale ?traceChartMode=heatmap on a source that + // shows the histogram, or a query error that hides the chart area, can't + // disable live tail or hide its controls. const isHeatmapChartVisible = analysisMode === 'results' && traceChartsSource != null && - traceChartMode === 'heatmap'; + traceChartMode === 'heatmap' && + traceHeatmapChartConfig != null && + !hasQueryError; useHeatmapLiveTailGuard({ isHeatmapChartVisible, isLive, setIsLive }); const histogramGroupBySelect = ( From f9b80acefba0ad0f3ab209f82cea8b58ffb518dc Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:20:50 +0000 Subject: [PATCH 12/15] refactor(app): move the trace chart mode reset into a tested hook The reset that clears traceChartMode after a source pick lived inline in DBSearchPage as a ref and an effect, with no tests, and it needed several follow-up fixes. Move it into useTraceChartModeReset, which the page arms on a user pick and disarms when the pick is undone, and test the cases those fixes were about: it fires only once the searched source reaches the pick, once per pick, never for Back/Forward, not after an undone pick, and for the latest pick. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 36 ++++---- .../__tests__/useTraceChartModeReset.test.ts | 82 +++++++++++++++++++ .../Search/useTraceChartModeReset.ts | 47 +++++++++++ 3 files changed, 143 insertions(+), 22 deletions(-) create mode 100644 packages/app/src/components/Search/__tests__/useTraceChartModeReset.test.ts create mode 100644 packages/app/src/components/Search/useTraceChartModeReset.ts diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 8fcf4dff9..42cfb2d23 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -169,6 +169,7 @@ import { TraceRedMetricsChart, } from './components/Search/TraceRedMetricsChart'; import { useHeatmapLiveTailGuard } from './components/Search/useHeatmapLiveTailGuard'; +import { useTraceChartModeReset } from './components/Search/useTraceChartModeReset'; import SourceSchemaPreview, { isSourceSchemaPreviewEnabled, } from './components/SourceSchemaPreview'; @@ -1474,13 +1475,14 @@ function DBSearchPageContent() { // Same, for the histogram group by. Also set when a saved search switches the // source, since the group by isn't part of the saved search. const pendingGroupByReconcileRef = useRef(null); - // Same, for the trace RED/Heatmap choice, which was made for the previous - // source: a source the user picks opens in the default RED view, so coming - // back to a trace source doesn't silently reopen the heatmap (and turn live - // tail off again). The reset waits until the URL points at the new source, - // so it lands on the new history entry and leaves the previous one intact; - // Back/Forward never set this, so they keep the mode the URL restores. - const pendingTraceChartModeResetRef = useRef(null); + // Same, for the trace RED/Heatmap choice: a source the user picks opens in + // the default RED view once the URL points at it (see + // useTraceChartModeReset). + const { arm: armTraceChartModeReset, disarm: disarmTraceChartModeReset } = + useTraceChartModeReset({ + searchedSourceId: searchedSource?.id, + setTraceChartMode, + }); const watchedSourceObj = useMemo( () => inputSourceObjs?.find(s => s.id === watchedSource), @@ -1548,10 +1550,10 @@ function DBSearchPageContent() { !!watchedSource && watchedSource === searchedSource?.id; // Re-selecting the searched source before a pick's search ran undoes that - // pick, so drop the trace chart mode reset it armed. Left set, it would + // pick, so drop the trace chart mode reset it armed. Left armed, it would // fire on a later navigation to the abandoned source. if (isCatchingUpToConfig) { - pendingTraceChartModeResetRef.current = null; + disarmTraceChartModeReset(); } if (isCatchingUpToConfig && savedSearchId == null) { @@ -1579,7 +1581,7 @@ function DBSearchPageContent() { // a freshly loaded page pushes its defaults into the search config. if (!isCatchingUpToConfig) { pendingGroupByReconcileRef.current = watchedSource ?? null; - pendingTraceChartModeResetRef.current = watchedSource ?? null; + armTraceChartModeReset(watchedSource ?? null); // If the user isn't in a saved search (or the source is different from the saved search source), reset fields if (savedSearchId == null || savedSearch?.source !== watchedSource) { setValue('select', ''); @@ -1610,20 +1612,10 @@ function DBSearchPageContent() { searchedSource?.id, rawSearchedConfig.source, setSearchedConfig, + armTraceChartModeReset, + disarmTraceChartModeReset, ]); - useEffect(() => { - if ( - pendingTraceChartModeResetRef.current != null && - pendingTraceChartModeResetRef.current === searchedSource?.id - ) { - pendingTraceChartModeResetRef.current = null; - // Cleared rather than set to 'red': nuqs 1.x writes an explicit default - // into the URL. - setTraceChartMode(null); - } - }, [searchedSource?.id, setTraceChartMode]); - const retainCompatibleFiltersAndGroupBy = useStableCallback( (columns: ColumnMeta[]) => { const allowed = new Set(columns.map(c => c.name)); diff --git a/packages/app/src/components/Search/__tests__/useTraceChartModeReset.test.ts b/packages/app/src/components/Search/__tests__/useTraceChartModeReset.test.ts new file mode 100644 index 000000000..1ed7097e2 --- /dev/null +++ b/packages/app/src/components/Search/__tests__/useTraceChartModeReset.test.ts @@ -0,0 +1,82 @@ +import { act, renderHook } from '@testing-library/react'; + +import { useTraceChartModeReset } from '@/components/Search/useTraceChartModeReset'; + +type Props = { searchedSourceId: string | undefined }; + +function renderReset(searchedSourceId: string | undefined) { + // A stable setter, like the nuqs one on the search page, so only the + // searched source retriggers the effect. + const setTraceChartMode = jest.fn(); + const hook = renderHook( + ({ searchedSourceId }: Props) => + useTraceChartModeReset({ searchedSourceId, setTraceChartMode }), + { initialProps: { searchedSourceId } }, + ); + return { ...hook, setTraceChartMode }; +} + +describe('useTraceChartModeReset', () => { + it('clears the mode once the searched source reaches the picked source', () => { + const { result, rerender, setTraceChartMode } = renderReset('traces'); + + act(() => result.current.arm('logs')); + // The pick alone doesn't reset: the URL still points at the old source. + rerender({ searchedSourceId: 'traces' }); + expect(setTraceChartMode).not.toHaveBeenCalled(); + + rerender({ searchedSourceId: 'logs' }); + expect(setTraceChartMode).toHaveBeenCalledTimes(1); + expect(setTraceChartMode).toHaveBeenCalledWith(null); + }); + + it('fires once per pick', () => { + const { result, rerender, setTraceChartMode } = renderReset('traces'); + + act(() => result.current.arm('logs')); + rerender({ searchedSourceId: 'logs' }); + rerender({ searchedSourceId: 'traces' }); + rerender({ searchedSourceId: 'logs' }); + + expect(setTraceChartMode).toHaveBeenCalledTimes(1); + }); + + // Back/Forward changes the searched source without a pick, so the mode the + // URL restores stays. + it('leaves source changes it was not armed for alone', () => { + const { rerender, setTraceChartMode } = renderReset('logs'); + + rerender({ searchedSourceId: 'traces' }); + rerender({ searchedSourceId: 'logs' }); + + expect(setTraceChartMode).not.toHaveBeenCalled(); + }); + + // Re-selecting the searched source before the search runs undoes the pick; + // a later navigation to the abandoned source must not trigger the reset. + it('drops an armed reset when the pick is undone', () => { + const { result, rerender, setTraceChartMode } = renderReset('traces'); + + act(() => { + result.current.arm('logs'); + result.current.disarm(); + }); + rerender({ searchedSourceId: 'logs' }); + + expect(setTraceChartMode).not.toHaveBeenCalled(); + }); + + it('follows the latest pick', () => { + const { result, rerender, setTraceChartMode } = renderReset('traces'); + + act(() => { + result.current.arm('logs'); + result.current.arm('sessions'); + }); + rerender({ searchedSourceId: 'logs' }); + expect(setTraceChartMode).not.toHaveBeenCalled(); + + rerender({ searchedSourceId: 'sessions' }); + expect(setTraceChartMode).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/app/src/components/Search/useTraceChartModeReset.ts b/packages/app/src/components/Search/useTraceChartModeReset.ts new file mode 100644 index 000000000..3564f8c5b --- /dev/null +++ b/packages/app/src/components/Search/useTraceChartModeReset.ts @@ -0,0 +1,47 @@ +import { useCallback, useEffect, useRef } from 'react'; + +import type { TraceChartMode } from './TraceRedMetricsChart'; + +/** + * Resets the trace RED/Heatmap choice to the default RED view when the user + * picks a different source. The choice was made for the previous source, so + * coming back to a trace source shouldn't silently reopen the heatmap (and + * turn live tail off again). + * + * The page arms the reset when the user picks a source, and it fires once the + * searched source (from the URL) reaches that source. Resetting at the pick + * itself would rewrite the previous history entry, since the pick runs before + * the debounced search pushes the new source. Back and Forward never arm it, + * so they keep the mode the URL restores, and the page disarms it when the + * user re-selects the searched source before the search runs. The mode is + * cleared rather than set to 'red', since nuqs 1.x writes an explicitly set + * default into the URL. + */ +export function useTraceChartModeReset({ + searchedSourceId, + setTraceChartMode, +}: { + searchedSourceId: string | undefined; + setTraceChartMode: (mode: TraceChartMode | null) => unknown; +}) { + const pendingSourceIdRef = useRef(null); + + useEffect(() => { + if ( + pendingSourceIdRef.current != null && + pendingSourceIdRef.current === searchedSourceId + ) { + pendingSourceIdRef.current = null; + setTraceChartMode(null); + } + }, [searchedSourceId, setTraceChartMode]); + + const arm = useCallback((sourceId: string | null) => { + pendingSourceIdRef.current = sourceId; + }, []); + const disarm = useCallback(() => { + pendingSourceIdRef.current = null; + }, []); + + return { arm, disarm }; +} From b181834f448784c6355487c41d7b790103c5b6c5 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:23:52 +0000 Subject: [PATCH 13/15] chore(app): tighten the trace heatmap comments Condense the comments this PR adds to the reasons a reader needs, and restore one comment it had reworded. No behavior change. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 58 +++++++------------ .../Search/TraceRedMetricsChart.tsx | 25 ++------ .../Search/useHeatmapLiveTailGuard.ts | 11 ++-- .../Search/useTraceChartModeReset.ts | 18 ++---- 4 files changed, 35 insertions(+), 77 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 42cfb2d23..801defa1e 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -1132,9 +1132,8 @@ function DBSearchPageContent() { ]).withDefault('results'), ); - // RED metrics vs heatmap for the trace results chart area. URL state (like - // the other view toggles on this page) so a reload or shared link keeps the - // chosen view; the switch lives inline in the search stats row. + // RED vs heatmap for the trace results chart. URL state, like the page's + // other view toggles, so a reload or shared link keeps the view. const [traceChartMode, setTraceChartMode] = useQueryState( 'traceChartMode', parseAsStringEnum([...TRACE_CHART_MODES]).withDefault('red'), @@ -1475,9 +1474,7 @@ function DBSearchPageContent() { // Same, for the histogram group by. Also set when a saved search switches the // source, since the group by isn't part of the saved search. const pendingGroupByReconcileRef = useRef(null); - // Same, for the trace RED/Heatmap choice: a source the user picks opens in - // the default RED view once the URL points at it (see - // useTraceChartModeReset). + // Same, for the trace RED/Heatmap choice (see useTraceChartModeReset). const { arm: armTraceChartModeReset, disarm: disarmTraceChartModeReset } = useTraceChartModeReset({ searchedSourceId: searchedSource?.id, @@ -1549,9 +1546,7 @@ function DBSearchPageContent() { const isCatchingUpToConfig = !!watchedSource && watchedSource === searchedSource?.id; - // Re-selecting the searched source before a pick's search ran undoes that - // pick, so drop the trace chart mode reset it armed. Left armed, it would - // fire on a later navigation to the abandoned source. + // Re-selecting the searched source undoes a pick whose search hasn't run. if (isCatchingUpToConfig) { disarmTraceChartModeReset(); } @@ -2085,10 +2080,10 @@ function DBSearchPageContent() { const aliasWith = useMemo(() => aliasMapToWithClauses(aliasMap), [aliasMap]); - // The trace results chart shows RED metrics (and a heatmap) only for a trace - // source that exposes a duration column; otherwise the single histogram - // stays. Derived once, as the narrowed source or null, so the callers can't - // drift apart on which one renders. + // The trace results chart shows RED metrics only for a trace source that + // exposes a duration column; otherwise the single histogram stays. Derived + // once, as the narrowed source or null, so the callers can't drift apart on + // which one renders. const traceRedMetricsSource = searchedSource != null && isTraceSource(searchedSource) && @@ -2155,24 +2150,18 @@ function DBSearchPageContent() { [isCustomGroupBy, histogramTimeChartConfig, searchedSource], ); - // The RED/Heatmap chart area renders only where it fits: a trace source with - // a duration column, on a non-compact viewport (three side-by-side tiles - // would be unreadable on a phone), without a custom group-by (the RED tiles - // have fixed grouping, so a custom group-by falls back to the histogram, - // which honors it). Derived once, as the narrowed source or null, so the - // chart branch, the stats-row RED/Heatmap switch and the live-tail pin can't - // drift apart on which one renders. + // The RED/Heatmap area renders only where it fits: not on a compact viewport, + // and not with a custom group-by, which the RED tiles' fixed grouping can't + // honor (the histogram can). The chart branch, the switch and the live-tail + // guard all read this, so they agree on which chart shows. const traceChartsSource = traceRedMetricsSource != null && !isCompact && !isCustomGroupBy ? traceRedMetricsSource : null; - // Base config for the trace heatmap tile, mirroring the delta-mode heatmap: - // the search's chart config over the searched range, carrying the source's - // select-alias definitions. Memoized so the tile's query stays stable across - // re-renders. The results table's sort is dropped, as for the histogram: the - // heatmap's own queries don't use it, but the chart keys its uPlot instance on - // the config, so sorting a column would otherwise rebuild the heatmap. + // Base config for the trace heatmap, like the delta-view heatmap's. The + // table's sort is dropped: the chart keys its uPlot instance on the config, + // so sorting a column would otherwise rebuild it. const traceHeatmapChartConfig = useMemo( () => chartConfig == null @@ -2186,14 +2175,10 @@ function DBSearchPageContent() { [chartConfig, searchedTimeRange, aliasWith], ); - // Live tail stays off while the heatmap is the visible chart, the way delta - // and pattern modes keep it off: the guard below turns it off, and the - // TimePicker's Live option and the Resume Live Tail button are hidden. - // Results mode defaults to live, so this view has to opt out for itself. - // Only while the heatmap is actually rendered (the same conditions as the - // chart branch below), so a stale ?traceChartMode=heatmap on a source that - // shows the histogram, or a query error that hides the chart area, can't - // disable live tail or hide its controls. + // While the heatmap shows, live tail stays off as in delta and pattern modes: + // the guard turns it off and the Live option and Resume Live Tail are hidden. + // Uses the chart branch's conditions, so a stale ?traceChartMode=heatmap or a + // query error that hides the chart can't take live tail away. const isHeatmapChartVisible = analysisMode === 'results' && traceChartsSource != null && @@ -2994,10 +2979,7 @@ function DBSearchPageContent() { totalCountConfig={totalCountConfig} enableParallelQueries > - {/* The heatmap doesn't group, and a custom - group-by would swap it for the histogram (see - traceChartsSource), so the picker is hidden - while it shows. */} + {/* The heatmap doesn't group. */} {isHeatmapChartVisible ? null : histogramGroupBySelect} diff --git a/packages/app/src/components/Search/TraceRedMetricsChart.tsx b/packages/app/src/components/Search/TraceRedMetricsChart.tsx index 689913e19..457c5f585 100644 --- a/packages/app/src/components/Search/TraceRedMetricsChart.tsx +++ b/packages/app/src/components/Search/TraceRedMetricsChart.tsx @@ -23,11 +23,8 @@ import { redBaseConfig, } from './traceRedMetrics'; -/** - * The trace results chart views, RED first as the default. The URL parser and - * the view switch both read this list, so a new mode can't be added to the type - * alone and silently parse back to RED. - */ +// The trace results chart views, RED first as the default. The type and the +// URL parser both come from this list, so they can't drift apart. export const TRACE_CHART_MODES = ['red', 'heatmap'] as const; export type TraceChartMode = (typeof TRACE_CHART_MODES)[number]; @@ -51,9 +48,7 @@ const HEATMAP_TILE_STYLE = { * RED metrics (Throughput, Errors, Duration) for the trace search results view, * replacing the single count histogram. The three charts render side by side as * sibling DBTimeCharts under a shared sync scope, so hovering one shows a - * cross-chart cursor on all three at the same timestamp. The RED/Heatmap switch - * lives in the search stats row (passed in as `mode`); the Heatmap view is the - * same bare heatmap tile the dashboard renders. + * cross-chart cursor on all three at the same timestamp. * * The per-chart aggregations are built by ./traceRedMetrics from the same base * config the histogram uses, so all three honor the active WHERE filter and @@ -112,18 +107,10 @@ export function TraceRedMetricsChart({ [base, durationExpression], ); - // The heatmap plots getDurationMsExpression (the source's duration already - // scaled to ms by its durationPrecision), which is the value - // HEATMAP_DURATION_NUMBER_FORMAT is paired with. + // Duration distribution over time, like the dashboard heatmap tile: the query + // the delta view's heatmap builds with its default settings, fixed here + // rather than read from that view's settings drawer. const durationMsExpression = getDurationMsExpression(source); - /** - * Heatmap tile query (duration distribution over time), matching the - * dashboard heatmap tile: no significant-fields comparison panel. It is the - * query the delta view's heatmap builds with its default settings, but the - * value, count and scale are fixed here rather than read from that view's - * settings drawer, so this stays a plain duration heatmap independent of the - * delta view's query state. - */ const heatmapQuery = useMemo( () => toHeatmapQuery({ diff --git a/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts b/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts index db2b4b42e..38ad38d0a 100644 --- a/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts +++ b/packages/app/src/components/Search/useHeatmapLiveTailGuard.ts @@ -1,13 +1,10 @@ import { useEffect } from 'react'; /** - * Keeps live tail off while the trace heatmap is the visible chart, the way - * delta and pattern modes keep it off. A live tick moves the absolute time - * range, and the heatmap keys its uPlot instance on the chart config, so every - * refresh would tear the chart down and rebuild it with a recomputed y-axis - * instead of updating in place. `isLive` is part of the check, not just the - * visibility, so live tail turned back on while the heatmap is showing - * (through any control) is switched off again. + * Keeps live tail off while the trace heatmap shows: each tick moves the time + * range, and the heatmap keys its uPlot instance on the config, so it would + * rebuild on every refresh. Checking `isLive` too switches live tail off again + * if any control turns it back on under the heatmap. */ export function useHeatmapLiveTailGuard({ isHeatmapChartVisible, diff --git a/packages/app/src/components/Search/useTraceChartModeReset.ts b/packages/app/src/components/Search/useTraceChartModeReset.ts index 3564f8c5b..4cf8f158c 100644 --- a/packages/app/src/components/Search/useTraceChartModeReset.ts +++ b/packages/app/src/components/Search/useTraceChartModeReset.ts @@ -3,19 +3,11 @@ import { useCallback, useEffect, useRef } from 'react'; import type { TraceChartMode } from './TraceRedMetricsChart'; /** - * Resets the trace RED/Heatmap choice to the default RED view when the user - * picks a different source. The choice was made for the previous source, so - * coming back to a trace source shouldn't silently reopen the heatmap (and - * turn live tail off again). - * - * The page arms the reset when the user picks a source, and it fires once the - * searched source (from the URL) reaches that source. Resetting at the pick - * itself would rewrite the previous history entry, since the pick runs before - * the debounced search pushes the new source. Back and Forward never arm it, - * so they keep the mode the URL restores, and the page disarms it when the - * user re-selects the searched source before the search runs. The mode is - * cleared rather than set to 'red', since nuqs 1.x writes an explicitly set - * default into the URL. + * Resets the trace RED/Heatmap choice to RED after the user picks a source, + * so coming back to a trace source doesn't silently reopen the heatmap. The + * page arms it on a pick, and it fires once the searched source reaches that + * pick, so it lands on the new history entry; Back/Forward never arm it, and + * an undone pick disarms it. It clears the param: nuqs 1.x would write 'red'. */ export function useTraceChartModeReset({ searchedSourceId, From 72b9fb3560e02172a7c0e3818270dc9e733f00e2 Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:34:42 +0000 Subject: [PATCH 14/15] fix(app): clear traceChartMode when RED is chosen in the switch The source-change reset already clears the param because nuqs 1.x writes an explicitly set default into the URL, but choosing RED in the switch still wrote traceChartMode=red into the URL and shared links. Clear it there too. Co-Authored-By: Claude Opus 5.5 --- packages/app/src/DBSearchPage.tsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/packages/app/src/DBSearchPage.tsx b/packages/app/src/DBSearchPage.tsx index 801defa1e..7e40d9606 100644 --- a/packages/app/src/DBSearchPage.tsx +++ b/packages/app/src/DBSearchPage.tsx @@ -2989,11 +2989,13 @@ function DBSearchPageContent() { setTraceChartMode( TRACE_CHART_MODES.find( - mode => mode === v, - ) ?? 'red', + mode => mode === v && mode !== 'red', + ) ?? null, ) } data={[ From 7e7a232d5a04b49287a17dbcb642e3be9d07ebae Mon Sep 17 00:00:00 2001 From: Alex Fedotyev <61838744+alex-fedotyev@users.noreply.github.com> Date: Wed, 18 Nov 2026 03:34:42 +0000 Subject: [PATCH 15/15] test(app): cover the RED and heatmap views of TraceRedMetricsChart Render the component in each mode with the chart components stubbed and the real query builder kept: heatmap mode mounts the heatmap, not the tiles, with the duration-in-ms value, count(), a log scale and the duration number format; RED mode mounts the three tiles, and only Duration opts into its pinned colors. Co-Authored-By: Claude Opus 5.5 --- .../__tests__/TraceRedMetricsChart.test.tsx | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) create mode 100644 packages/app/src/components/Search/__tests__/TraceRedMetricsChart.test.tsx diff --git a/packages/app/src/components/Search/__tests__/TraceRedMetricsChart.test.tsx b/packages/app/src/components/Search/__tests__/TraceRedMetricsChart.test.tsx new file mode 100644 index 000000000..a2b1a3a83 --- /dev/null +++ b/packages/app/src/components/Search/__tests__/TraceRedMetricsChart.test.tsx @@ -0,0 +1,145 @@ +import React from 'react'; +import { + BuilderChartConfigWithDateRange, + SourceKind, + TTraceSource, +} from '@hyperdx/common-utils/dist/types'; +import { screen } from '@testing-library/react'; + +import type DBHeatmapChartType from '@/components/DBHeatmapChart'; +import { HEATMAP_DURATION_NUMBER_FORMAT } from '@/components/DBHeatmapChart'; +import type { DBTimeChart as DBTimeChartType } from '@/components/DBTimeChart'; +import { TraceRedMetricsChart } from '@/components/Search/TraceRedMetricsChart'; + +type HeatmapProps = React.ComponentProps; +type TimeChartProps = React.ComponentProps; +const mockHeatmapProps: HeatmapProps[] = []; +const mockTimeChartProps: TimeChartProps[] = []; + +// Only the chart components are stubbed. The real query builder and number +// format stay, so the test checks the query the heatmap actually gets. +jest.mock('../../DBHeatmapChart', () => ({ + __esModule: true, + default: jest.fn((props: HeatmapProps) => { + mockHeatmapProps.push(props); + return
; + }), + toHeatmapQuery: jest.requireActual< + typeof import('../../DBHeatmapChart/heatmapQueries') + >('../../DBHeatmapChart/heatmapQueries').toHeatmapQuery, + HEATMAP_DURATION_NUMBER_FORMAT: jest.requireActual< + typeof import('../../DBHeatmapChart/heatmapAxis') + >('../../DBHeatmapChart/heatmapAxis').HEATMAP_DURATION_NUMBER_FORMAT, +})); + +jest.mock('../../DBTimeChart', () => ({ + DBTimeChart: jest.fn((props: TimeChartProps) => { + mockTimeChartProps.push(props); + return
; + }), +})); + +jest.mock('@/source', () => ({ + ...jest.requireActual('@/source'), + getDurationMsExpression: jest.fn(() => 'duration_ms_expr'), +})); + +const source: TTraceSource = { + id: 'trace-source', + kind: SourceKind.Trace, + name: 'Trace Source', + connection: 'conn', + from: { databaseName: 'otel', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + defaultTableSelectExpression: 'Timestamp', + durationExpression: 'Duration', + durationPrecision: 3, + traceIdExpression: 'TraceId', + spanIdExpression: 'SpanId', + parentSpanIdExpression: 'ParentSpanId', + spanNameExpression: 'SpanName', + spanKindExpression: 'SpanKind', + statusCodeExpression: 'StatusCode', +}; + +const baseConfig: BuilderChartConfigWithDateRange = { + dateRange: [new Date(0), new Date(60_000)], + from: { databaseName: 'otel', tableName: 'otel_traces' }, + timestampValueExpression: 'Timestamp', + connection: 'conn', + select: '', + where: '', + whereLanguage: 'sql', +}; + +const histogramTimeChartConfig: BuilderChartConfigWithDateRange = { + ...baseConfig, + select: [{ aggFn: 'count', aggCondition: '', valueExpression: '' }], + groupBy: 'StatusCode', + granularity: 'auto', +}; + +function renderChart(mode: 'red' | 'heatmap') { + renderWithMantine( + , + ); +} + +function asDistribution(query: HeatmapProps['query']) { + if (query.mode !== 'distribution') { + throw new Error(`expected a distribution query, got ${query.mode}`); + } + return query; +} + +describe('TraceRedMetricsChart', () => { + beforeEach(() => { + jest.clearAllMocks(); + mockHeatmapProps.length = 0; + mockTimeChartProps.length = 0; + }); + + it('renders the duration heatmap, not the RED tiles, in heatmap mode', () => { + renderChart('heatmap'); + + expect(screen.getByTestId('db-heatmap-chart')).toBeInTheDocument(); + expect(screen.queryByTestId('db-time-chart')).not.toBeInTheDocument(); + + const props = mockHeatmapProps[mockHeatmapProps.length - 1]; + expect(props.enabled).toBe(true); + const query = asDistribution(props.query); + // The source's duration in ms, counted per bucket on a log scale, with the + // duration number format: the delta view's default duration heatmap. + expect(query.config.select).toEqual([ + { + aggFn: 'heatmap', + valueExpression: 'duration_ms_expr', + countExpression: 'count()', + }, + ]); + expect(query.scaleType).toBe('log'); + expect(query.config.numberFormat).toEqual(HEATMAP_DURATION_NUMBER_FORMAT); + expect(query.config.dateRange).toBe(baseConfig.dateRange); + }); + + it('renders the three RED tiles, not the heatmap, in RED mode', () => { + renderChart('red'); + + expect(screen.queryByTestId('db-heatmap-chart')).not.toBeInTheDocument(); + expect(new Set(mockTimeChartProps.map(p => p.title))).toEqual( + new Set(['Throughput', 'Errors', 'Duration']), + ); + // Only the Duration tile opts into its select items' pinned colors. + expect( + new Set( + mockTimeChartProps.filter(p => p.applySelectColors).map(p => p.title), + ), + ).toEqual(new Set(['Duration'])); + }); +});