SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.
TypeScript apmapplication-monitoringdistributed-tracinggogood-first-issuejaegerloglogsmetricsmonitoringnextjsobservabilityopen-sourceopentelemetryprometheusreactreactjsself-hostedtracingtypescript
Feat/trace details pending 2 (#11255)
Aditya Singh515220194d53
diff --git a/frontend/src/container/TraceMetadata/TraceMetadata.tsx b/frontend/src/container/TraceMetadata/TraceMetadata.tsxindex cb5c1aa9f1..a6ceb23c27 100644--- a/frontend/src/container/TraceMetadata/TraceMetadata.tsx+++ b/frontend/src/container/TraceMetadata/TraceMetadata.tsx@@ -106,7 +106,7 @@ function TraceMetadata(props: ITraceMetadataProps): JSX.Element {className="new-view-btn"onClick={handleSwitchToNewView}>- New view+ Try new experience</Button>)}</div>diff --git a/frontend/src/hooks/spanDetails/__tests__/usePinnedAttributes.test.ts b/frontend/src/hooks/spanDetails/__tests__/usePinnedAttributes.test.tsnew file mode 100644index 0000000000..0378be3301--- /dev/null+++ b/frontend/src/hooks/spanDetails/__tests__/usePinnedAttributes.test.ts@@ -0,0 +1,122 @@+import { normalizeRawToV2 } from '../usePinnedAttributes';++describe('normalizeRawToV2', () => {+ it('returns empty result for empty input', () => {+ expect(normalizeRawToV2([])).toStrictEqual({ value: [], changed: false });+ });++ it('passes V2 flat entries through unchanged', () => {+ const raw = ['http.method', 'service.name'];+ expect(normalizeRawToV2(raw)).toStrictEqual({+ value: ['http.method', 'service.name'],+ changed: false,+ });+ });++ it('converts a V3 path entry to its leaf key', () => {+ const result = normalizeRawToV2(['["attributes","http.method"]']);+ expect(result.value).toStrictEqual(['http.method']);+ expect(result.changed).toBe(true);+ });++ it('converts V3 resource path to its leaf key', () => {+ const result = normalizeRawToV2(['["resource","service.name"]']);+ expect(result.value).toStrictEqual(['service.name']);+ expect(result.changed).toBe(true);+ });++ it('handles single-element V3 path (top-level fields)', () => {+ const result = normalizeRawToV2(['["name"]']);+ expect(result.value).toStrictEqual(['name']);+ expect(result.changed).toBe(true);+ });++ it('dedupes V3 entries that share a leaf key across namespaces', () => {+ const result = normalizeRawToV2([+ '["attributes","http.method"]',+ '["resource","http.method"]',+ ]);+ expect(result.value).toStrictEqual(['http.method']);+ expect(result.changed).toBe(true);+ });++ it('dedupes a V3 entry sharing a leaf with an existing V2 entry', () => {+ const result = normalizeRawToV2([+ 'http.method',+ '["attributes","http.method"]',+ ]);+ expect(result.value).toStrictEqual(['http.method']);+ expect(result.changed).toBe(true);+ });++ it('dedupes duplicate V2 entries', () => {+ const result = normalizeRawToV2(['http.method', 'http.method']);+ expect(result.value).toStrictEqual(['http.method']);+ expect(result.changed).toBe(true);+ });++ it('preserves V2 entries when no V3 conversion or dedupe is needed', () => {+ const result = normalizeRawToV2(['a', 'b', 'c']);+ expect(result.value).toStrictEqual(['a', 'b', 'c']);+ expect(result.changed).toBe(false);+ });++ it('handles a mixed array: V3 + V2 with no overlap', () => {+ const result = normalizeRawToV2([+ '["attributes","http.method"]',+ 'db.system',+ '["resource","service.name"]',+ ]);+ expect(result.value).toStrictEqual([+ 'http.method',+ 'db.system',+ 'service.name',+ ]);+ expect(result.changed).toBe(true);+ });++ it('preserves insertion order of first-seen leaf keys', () => {+ const result = normalizeRawToV2([+ '["attributes","b"]',+ 'a',+ '["resource","c"]',+ 'a', // duplicate, should be dropped+ ]);+ expect(result.value).toStrictEqual(['b', 'a', 'c']);+ expect(result.changed).toBe(true);+ });++ it('treats malformed V3-looking entries (non-array JSON) as V2 flat', () => {+ // '{}' parses as JSON but isn't an array, so isV3PinnedAttribute returns false.+ const result = normalizeRawToV2(['{}']);+ expect(result.value).toStrictEqual(['{}']);+ expect(result.changed).toBe(false);+ });++ it('keeps a V3 entry as-is when deserialize fails (empty path)', () => {+ // Edge case: '[]' parses as an empty array. isV3PinnedAttribute returns+ // true, but deserializeKeyPath returns an empty array → leaf can't be+ // extracted, so we fall back to keeping the entry verbatim.+ const result = normalizeRawToV2(['[]']);+ expect(result.value).toStrictEqual(['[]']);+ expect(result.changed).toBe(false);+ });++ describe('round-trip with V3 migration', () => {+ it('V2 entries → V3 conversion → V2 normalization recovers the originals', () => {+ // Simulates the cross-view workflow.+ const originalV2 = ['http.method', 'service.name'];++ // Simulate V3 migration would have produced these paths.+ const v3Form = [+ '["attributes","http.method"]',+ '["resource","service.name"]',+ ];++ // V2 hook normalizes them back to flat strings.+ const result = normalizeRawToV2(v3Form);+ expect(result.value).toStrictEqual(originalV2);+ expect(result.changed).toBe(true);+ });+ });+});diff --git a/frontend/src/hooks/spanDetails/usePinnedAttributes.ts b/frontend/src/hooks/spanDetails/usePinnedAttributes.tsindex 8bd80221f9..853200b6ab 100644--- a/frontend/src/hooks/spanDetails/usePinnedAttributes.ts+++ b/frontend/src/hooks/spanDetails/usePinnedAttributes.ts@@ -1,7 +1,12 @@-import { useCallback, useMemo } from 'react';+import { useCallback, useEffect, useMemo, useRef } from 'react';+import { useMutation } from 'react-query';+import getLocalStorageKey from 'api/browser/localstorage/get';+import updateUserPreferenceAPI from 'api/v1/user/preferences/name/update';import { LOCALSTORAGE } from 'constants/localStorage';--import { useLocalStorage } from '../useLocalStorage';+import { USER_PREFERENCES } from 'constants/userPreferences';+import { isV3PinnedAttribute } from 'pages/TraceDetailsV3/utils';+import { deserializeKeyPath } from 'periscope/components/PrettyView/utils';+import { useAppContext } from 'providers/App/App';interface UsePinnedAttributesReturn {pinnedAttributes: Record<string, boolean>;@@ -10,20 +15,101 @@ interface UsePinnedAttributesReturn {}/**- * V2 trace-details pinned-attributes hook. localStorage-only.+ * V2 trace-details pinned-attributes hook.+ *+ * Reads/writes the shared user-preference `span_details_pinned_attributes`+ * (same key V3 uses). Projects V3-shape entries (JSON-stringified paths)+ * down to their leaf-key string so V2 consumers see flat names, then writes+ * any normalization back to the pref so subsequent reads are V2-clean.*- * NOTE: V2 used to also persist to the user-pref API- * (`span_details_pinned_attributes`) but V3 now owns that key with a different- * (nested-path) format. V2 is isolated to localStorage so it doesn't fight V3- * over the same backend value. See `useMigratePinnedAttributes` in V3.+ * Legacy seed: on first mount with an empty pref slot but non-empty+ * `localStorage.SPAN_DETAILS_PINNED_ATTRIBUTES`, copy localStorage → pref+ * once (for users who pinned in V2 before V2 stopped dual-writing). After+ * that, localStorage is no longer touched.*/export function usePinnedAttributes(availableAttributes: string[],): UsePinnedAttributesReturn {- const [pinnedKeys, setPinnedKeys] = useLocalStorage<string[]>(- LOCALSTORAGE.SPAN_DETAILS_PINNED_ATTRIBUTES,- [],- );+ const { userPreferences, updateUserPreferenceInContext } = useAppContext();+ const { mutate } = useMutation(updateUserPreferenceAPI);+ const ranRef = useRef(false);++ // Normalize the raw pref array (potentially mixed V2 + V3) into a flat+ // list of leaf-key strings for V2 consumption. Dedupe in case V3 had+ // `attributes.foo` and `resource.foo` (same leaf, different namespaces).+ const pinnedKeys = useMemo<string[]>(() => {+ const pref = userPreferences?.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PINNED_ATTRIBUTES,+ );+ const raw = (pref?.value as string[] | undefined) ?? [];+ return normalizeRawToV2(raw).value;+ }, [userPreferences]);++ // On mount: legacy seed + V3 → V2 normalization. Writes the normalized+ // (and possibly seeded) array back to the pref so subsequent reads see+ // a clean V2-shape array.+ useEffect(() => {+ if (ranRef.current || !userPreferences) {+ return;+ }++ const pref = userPreferences.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PINNED_ATTRIBUTES,+ );+ const raw = (pref?.value as string[] | undefined) ?? [];++ // Legacy seed: empty pref + localStorage has entries → copy to pref.+ if (raw.length === 0) {+ const legacy = readLegacyLocalStorageEntries();+ if (legacy.length > 0 && pref) {+ const previousValue = pref.value;+ updateUserPreferenceInContext({ ...pref, value: legacy });+ mutate(+ {+ name: USER_PREFERENCES.SPAN_DETAILS_PINNED_ATTRIBUTES,+ value: legacy,+ },+ {+ onSuccess: () => {+ ranRef.current = true;+ },+ onError: () => {+ updateUserPreferenceInContext({ ...pref, value: previousValue });+ },+ },+ );+ } else {+ ranRef.current = true;+ }+ return;+ }++ const { value: nextValue, changed } = normalizeRawToV2(raw);++ if (!changed) {+ ranRef.current = true;+ return;+ }++ if (pref) {+ const previousValue = pref.value;+ updateUserPreferenceInContext({ ...pref, value: nextValue });+ mutate(+ {+ name: USER_PREFERENCES.SPAN_DETAILS_PINNED_ATTRIBUTES,+ value: nextValue,+ },+ {+ onSuccess: () => {+ ranRef.current = true;+ },+ onError: () => {+ updateUserPreferenceInContext({ ...pref, value: previousValue });+ },+ },+ );+ }+ }, [userPreferences, updateUserPreferenceInContext, mutate]);const pinnedAttributes = useMemo((): Record<string, boolean> =>@@ -41,13 +127,22 @@ export function usePinnedAttributes(const togglePin = useCallback((attributeKey: string): void => {- setPinnedKeys((prev) =>- prev.includes(attributeKey)- ? prev.filter((k) => k !== attributeKey)- : [...prev, attributeKey],+ const next = pinnedKeys.includes(attributeKey)+ ? pinnedKeys.filter((k) => k !== attributeKey)+ : [...pinnedKeys, attributeKey];++ const pref = userPreferences?.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PINNED_ATTRIBUTES,);+ if (pref) {+ updateUserPreferenceInContext({ ...pref, value: next });+ }+ mutate({+ name: USER_PREFERENCES.SPAN_DETAILS_PINNED_ATTRIBUTES,+ value: next,+ });},- [setPinnedKeys],+ [pinnedKeys, userPreferences, updateUserPreferenceInContext, mutate],);const isPinned = useCallback(@@ -61,3 +156,55 @@ export function usePinnedAttributes(isPinned,};}++/**+ * Pure V3 → V2 normalization. Walks `raw` (potentially mixed V2 flat strings+ * + V3 JSON paths), produces a deduped V2-shape array, and reports whether+ * the result differs from the input. Used both for the read projection+ * (where the `changed` flag is ignored) and the on-mount migration write+ * (where it gates the API call).+ */+export function normalizeRawToV2(raw: string[]): {+ value: string[];+ changed: boolean;+} {+ const normalized = new Set<string>();+ let changed = false;++ for (const entry of raw) {+ let key: string;+ if (isV3PinnedAttribute(entry)) {+ const path = deserializeKeyPath(entry);+ if (path && path.length > 0) {+ key = String(path[path.length - 1]);+ changed = true; // V3 → V2 conversion happened+ } else {+ key = entry;+ }+ } else {+ key = entry;+ }+ if (normalized.has(key)) {+ changed = true; // dedupe trimmed an entry+ continue;+ }+ normalized.add(key);+ }++ return { value: Array.from(normalized), changed };+}++function readLegacyLocalStorageEntries(): string[] {+ try {+ const raw = getLocalStorageKey(LOCALSTORAGE.SPAN_DETAILS_PINNED_ATTRIBUTES);+ if (!raw) {+ return [];+ }+ const parsed = JSON.parse(raw);+ return Array.isArray(parsed)+ ? parsed.filter((s): s is string => typeof s === 'string')+ : [];+ } catch {+ return [];+ }+}diff --git a/frontend/src/hooks/trace/useGetTraceFlamegraph.tsx b/frontend/src/hooks/trace/useGetTraceFlamegraph.tsxindex ae4f6d865e..6f4d443644 100644--- a/frontend/src/hooks/trace/useGetTraceFlamegraph.tsx+++ b/frontend/src/hooks/trace/useGetTraceFlamegraph.tsx@@ -15,6 +15,7 @@ const useGetTraceFlamegraph = (queryKey: [REACT_QUERY_KEY.GET_TRACE_V2_FLAMEGRAPH,props.traceId,+ props.selectedSpanId,props.selectFields,],enabled: !!props.traceId,diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsxindex 1fa6ebf407..880c3083c2 100644--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel.tsx@@ -10,8 +10,11 @@ import { themeColors } from 'constants/theme';import { generateColor } from 'lib/uPlotLib/utils/generateColor';import { FloatingPanel } from 'periscope/components/FloatingPanel';-import { useTraceContext } from '../../contexts/TraceContext';-import { AGGREGATIONS } from '../../utils/aggregations';+import { useTraceStore } from '../../stores/traceStore';+import {+ AGGREGATIONS,+ getAggregationMap as findAggregationMap,+} from '../../utils/aggregations';import './AnalyticsPanel.styles.scss';@@ -29,16 +32,23 @@ function AnalyticsPanel({isOpen,onClose,}: AnalyticsPanelProps): JSX.Element | null {- const { getAggregationMap } = useTraceContext();+ const aggregations = useTraceStore((s) => s.aggregations);+ const colorByFieldName = useTraceStore((s) => s.colorByField.name);const execTimePct = useMemo(- () => getAggregationMap(AGGREGATIONS.EXEC_TIME_PCT),- [getAggregationMap],+ () =>+ findAggregationMap(+ aggregations,+ AGGREGATIONS.EXEC_TIME_PCT,+ colorByFieldName,+ ),+ [aggregations, colorByFieldName],);const spanCounts = useMemo(- () => getAggregationMap(AGGREGATIONS.SPAN_COUNT),- [getAggregationMap],+ () =>+ findAggregationMap(aggregations, AGGREGATIONS.SPAN_COUNT, colorByFieldName),+ [aggregations, colorByFieldName],);const execTimeRows = useMemo(() => {diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel.tsxindex 83a0305aec..4187af30fb 100644--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel.tsx+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/SpanDetailsPanel.tsx@@ -1,4 +1,4 @@-import { useCallback, useMemo, useState } from 'react';+import { useCallback, useMemo } from 'react';import { Button } from '@signozhq/ui/button';import {TabsContent,@@ -15,7 +15,6 @@ import {import {Bookmark,CalendarClock,- ChartBar,ChartColumnBig,Dock,Link2,@@ -56,7 +55,6 @@ import { SpanV3 } from 'types/api/trace/getTraceV3';import { DataSource, LogsAggregatorOperator } from 'types/common/queryBuilder';import { openInNewTab } from 'utils/navigation';-import AnalyticsPanel from './AnalyticsPanel/AnalyticsPanel';import { HIGHLIGHTED_OPTIONS } from './config';import {// KEY_ATTRIBUTE_KEYS, // uncomment when key attributes section is re-enabled@@ -470,24 +468,8 @@ function SpanDetailsPanel({traceStartTime,traceEndTime,}: SpanDetailsPanelProps): JSX.Element {- const [isAnalyticsOpen, setIsAnalyticsOpen] = useState(false);-const headerActions = useMemo((): HeaderAction[] => {const actions: HeaderAction[] = [- {- key: 'analytics',- component: (- <Button- variant="ghost"- size="sm"- color="secondary"- prefix={<ChartBar size={14} />}- onClick={(): void => setIsAnalyticsOpen((prev) => !prev)}- >- Analytics- </Button>- ),- },// TODO: Add back when driven through separate config for different pages// {// key: 'view-full-trace',@@ -571,64 +553,46 @@ function SpanDetailsPanel({</>);- const analyticsPanel = (- <AnalyticsPanel- isOpen={isAnalyticsOpen}- onClose={(): void => setIsAnalyticsOpen(false)}- />- );-if (variant === SpanDetailVariant.DOCKED) {- return (- <>- <div className="span-details-panel">{content}</div>- {analyticsPanel}- </>- );+ return <div className="span-details-panel">{content}</div>;}if (variant === SpanDetailVariant.DRAWER) {return (- <>- <DetailsPanelDrawer- isOpen={panelState.isOpen}- onClose={panelState.close}- className="span-details-panel"- >- {content}- </DetailsPanelDrawer>- {analyticsPanel}- </>- );- }-- return (- <>- <FloatingPanel+ <DetailsPanelDrawerisOpen={panelState.isOpen}+ onClose={panelState.close}className="span-details-panel"- width={PANEL_WIDTH}- minWidth={480}- height={window.innerHeight - PANEL_MARGIN_TOP - PANEL_MARGIN_BOTTOM}- defaultPosition={{- x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN_RIGHT,- y: PANEL_MARGIN_TOP,- }}- enableResizing={{- top: true,- right: true,- bottom: true,- left: true,- topRight: false,- bottomRight: false,- bottomLeft: false,- topLeft: false,- }}>{content}- </FloatingPanel>- {analyticsPanel}- </>+ </DetailsPanelDrawer>+ );+ }++ return (+ <FloatingPanel+ isOpen={panelState.isOpen}+ className="span-details-panel"+ width={PANEL_WIDTH}+ minWidth={480}+ height={window.innerHeight - PANEL_MARGIN_TOP - PANEL_MARGIN_BOTTOM}+ defaultPosition={{+ x: window.innerWidth - PANEL_WIDTH - PANEL_MARGIN_RIGHT,+ y: PANEL_MARGIN_TOP,+ }}+ enableResizing={{+ top: true,+ right: true,+ bottom: true,+ left: true,+ topRight: false,+ bottomRight: false,+ bottomLeft: false,+ topLeft: false,+ }}+ >+ {content}+ </FloatingPanel>);}diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/config.tsx b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/config.tsxindex 0e08e6bcc6..b894262887 100644--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/config.tsx+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/config.tsx@@ -23,8 +23,8 @@ export const HIGHLIGHTED_OPTIONS: HighlightedOption[] = [) : null,},{- key: 'statusCodeString',- label: 'STATUS CODE STRING',+ key: 'statusCode',+ label: 'STATUS CODE',render: (span): ReactNode | null =>span.status_code_string ? (<Badge color="vanilla">{span.status_code_string}</Badge>diff --git a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/hooks/useSpanAttributeActions.ts b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/hooks/useSpanAttributeActions.tsindex 97485e68c5..3e9666c9a4 100644--- a/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/hooks/useSpanAttributeActions.ts+++ b/frontend/src/pages/TraceDetailsV3/SpanDetailsPanel/hooks/useSpanAttributeActions.ts@@ -26,8 +26,11 @@ export interface SpanAttributeAction {disabled?: boolean;hidden?: boolean;callback: (args: { key: string; value: string; dataType?: string }) => void;- /** Returns true if this action should be hidden for the given field key */- shouldHide: (key: string) => boolean;+ /**+ * Returns true if this action should be hidden. Receives the leaf key and+ * the full path so we can hide based on ancestor segments too.+ */+ shouldHide: (key: string, fieldKeyPath: (string | number)[]) => boolean;}// Keys that should NOT support filter/group-by actions.@@ -44,7 +47,19 @@ export const NON_FILTERABLE_KEYS = new Set(['timestamp',]);-const shouldHideForKey = (key: string): boolean => NON_FILTERABLE_KEYS.has(key);+// Keys whose entire subtree is non-queryable. Hides filter/group-by for the+// key itself AND any descendant leaf. Used for nested data that exists on the+// span payload but isn't queryable as a trace attribute (e.g. span events, links).+export const NON_FILTERABLE_ANCESTOR_KEYS = new Set(['events', 'references']);++const shouldHideForKey = (+ leafKey: string,+ fieldKeyPath: (string | number)[],+): boolean =>+ NON_FILTERABLE_KEYS.has(leafKey) ||+ fieldKeyPath.some(+ (seg) => typeof seg === 'string' && NON_FILTERABLE_ANCESTOR_KEYS.has(seg),+ );// Action identifiersexport const SPAN_ACTION = {diff --git a/frontend/src/pages/TraceDetailsV3/SpanHoverCard/SpanHoverCard.tsx b/frontend/src/pages/TraceDetailsV3/SpanHoverCard/SpanHoverCard.tsxindex 9a812e718d..017ba343b8 100644--- a/frontend/src/pages/TraceDetailsV3/SpanHoverCard/SpanHoverCard.tsx+++ b/frontend/src/pages/TraceDetailsV3/SpanHoverCard/SpanHoverCard.tsx@@ -5,8 +5,8 @@ import {TooltipTrigger,} from '@signozhq/ui/tooltip';import { convertTimeToRelevantUnit } from 'container/TraceDetail/utils';-import { useTraceContext } from 'pages/TraceDetailsV3/contexts/TraceContext';-import { getSpanAttribute } from 'pages/TraceDetailsV3/utils';+import { useTraceStore } from 'pages/TraceDetailsV3/stores/traceStore';+import { getSpanAttribute, resolveSpanColor } from 'pages/TraceDetailsV3/utils';import { useMemo } from 'react';import { SpanV3 } from 'types/api/trace/getTraceV3';import { toFixed } from 'utils/toFixed';@@ -105,7 +105,8 @@ export function SpanHoverCard({spans,traceStartTime,}: SpanHoverCardProps): JSX.Element {- const { previewFields, resolveSpanColor } = useTraceContext();+ const previewFields = useTraceStore((s) => s.previewFields);+ const colorByFieldName = useTraceStore((s) => s.colorByField.name);const hoverCardData = useMemo(() => {if (!hoveredSpanId) {@@ -130,7 +131,7 @@ export function SpanHoverCard({anchorTop: idx * rowHeight,tooltip: {spanName: span.name,- color: resolveSpanColor(span),+ color: resolveSpanColor(span, colorByFieldName),hasError: span.has_error,relativeStartMs: span.timestamp - traceStartTime,durationMs: span.duration_nano / 1e6,@@ -141,7 +142,7 @@ export function SpanHoverCard({hoveredSpanId,spans,previewFields,- resolveSpanColor,+ colorByFieldName,rowHeight,traceStartTime,]);diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.styles.scss b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.styles.scssindex 33a8df2267..0c619a90f3 100644--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.styles.scss+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.styles.scss@@ -23,10 +23,6 @@}min-width: 0;- &:not(&--expanded) {- margin-left: auto;- }-&--expanded {max-width: none;flex: 1;@@ -37,6 +33,11 @@flex-shrink: 0;}+ &__analytics-btn {+ flex-shrink: 0;+ margin-left: auto;+ }+&__sub-header {display: flex;align-items: center;diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsxindex 17b7cd5f7e..34bd392a7a 100644--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceDetailsHeader.tsx@@ -1,6 +1,12 @@import { useCallback, useState } from 'react';import { useParams } from 'react-router-dom';import { Button } from '@signozhq/ui/button';+import {+ Tooltip,+ TooltipContent,+ TooltipProvider,+ TooltipTrigger,+} from '@signozhq/ui/tooltip';import { Skeleton } from 'antd';import setLocalStorageKey from 'api/browser/localstorage/set';import HttpStatusBadge from 'components/HttpStatusBadge/HttpStatusBadge';@@ -9,14 +15,21 @@ import ROUTES from 'constants/routes';import { convertTimeToRelevantUnit } from 'container/TraceDetail/utils';import dayjs from 'dayjs';import history from 'lib/history';-import { ArrowLeft, CalendarClock, Server, Timer } from '@signozhq/icons';+import {+ ArrowLeft,+ CalendarClock,+ ChartPie,+ Server,+ Timer,+} from '@signozhq/icons';import { FloatingPanel } from 'periscope/components/FloatingPanel';import KeyValueLabel from 'periscope/components/KeyValueLabel';import { TraceDetailV2URLProps } from 'types/api/trace/getTraceV2';import { DataSource } from 'types/common/queryBuilder';import FieldsSettings from '../components/FieldsSettings/FieldsSettings';-import { useTraceContext } from '../contexts/TraceContext';+import { useTraceStore } from '../stores/traceStore';+import AnalyticsPanel from '../SpanDetailsPanel/AnalyticsPanel/AnalyticsPanel';import Filters from '../TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters';import TraceOptionsMenu from './TraceOptionsMenu';@@ -72,7 +85,9 @@ function TraceDetailsHeader({const [showTraceDetails, setShowTraceDetails] = useState(true);const [isFilterExpanded, setIsFilterExpanded] = useState(false);const [isPreviewFieldsOpen, setIsPreviewFieldsOpen] = useState(false);- const { previewFields, setPreviewFields } = useTraceContext();+ const [isAnalyticsOpen, setIsAnalyticsOpen] = useState(false);+ const previewFields = useTraceStore((s) => s.previewFields);+ const setPreviewFields = useTraceStore((s) => s.setPreviewFields);const handleSwitchToOldView = useCallback((): void => {setLocalStorageKey(LOCALSTORAGE.TRACE_DETAILS_PREFER_OLD_VIEW, 'true');@@ -127,6 +142,31 @@ function TraceDetailsHeader({)}{isDataLoaded && (<>+ {!isFilterExpanded && (+ <>+ <TooltipProvider>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ color="secondary"+ className="trace-details-header__analytics-btn"+ onClick={(): void => setIsAnalyticsOpen((prev) => !prev)}+ >+ <ChartPie size={14} />+ </Button>+ </TooltipTrigger>+ <TooltipContent>Analytics</TooltipContent>+ </Tooltip>+ </TooltipProvider>+ <TraceOptionsMenu+ showTraceDetails={showTraceDetails}+ onToggleTraceDetails={handleToggleTraceDetails}+ onOpenPreviewFields={(): void => setIsPreviewFieldsOpen(true)}+ />+ </>+ )}<divclassName={`trace-details-header__filter${isFilterExpanded ? ' trace-details-header__filter--expanded' : ''@@ -143,22 +183,15 @@ function TraceDetailsHeader({/></div>{!isFilterExpanded && (- <>- <Button- variant="solid"- color="secondary"- size="sm"- className="trace-details-header__old-view-btn"- onClick={handleSwitchToOldView}- >- Old View- </Button>- <TraceOptionsMenu- showTraceDetails={showTraceDetails}- onToggleTraceDetails={handleToggleTraceDetails}- onOpenPreviewFields={(): void => setIsPreviewFieldsOpen(true)}- />- </>+ <Button+ variant="solid"+ color="secondary"+ size="sm"+ className="trace-details-header__old-view-btn"+ onClick={handleSwitchToOldView}+ >+ Legacy View+ </Button>)}</>)}@@ -216,6 +249,11 @@ function TraceDetailsHeader({/></FloatingPanel>)}++ <AnalyticsPanel+ isOpen={isAnalyticsOpen}+ onClose={(): void => setIsAnalyticsOpen(false)}+ /></div>);}diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceOptionsMenu.tsx b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceOptionsMenu.tsxindex ccc326e437..f0b8f7a502 100644--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceOptionsMenu.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsHeader/TraceOptionsMenu.tsx@@ -4,7 +4,7 @@ import { Button } from '@signozhq/ui/button';import { DropdownMenuSimple as Dropdown } from '@signozhq/ui/dropdown-menu';import { Ellipsis } from '@signozhq/icons';-import { useTraceContext } from '../contexts/TraceContext';+import { useTraceStore } from '../stores/traceStore';interface TraceOptionsMenuProps {showTraceDetails: boolean;@@ -17,8 +17,11 @@ function TraceOptionsMenu({onToggleTraceDetails,onOpenPreviewFields,}: TraceOptionsMenuProps): JSX.Element {- const { colorByField, setColorByField, availableColorByOptions } =- useTraceContext();+ const colorByField = useTraceStore((s) => s.colorByField);+ const setColorByField = useTraceStore((s) => s.setColorByField);+ const availableColorByOptions = useTraceStore(+ (s) => s.availableColorByOptions,+ );const menuItems: MenuItem[] = useMemo(() => {const items: MenuItem[] = [@@ -79,11 +82,11 @@ function TraceOptionsMenu({]);return (- <Dropdown menu={{ items: menuItems }}>+ <Dropdown menu={{ items: menuItems }} align="start"><Button- variant="solid"+ variant="ghost"+ size="icon"color="secondary"- size="sm"prefix={<Ellipsis size={14} />}/></Dropdown>diff --git a/frontend/src/pages/TraceDetailsV3/TraceDetailsV3.styles.scss b/frontend/src/pages/TraceDetailsV3/TraceDetailsV3.styles.scssindex f6497afed7..6e9b66ae7f 100644--- a/frontend/src/pages/TraceDetailsV3/TraceDetailsV3.styles.scss+++ b/frontend/src/pages/TraceDetailsV3/TraceDetailsV3.styles.scss@@ -21,7 +21,8 @@}.ant-collapse-header {- border: 1px solid var(--l2-border);+ border-top: 1px solid var(--l2-border);+ border-bottom: 1px solid var(--l2-border);}.ant-collapse-content {@@ -39,15 +40,27 @@width: 100%;}+ &__collapse-title {+ display: inline-flex;+ align-items: center;+ gap: 6px;+ }+&__collapse-count {display: flex;- gap: 6px;+ gap: 12px;align-items: center;font-size: 12px;font-weight: 400;color: var(--l2-foreground);}+ &__collapse-count-item {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ }+&__collapse-count-errors {color: var(--destructive);}diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsxindex cfd905e40a..ea4c89fea3 100644--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/TraceFlamegraph.tsx@@ -4,9 +4,10 @@ import { Skeleton } from 'antd';import useGetTraceFlamegraph from 'hooks/trace/useGetTraceFlamegraph';import useUrlQuery from 'hooks/useUrlQuery';import { TraceDetailFlamegraphURLProps } from 'types/api/trace/getTraceFlamegraph';+import { SpanV3 } from 'types/api/trace/getTraceV3';import { COLOR_BY_FIELDS } from '../constants';-import { useTraceContext } from '../contexts/TraceContext';+import { useTraceStore } from '../stores/traceStore';import Error from '../TraceWaterfall/TraceWaterfallStates/Error/Error';import {mergeTelemetryFieldKeys,@@ -19,11 +20,15 @@ import { useVisualLayoutWorker } from './hooks/useVisualLayoutWorker';interface TraceFlamegraphProps {filteredSpanIds: string[];isFilterActive: boolean;+ selectedSpan: SpanV3 | undefined;+ totalSpansCount: number;}function TraceFlamegraph({filteredSpanIds,isFilterActive,+ selectedSpan,+ totalSpansCount,}: TraceFlamegraphProps): JSX.Element {const { id: traceId } = useParams<TraceDetailFlamegraphURLProps>();const urlQuery = useUrlQuery();@@ -50,7 +55,7 @@ function TraceFlamegraph({[history, search],);- const { previewFields } = useTraceContext();+ const previewFields = useTraceStore((s) => s.previewFields);// Color-by fields baseline + user-picked preview fields. De-duped by `name`,// color-by entries first so their canonical metadata wins on collision.@@ -63,13 +68,18 @@ function TraceFlamegraph({[previewFields],);+ // Only pass selectedSpanId in sampled mode — for full traces, the span is+ // already in the loaded flamegraph data and no refetch is needed.+ const isSampled = totalSpansCount > FLAMEGRAPH_SPAN_LIMIT;+ const selectedSpanIdForFetch = isSampled ? selectedSpan?.span_id : undefined;+const {data,isFetching,error: fetchError,} = useGetTraceFlamegraph({traceId,- // selectedSpanId: firstSpanAtFetchLevel,+ selectedSpanId: selectedSpanIdForFetch,limit: FLAMEGRAPH_SPAN_LIMIT,selectFields: flamegraphSelectFields,});diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/TraceFlamegraph.test.tsx b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/TraceFlamegraph.test.tsxnew file mode 100644index 0000000000..a9a7b3d616--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/TraceFlamegraph.test.tsx@@ -0,0 +1,108 @@+import { render } from '@testing-library/react';+import useGetTraceFlamegraph from 'hooks/trace/useGetTraceFlamegraph';+import { AllTheProviders } from 'tests/test-utils';+import { SpanV3 } from 'types/api/trace/getTraceV3';++import { FLAMEGRAPH_SPAN_LIMIT } from '../constants';+import TraceFlamegraph from '../TraceFlamegraph';++jest.mock('hooks/trace/useGetTraceFlamegraph');++// Short-circuit the worker so the test doesn't depend on layout computation.+jest.mock('../hooks/useVisualLayoutWorker', () => ({+ useVisualLayoutWorker: (): unknown => ({+ layout: { totalVisualRows: 0, visualRows: [] },+ isComputing: false,+ error: null,+ }),+}));++const mockUseGetTraceFlamegraph = useGetTraceFlamegraph as jest.MockedFunction<+ typeof useGetTraceFlamegraph+>;++function renderFlamegraph(props: {+ selectedSpan: SpanV3 | undefined;+ totalSpansCount: number;+}): ReturnType<typeof render> {+ return render(+ <AllTheProviders>+ <TraceFlamegraph+ filteredSpanIds={[]}+ isFilterActive={false}+ selectedSpan={props.selectedSpan}+ totalSpansCount={props.totalSpansCount}+ />+ </AllTheProviders>,+ );+}++function makeSpan(spanId: string): SpanV3 {+ return { span_id: spanId } as SpanV3;+}++describe('TraceFlamegraph - selectedSpanId pass-through', () => {+ beforeEach(() => {+ mockUseGetTraceFlamegraph.mockReset();+ mockUseGetTraceFlamegraph.mockReturnValue({+ data: { payload: { spans: [] } },+ isFetching: false,+ error: null,+ } as never);+ });++ it('passes selectedSpanId: undefined when below sampling threshold and no selection', () => {+ renderFlamegraph({ selectedSpan: undefined, totalSpansCount: 500 });+ expect(mockUseGetTraceFlamegraph).toHaveBeenLastCalledWith(+ expect.objectContaining({ selectedSpanId: undefined }),+ );+ });++ it('omits selectedSpanId even when a span is selected, if trace is not sampled', () => {+ renderFlamegraph({ selectedSpan: makeSpan('abc'), totalSpansCount: 500 });+ expect(mockUseGetTraceFlamegraph).toHaveBeenLastCalledWith(+ expect.objectContaining({ selectedSpanId: undefined }),+ );+ });++ it('passes selectedSpan.span_id when trace is sampled and a span is selected', () => {+ renderFlamegraph({+ selectedSpan: makeSpan('abc'),+ totalSpansCount: 500_000,+ });+ expect(mockUseGetTraceFlamegraph).toHaveBeenLastCalledWith(+ expect.objectContaining({ selectedSpanId: 'abc' }),+ );+ });++ it('refetches with the new id when a different span is selected in sampled mode', () => {+ const { rerender } = renderFlamegraph({+ selectedSpan: makeSpan('abc'),+ totalSpansCount: 500_000,+ });+ rerender(+ <AllTheProviders>+ <TraceFlamegraph+ filteredSpanIds={[]}+ isFilterActive={false}+ selectedSpan={makeSpan('xyz')}+ totalSpansCount={500_000}+ />+ </AllTheProviders>,+ );+ expect(mockUseGetTraceFlamegraph).toHaveBeenLastCalledWith(+ expect.objectContaining({ selectedSpanId: 'xyz' }),+ );+ expect(mockUseGetTraceFlamegraph.mock.calls.length).toBeGreaterThanOrEqual(2);+ });++ it('treats totalSpansCount === FLAMEGRAPH_SPAN_LIMIT as non-sampled', () => {+ renderFlamegraph({+ selectedSpan: makeSpan('abc'),+ totalSpansCount: FLAMEGRAPH_SPAN_LIMIT,+ });+ expect(mockUseGetTraceFlamegraph).toHaveBeenLastCalledWith(+ expect.objectContaining({ selectedSpanId: undefined }),+ );+ });+});diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/useFlamegraphHover.test.tsx b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/useFlamegraphHover.test.tsxindex 743a29938b..de835ac126 100644--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/useFlamegraphHover.test.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/__tests__/useFlamegraphHover.test.tsx@@ -2,17 +2,12 @@ import React from 'react';import { act, renderHook } from '@testing-library/react';import { AllTheProviders } from 'tests/test-utils';-import { TraceProvider } from '../../contexts/TraceContext';import { useFlamegraphHover } from '../hooks/useFlamegraphHover';import type { SpanRect } from '../types';import { MOCK_SPAN, MOCK_TRACE_METADATA } from './testUtils';function wrapper({ children }: { children: React.ReactNode }): JSX.Element {- return (- <AllTheProviders>- <TraceProvider aggregations={undefined}>{children}</TraceProvider>- </AllTheProviders>- );+ return <AllTheProviders>{children}</AllTheProviders>;}function createMockCanvas(): HTMLCanvasElement {diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphDraw.ts b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphDraw.tsindex 7c161c2cec..af15a3d5ec 100644--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphDraw.ts+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphDraw.ts@@ -1,7 +1,7 @@import React, { RefObject, useCallback, useMemo, useRef } from 'react';import { themeColors } from 'constants/theme';import { generateColor } from 'lib/uPlotLib/utils/generateColor';-import { useTraceContext } from 'pages/TraceDetailsV3/contexts/TraceContext';+import { useTraceStore } from 'pages/TraceDetailsV3/stores/traceStore';import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';import { TelemetryFieldKey } from 'types/api/v5/queryRange';@@ -237,7 +237,7 @@ export function useFlamegraphDraw(const eventRectsRefInternal = useRef<EventRect[]>([]);const eventRectsRef = eventRectsRefProp ?? eventRectsRefInternal;- const { colorByField } = useTraceContext();+ const colorByField = useTraceStore((s) => s.colorByField);const filteredSpanIdsSet = useMemo(() => (isFilterActive && filteredSpanIds ? new Set(filteredSpanIds) : null),diff --git a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphHover.ts b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphHover.tsindex fb0ea5c7dc..7034d38c2e 100644--- a/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphHover.ts+++ b/frontend/src/pages/TraceDetailsV3/TraceFlamegraph/hooks/useFlamegraphHover.ts@@ -8,7 +8,7 @@ import {useRef,useState,} from 'react';-import { useTraceContext } from 'pages/TraceDetailsV3/contexts/TraceContext';+import { useTraceStore } from 'pages/TraceDetailsV3/stores/traceStore';import { RESERVED_PREVIEW_KEYS } from 'pages/TraceDetailsV3/SpanHoverCard/SpanHoverCard';import { getSpanAttribute } from 'pages/TraceDetailsV3/utils';import { FlamegraphSpan } from 'types/api/trace/getTraceFlamegraph';@@ -138,7 +138,8 @@ export function useFlamegraphHover(null,);- const { colorByField, previewFields } = useTraceContext();+ const colorByField = useTraceStore((s) => s.colorByField);+ const previewFields = useTraceStore((s) => s.previewFields);const buildPreviewRows = useCallback((span: FlamegraphSpan): SpanPreviewRowData[] =>diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsxindex 1282d6ad89..6dfebc1c79 100644--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Filters/Filters.tsx@@ -159,8 +159,21 @@ function Filters({expressionRef,runQuery,};- const { isHighlightErrors, handleToggle: handleToggleHighlightErrors } =+ const { isHighlightErrors, handleToggle: toggleHighlightErrors } =useHighlightErrors(filterProps);++ // Auto-expand the filter row when turning Highlight errors ON so the user+ // can immediately use prev/next navigation. Turning it OFF doesn't auto-+ // collapse — the user keeps whatever expansion state they had.+ const handleToggleHighlightErrors = useCallback(+ (checked: boolean): void => {+ if (checked && !isExpanded) {+ onExpand();+ }+ toggleHighlightErrors(checked);+ },+ [isExpanded, onExpand, toggleHighlightErrors],+ );const { selectedCategory, categories, handleCategoryChange } =useSpanCategoryFilter(filterProps);diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.styles.scss b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.styles.scssindex 8af9fffc61..2b8fc938f0 100644--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.styles.scss+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.styles.scss@@ -371,7 +371,7 @@// Right-aligns the badge inside so single-digit counts don't push the// icon left of where multi-digit counts would put it..subtree-count-slot {- min-width: 20px;+ min-width: 34px;flex-shrink: 0;display: inline-flex;align-items: center;diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsxindex 1c19eae6ce..3b00c2a584 100644--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/Success.tsx@@ -40,7 +40,8 @@ import {Link,ListPlus,} from '@signozhq/icons';-import { useTraceContext } from 'pages/TraceDetailsV3/contexts/TraceContext';+import { useTraceStore } from 'pages/TraceDetailsV3/stores/traceStore';+import { resolveSpanColor } from 'pages/TraceDetailsV3/utils';import { useBoundaryPagination } from 'pages/TraceDetailsV3/TraceWaterfall/hooks/useBoundaryPagination';import { useCrosshair } from 'pages/TraceDetailsV3/hooks/useCrosshair';import { ResizableBox } from 'periscope/components/ResizableBox';@@ -212,9 +213,9 @@ const SpanOverview = memo(function SpanOverview({}): JSX.Element {const isRootSpan = span.level === 0;const { onSpanCopy } = useCopySpanLink(span);- const { resolveSpanColor } = useTraceContext();+ const colorByFieldName = useTraceStore((s) => s.colorByField.name);- const color = resolveSpanColor(span);+ const color = resolveSpanColor(span, colorByFieldName);// Smart highlighting logicconst {@@ -389,8 +390,8 @@ export const SpanDuration = memo(function SpanDuration({const leftOffset = ((span.timestamp - traceMetadata.startTime) * 1e2) / spread;const width = (span.duration_nano * 1e2) / (spread * 1e6);- const { resolveSpanColor } = useTraceContext();- const color = resolveSpanColor(span);+ const colorByFieldName = useTraceStore((s) => s.colorByField.name);+ const color = resolveSpanColor(span, colorByFieldName);// `resolveSpanColor` returns a CSS variable for errors; `colorToRgb` can't parse it.const rgbColor = span.has_error ? '239, 68, 68' : colorToRgb(color);@@ -585,7 +586,6 @@ function Success(props: ISuccessProps): JSX.Element {setInterestedSpanId({spanId,isUncollapsed: !collapse,- scrollToSpan: false,});},[isFullDataLoaded, setLocalUncollapsedNodes, setInterestedSpanId],@@ -740,15 +740,24 @@ function Success(props: ISuccessProps): JSX.Element {);}, [spans, sidebarWidth]);- // Scroll to interested span — only when scrollToSpan is true (URL nav, flamegraph click, initial load)- // Skip for collapse/uncollapse to avoid jarring scroll jumps+ // Scroll to the interested span only when it isn't already on screen.+ // Covers every entry point uniformly: deep-link, flamegraph click,+ // filter prev/next, browser back/forward all scroll only if needed;+ // waterfall row clicks and chevron expand/collapse don't yank the viewport+ // because the affected row is by definition already visible.useEffect(() => {if (interestedSpanId.spanId !== '' && virtualizerRef.current) {const idx = spans.findIndex((span) => span.span_id === interestedSpanId.spanId,);if (idx !== -1) {- if (interestedSpanId.scrollToSpan !== false) {+ const visible = virtualizerRef.current.getVirtualItems();+ const isOnScreen =+ visible.length > 0 &&+ idx >= visible[0].index &&+ idx <= visible[visible.length - 1].index;++ if (!isOnScreen) {setTimeout(() => {virtualizerRef.current?.scrollToIndex(idx, {align: 'center',diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/SpanDuration.test.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/SpanDuration.test.tsxindex 9899acdb5e..595070e4cd 100644--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/SpanDuration.test.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/SpanDuration.test.tsx@@ -2,11 +2,10 @@ import useUrlQuery from 'hooks/useUrlQuery';import { fireEvent, render, screen } from 'tests/test-utils';import { SpanV3 } from 'types/api/trace/getTraceV3';-import { TraceProvider } from '../../../../contexts/TraceContext';import { SpanDuration } from '../Success';const renderWithTraceProvider: typeof render = (ui, options) =>- render(<TraceProvider aggregations={undefined}>{ui}</TraceProvider>, options);+ render(ui, options);// Constants to avoid string duplicationconst SPAN_DURATION_TEXT = '1.16 ms';diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/UnifiedSpanClick.test.tsx b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/UnifiedSpanClick.test.tsxindex c2bd980d61..5e884feba7 100644--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/UnifiedSpanClick.test.tsx+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/TraceWaterfallStates/Success/__tests__/UnifiedSpanClick.test.tsx@@ -2,15 +2,10 @@ import React from 'react';import { render, screen, userEvent, waitFor } from 'tests/test-utils';import { SpanV3 } from 'types/api/trace/getTraceV3';-import { TraceProvider } from '../../../../contexts/TraceContext';import Success from '../Success';const renderWithTraceProvider: typeof render = (ui, options, customOptions) =>- render(- <TraceProvider aggregations={undefined}>{ui}</TraceProvider>,- options,- customOptions,- );+ render(ui, options, customOptions);// Mock the required hooks with proper typingconst mockSafeNavigate = jest.fn() as jest.MockedFunction<diff --git a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/types.ts b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/types.tsindex f5b246c732..92b8b6bb89 100644--- a/frontend/src/pages/TraceDetailsV3/TraceWaterfall/types.ts+++ b/frontend/src/pages/TraceDetailsV3/TraceWaterfall/types.ts@@ -1,5 +1,4 @@export interface IInterestedSpan {spanId: string;isUncollapsed: boolean;- scrollToSpan?: boolean;}diff --git a/frontend/src/pages/TraceDetailsV3/constants.ts b/frontend/src/pages/TraceDetailsV3/constants.tsindex d579b236b5..bd7b571233 100644--- a/frontend/src/pages/TraceDetailsV3/constants.ts+++ b/frontend/src/pages/TraceDetailsV3/constants.ts@@ -12,7 +12,7 @@ export const COLOR_BY_OPTIONS: ColorByOption[] = [fieldContext: 'resource',fieldDataType: 'string',},- label: 'Service',+ label: 'service.name',},{field: {@@ -20,7 +20,7 @@ export const COLOR_BY_OPTIONS: ColorByOption[] = [fieldContext: 'resource',fieldDataType: 'string',},- label: 'Namespace',+ label: 'service.namespace',},{field: {@@ -28,7 +28,7 @@ export const COLOR_BY_OPTIONS: ColorByOption[] = [fieldContext: 'resource',fieldDataType: 'string',},- label: 'Host',+ label: 'host.name',},{field: {@@ -36,7 +36,7 @@ export const COLOR_BY_OPTIONS: ColorByOption[] = [fieldContext: 'resource',fieldDataType: 'string',},- label: 'Node',+ label: 'k8s.node.name',},{field: {@@ -44,7 +44,7 @@ export const COLOR_BY_OPTIONS: ColorByOption[] = [fieldContext: 'resource',fieldDataType: 'string',},- label: 'Container',+ label: 'k8s.container.name',},];diff --git a/frontend/src/pages/TraceDetailsV3/contexts/TraceContext.tsx b/frontend/src/pages/TraceDetailsV3/contexts/TraceContext.tsxdeleted file mode 100644index efd0432373..0000000000--- a/frontend/src/pages/TraceDetailsV3/contexts/TraceContext.tsx+++ /dev/null@@ -1,220 +0,0 @@-import {- // oxlint-disable-next-line no-restricted-imports- createContext,- ReactNode,- useCallback,- // oxlint-disable-next-line no-restricted-imports- useContext,- useMemo,-} from 'react';-import { useMutation } from 'react-query';-import updateUserPreferenceAPI from 'api/v1/user/preferences/name/update';-import { themeColors } from 'constants/theme';-import { USER_PREFERENCES } from 'constants/userPreferences';-import { generateColor } from 'lib/uPlotLib/utils/generateColor';-import { useAppContext } from 'providers/App/App';-import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';-import { TelemetryFieldKey } from 'types/api/v5/queryRange';-import {- SpanV3,- WaterfallAggregationResponse,- WaterfallAggregationType,-} from 'types/api/trace/getTraceV3';--import {- ColorByOption,- COLOR_BY_FIELDS,- COLOR_BY_OPTIONS,- DEFAULT_COLOR_BY_FIELD,-} from '../constants';-import { getSpanAttribute } from '../utils';-import {- AGGREGATIONS,- getAggregationMap as findAggregationMap,-} from '../utils/aggregations';--interface TraceContextValue {- colorByField: TelemetryFieldKey;- setColorByField: (field: TelemetryFieldKey) => void;- aggregations: WaterfallAggregationResponse[] | undefined;- getAggregationMap: (- type: WaterfallAggregationType,- ) => Record<string, number> | undefined;- getSpanGroupValue: (span: SpanV3) => string;- resolveSpanColor: (span: SpanV3) => string;- /**- * Subset of COLOR_BY_OPTIONS whose data is populated on the current trace.- * `service.name` is always included; host/container only when their- * aggregation `value` map has entries.- */- availableColorByOptions: ColorByOption[];- /**- * Per-user preview fields (selected via the floating "Preview fields"- * panel). Stored in `span_details_preview_attributes` user pref. Will be- * consumed by the flamegraph `selectFields` request and the waterfall +- * flamegraph hover popovers in follow-up phases.- */- previewFields: BaseAutocompleteData[];- setPreviewFields: (next: BaseAutocompleteData[]) => void;-}--const TraceContext = createContext<TraceContextValue | null>(null);--export function TraceProvider({- aggregations,- children,-}: {- aggregations: WaterfallAggregationResponse[] | undefined;- children: ReactNode;-}): JSX.Element | null {- const { userPreferences, updateUserPreferenceInContext } = useAppContext();- const { mutate: updateUserPreferenceMutation } = useMutation(- updateUserPreferenceAPI,- );-- // Source of truth: user-preferences API (loaded once on app init via- // AppProvider). Render nothing until it resolves so we never paint the- // default colour first and then swap to the user's persisted choice.- // AppProvider fires the prefs query as soon as the user is logged in, so- // this is usually already settled by the time TraceDetailsV3 mounts.- const persistedColorByField = useMemo<TelemetryFieldKey>(() => {- const pref = userPreferences?.find(- (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_COLOR_BY_ATTRIBUTE,- );- const name = (pref?.value as string) || '';- return COLOR_BY_FIELDS.find((f) => f.name === name) ?? DEFAULT_COLOR_BY_FIELD;- }, [userPreferences]);-- const setColorByField = useCallback(- (field: TelemetryFieldKey): void => {- // Optimistically reflect the choice in the in-memory cache so the UI- // reacts immediately (the GET /user/preferences response on app init- // always includes the registered key, so `existing` will be defined).- const existing = userPreferences?.find(- (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_COLOR_BY_ATTRIBUTE,- );- if (existing) {- updateUserPreferenceInContext({ ...existing, value: field.name });- }- updateUserPreferenceMutation({- name: USER_PREFERENCES.SPAN_DETAILS_COLOR_BY_ATTRIBUTE,- value: field.name,- });- },- [- userPreferences,- updateUserPreferenceInContext,- updateUserPreferenceMutation,- ],- );-- const previewFields = useMemo<BaseAutocompleteData[]>(() => {- const pref = userPreferences?.find(- (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PREVIEW_ATTRIBUTES,- );- const raw = (pref?.value as BaseAutocompleteData[] | undefined) ?? [];- // Defensive: keep only entries that have a string `key`.- return raw.filter(- (f): f is BaseAutocompleteData =>- typeof f === 'object' &&- f !== null &&- typeof (f as { key?: unknown }).key === 'string',- );- }, [userPreferences]);-- const setPreviewFields = useCallback(- (next: BaseAutocompleteData[]): void => {- const existing = userPreferences?.find(- (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PREVIEW_ATTRIBUTES,- );- if (existing) {- updateUserPreferenceInContext({ ...existing, value: next });- }- updateUserPreferenceMutation({- name: USER_PREFERENCES.SPAN_DETAILS_PREVIEW_ATTRIBUTES,- value: next,- });- },- [- userPreferences,- updateUserPreferenceInContext,- updateUserPreferenceMutation,- ],- );-- const value = useMemo<TraceContextValue>(() => {- const isFieldAvailable = (fieldName: string): boolean => {- if (fieldName === DEFAULT_COLOR_BY_FIELD.name) {- return true;- }- // Pick any aggregation type — if execution_time_percentage is empty,- // span_count for the same field will be too (both are derived from- // the same set of spans).- const map = findAggregationMap(- aggregations,- AGGREGATIONS.EXEC_TIME_PCT,- fieldName,- );- return !!map && Object.keys(map).length > 0;- };-- const availableColorByOptions = COLOR_BY_OPTIONS.filter((opt) =>- isFieldAvailable(opt.field.name),- );-- const colorByField =- aggregations === undefined || isFieldAvailable(persistedColorByField.name)- ? persistedColorByField- : DEFAULT_COLOR_BY_FIELD;-- const getAggregationMap = (- type: WaterfallAggregationType,- ): Record<string, number> | undefined =>- findAggregationMap(aggregations, type, colorByField.name);-- const getSpanGroupValue = (span: SpanV3): string =>- getSpanAttribute(span, colorByField.name) || 'unknown';-- const resolveSpanColor = (span: SpanV3): string => {- if (span.has_error) {- return 'var(--bg-cherry-500)';- }- return generateColor(- getSpanGroupValue(span),- themeColors.traceDetailColorsV3,- );- };-- return {- colorByField,- setColorByField,- aggregations,- getAggregationMap,- getSpanGroupValue,- resolveSpanColor,- availableColorByOptions,- previewFields,- setPreviewFields,- };- }, [- persistedColorByField,- aggregations,- setColorByField,- previewFields,- setPreviewFields,- ]);-- if (!userPreferences) {- return null;- }-- return <TraceContext.Provider value={value}>{children}</TraceContext.Provider>;-}--export function useTraceContext(): TraceContextValue {- const ctx = useContext(TraceContext);- if (!ctx) {- throw new Error('useTraceContext must be used inside TraceProvider');- }- return ctx;-}diff --git a/frontend/src/pages/TraceDetailsV3/hooks/__tests__/useMigratePinnedAttributes.test.ts b/frontend/src/pages/TraceDetailsV3/hooks/__tests__/useMigratePinnedAttributes.test.tsnew file mode 100644index 0000000000..550090cc45--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/hooks/__tests__/useMigratePinnedAttributes.test.ts@@ -0,0 +1,155 @@+import { SpanV3 } from 'types/api/trace/getTraceV3';++import {+ migrateV2ToV3Entries,+ v2KeyToPath,+} from '../useMigratePinnedAttributes';++function makeSpan(overrides: Partial<SpanV3> = {}): SpanV3 {+ return {+ span_id: 'span-1',+ trace_id: 'trace-1',+ parent_span_id: '',+ timestamp: 0,+ duration_nano: 0,+ name: 'test-span',+ 'service.name': 'test-svc',+ has_error: false,+ status_message: '',+ status_code: 0,+ status_code_string: '',+ attributes: {},+ resource: {},+ ...overrides,+ } as SpanV3;+}++describe('v2KeyToPath', () => {+ it('returns attributes path when key is in span.attributes', () => {+ const span = makeSpan({ attributes: { 'http.method': 'GET' } });+ expect(v2KeyToPath('http.method', span)).toStrictEqual([+ 'attributes',+ 'http.method',+ ]);+ });++ it('returns resource path when key is only in span.resource', () => {+ const span = makeSpan({ resource: { 'service.name': 'svc' } });+ expect(v2KeyToPath('service.name', span)).toStrictEqual([+ 'resource',+ 'service.name',+ ]);+ });++ it('prefers attributes over resource when key exists in both', () => {+ const span = makeSpan({+ attributes: { foo: 'a' },+ resource: { foo: 'r' },+ });+ expect(v2KeyToPath('foo', span)).toStrictEqual(['attributes', 'foo']);+ });++ it('returns top-level path when key is on the span root', () => {+ const span = makeSpan({ attributes: {}, resource: {} });+ // `name` is a top-level field on SpanV3+ expect(v2KeyToPath('name', span)).toStrictEqual(['name']);+ });++ it('returns null when key is not found anywhere', () => {+ const span = makeSpan({ attributes: {}, resource: {} });+ expect(v2KeyToPath('unknown.key', span)).toBeNull();+ });+});++describe('migrateV2ToV3Entries', () => {+ const span = makeSpan({+ attributes: { 'http.method': 'GET', 'db.system': 'postgres' },+ resource: { 'service.name': 'svc' },+ });++ it('returns empty result for empty input', () => {+ expect(migrateV2ToV3Entries([], span)).toStrictEqual({+ next: [],+ convertedAny: false,+ stillHasV2: false,+ });+ });++ it('passes V3 entries through unchanged', () => {+ const v3Entry = '["attributes","http.method"]';+ expect(migrateV2ToV3Entries([v3Entry], span)).toStrictEqual({+ next: [v3Entry],+ convertedAny: false,+ stillHasV2: false,+ });+ });++ it('converts a resolvable V2 entry under attributes', () => {+ const result = migrateV2ToV3Entries(['http.method'], span);+ expect(result.next).toStrictEqual(['["attributes","http.method"]']);+ expect(result.convertedAny).toBe(true);+ expect(result.stillHasV2).toBe(false);+ });++ it('converts a resolvable V2 entry under resource', () => {+ const result = migrateV2ToV3Entries(['service.name'], span);+ expect(result.next).toStrictEqual(['["resource","service.name"]']);+ expect(result.convertedAny).toBe(true);+ expect(result.stillHasV2).toBe(false);+ });++ it('preserves an unresolvable V2 entry as-is', () => {+ const result = migrateV2ToV3Entries(['unknown.key'], span);+ expect(result.next).toStrictEqual(['unknown.key']);+ expect(result.convertedAny).toBe(false);+ expect(result.stillHasV2).toBe(true);+ });++ it('handles a mixed array: V3 + resolvable V2 + unresolvable V2', () => {+ const v3Entry = '["attributes","http.method"]';+ const result = migrateV2ToV3Entries(+ [v3Entry, 'db.system', 'unknown.key'],+ span,+ );+ expect(result.next).toStrictEqual([+ v3Entry,+ '["attributes","db.system"]',+ 'unknown.key',+ ]);+ expect(result.convertedAny).toBe(true);+ expect(result.stillHasV2).toBe(true);+ });++ it('preserves input order in next[]', () => {+ const result = migrateV2ToV3Entries(+ ['unknown.key', 'http.method', 'service.name'],+ span,+ );+ expect(result.next).toStrictEqual([+ 'unknown.key',+ '["attributes","http.method"]',+ '["resource","service.name"]',+ ]);+ });++ it('on a different span, previously-unresolvable entries can now resolve', () => {+ // First span doesn't have db.system.+ const httpSpan = makeSpan({+ attributes: { 'http.method': 'GET' },+ resource: {},+ });+ const first = migrateV2ToV3Entries(['db.system'], httpSpan);+ expect(first.stillHasV2).toBe(true);+ expect(first.next).toStrictEqual(['db.system']);++ // Same entries on a DB span now resolve.+ const dbSpan = makeSpan({+ attributes: { 'db.system': 'postgres' },+ resource: {},+ });+ const second = migrateV2ToV3Entries(first.next, dbSpan);+ expect(second.convertedAny).toBe(true);+ expect(second.stillHasV2).toBe(false);+ expect(second.next).toStrictEqual(['["attributes","db.system"]']);+ });+});diff --git a/frontend/src/pages/TraceDetailsV3/hooks/useMigratePinnedAttributes.ts b/frontend/src/pages/TraceDetailsV3/hooks/useMigratePinnedAttributes.tsindex 0395611085..5d5dd2e32f 100644--- a/frontend/src/pages/TraceDetailsV3/hooks/useMigratePinnedAttributes.ts+++ b/frontend/src/pages/TraceDetailsV3/hooks/useMigratePinnedAttributes.ts@@ -11,13 +11,15 @@ import { SpanV3 } from 'types/api/trace/getTraceV3';* V2 stored pinned attributes as flat strings (`["http.method"]`).* V3 stores nested key paths (`['["attributes","http.method"]']`).*- * On first load with both `userPreferences` and `selectedSpan` available,- * detect a V2-format value in the backend pref and convert it to V3 paths- * using the loaded span's shape. Idempotent: once written in V3 format the- * format check on subsequent loads short-circuits.+ * On every spanId change while there are still V2-shape entries in the pref,+ * detect V2 entries and convert them to V3 paths using the loaded span's+ * shape. Idempotent: once everything is V3 the gate flips and the hook+ * short-circuits on subsequent renders.*- * Unmappable keys (not present on the loaded span) are dropped — we can't- * determine whether they belong under `attributes`, `resource`, or top-level.+ * Unmappable keys (not present on the loaded span) are preserved as V2-shape+ * in the pref. They get a chance to convert when a future span containing+ * them loads. The V3 read path (`useTracePinnedFields.value`) filters V2+ * leftovers out of PrettyView so they don't render half-resolved.*/export function useMigratePinnedAttributes(selectedSpan: SpanV3 | undefined,@@ -43,29 +45,18 @@ export function useMigratePinnedAttributes(return;}- // Walk every entry — the array may be mixed (e.g. some legacy V2 flat- // keys saved alongside V3 paths). V3 entries pass through unchanged;- // V2 entries get converted via the loaded span; unmappable V2 entries- // are dropped. We only persist when at least one V2 entry was found- // (otherwise the input is already V3-clean).- const next: string[] = [];- let hadV2Entry = false;+ const { next, convertedAny, stillHasV2 } = migrateV2ToV3Entries(+ value,+ selectedSpan,+ );- for (const entry of value) {- if (isV3PinnedAttribute(entry)) {- next.push(entry);- continue;- }- hadV2Entry = true;- const path = v2KeyToPath(entry, selectedSpan);- if (path) {- next.push(serializeKeyPath(path));+ if (!convertedAny) {+ // Nothing to persist this round. Mark done only when there's nothing+ // left to retry; otherwise leave ranRef false so the next spanId+ // change gets a chance at the lingering V2 entries.+ if (!stillHasV2) {+ ranRef.current = true;}- // else: unmappable on the loaded span — drop- }-- if (!hadV2Entry) {- ranRef.current = true;return;}@@ -79,10 +70,10 @@ export function useMigratePinnedAttributes(},{onSuccess: () => {- ranRef.current = true;+ ranRef.current = !stillHasV2;},onError: () => {- // Roll back the optimistic context update+ // Roll back the optimistic context updatexwif (pref) {updateUserPreferenceInContext({ ...pref, value });}@@ -92,7 +83,15 @@ export function useMigratePinnedAttributes(}, [userPreferences, selectedSpan, updateUserPreferenceInContext, mutate]);}-function v2KeyToPath(key: string, span: SpanV3): (string | number)[] | null {+/**+ * Find where a V2 flat key lives on a span. Returns the V3 path tuple if+ * the key is present in `attributes`, `resource`, or as a top-level field,+ * otherwise `null`.+ */+export function v2KeyToPath(+ key: string,+ span: SpanV3,+): (string | number)[] | null {if (span.attributes && key in span.attributes) {return ['attributes', key];}@@ -104,3 +103,34 @@ function v2KeyToPath(key: string, span: SpanV3): (string | number)[] | null {}return null;}++/**+ * Pure migration logic — walk `value` once and produce the V3-converted+ * array plus two flags describing what happened. See the hook above for+ * how the flags drive write/retry decisions.+ */+export function migrateV2ToV3Entries(+ value: string[],+ span: SpanV3,+): { next: string[]; convertedAny: boolean; stillHasV2: boolean } {+ const next: string[] = [];+ let convertedAny = false;+ let stillHasV2 = false;++ for (const entry of value) {+ if (isV3PinnedAttribute(entry)) {+ next.push(entry);+ continue;+ }+ const path = v2KeyToPath(entry, span);+ if (path) {+ next.push(serializeKeyPath(path));+ convertedAny = true;+ } else {+ next.push(entry);+ stillHasV2 = true;+ }+ }++ return { next, convertedAny, stillHasV2 };+}diff --git a/frontend/src/pages/TraceDetailsV3/index.tsx b/frontend/src/pages/TraceDetailsV3/index.tsxindex d720dd6b22..6307d93b00 100644--- a/frontend/src/pages/TraceDetailsV3/index.tsx+++ b/frontend/src/pages/TraceDetailsV3/index.tsx@@ -1,6 +1,7 @@/* eslint-disable sonarjs/cognitive-complexity */import { useCallback, useEffect, useMemo, useRef, useState } from 'react';import { useParams } from 'react-router-dom';+import { ChartNoAxesGantt, TriangleAlert } from '@signozhq/icons';import getLocalStorageKey from 'api/browser/localstorage/get';import setLocalStorageKey from 'api/browser/localstorage/set';import { Collapse } from 'antd';@@ -19,7 +20,7 @@ import {} from 'types/api/trace/getTraceV3';import { COLOR_BY_FIELDS } from './constants';-import { TraceProvider } from './contexts/TraceContext';+import TraceStoreSync from './stores/TraceStoreSync';import { AGGREGATIONS } from './utils/aggregations';import { SpanDetailVariant } from './SpanDetailsPanel/constants';import SpanDetailsPanel from './SpanDetailsPanel/SpanDetailsPanel';@@ -40,7 +41,6 @@ function TraceDetailsV3(): JSX.Element {() => ({spanId: urlQuery.get('spanId') || '',isUncollapsed: urlQuery.get('spanId') !== '',- scrollToSpan: true,}),);const [uncollapsedNodes, setUncollapsedNodes] = useState<string[]>([]);@@ -82,7 +82,6 @@ function TraceDetailsV3(): JSX.Element {setInterestedSpanId({spanId,isUncollapsed: true,- scrollToSpan: true,});}, [urlQuery]);@@ -285,7 +284,7 @@ function TraceDetailsV3(): JSX.Element {);return (- <TraceProvider aggregations={traceData?.payload?.aggregations}>+ <TraceStoreSync aggregations={traceData?.payload?.aggregations}><div className="trace-details-v3"><TraceDetailsHeaderfilterMetadata={filterMetadata}@@ -311,26 +310,32 @@ function TraceDetailsV3(): JSX.Element {key: 'flame',label: (<div className="trace-details-v3__collapse-label">- <span>Flame Graph</span>+ <span className="trace-details-v3__collapse-title">+ Flame Graph+ {traceData?.payload?.totalSpansCount &&+ traceData.payload.totalSpansCount > FLAMEGRAPH_SPAN_LIMIT && (+ <WarningPopover+ message="The total span count exceeds the visualization limit. Displaying a sampled subset of spans in flamegraph."+ placement="bottomLeft"+ />+ )}+ </span>{traceData?.payload?.totalSpansCount ? (<span className="trace-details-v3__collapse-count">- <span>Spans: {traceData.payload.totalSpansCount}</span>+ <span className="trace-details-v3__collapse-count-item">+ <ChartNoAxesGantt size={13} />+ Spans: {traceData.payload.totalSpansCount}+ </span><span- className={+ className={`trace-details-v3__collapse-count-item${traceData.payload.totalErrorSpansCount > 0- ? 'trace-details-v3__collapse-count-errors'- : undefined- }+ ? ' trace-details-v3__collapse-count-errors'+ : ''+ }`}>+ <TriangleAlert size={13} />Errors: {traceData.payload.totalErrorSpansCount ?? 0}</span>- {traceData.payload.totalSpansCount > FLAMEGRAPH_SPAN_LIMIT && (- <WarningPopover- message="The total span count exceeds the visualization limit. Displaying a sampled subset of spans in flamegraph."- placement="bottomRight"- autoAdjustOverflow={false}- />- )}</span>) : null}</div>@@ -340,6 +345,8 @@ function TraceDetailsV3(): JSX.Element {<TraceFlamegraphfilteredSpanIds={filteredSpanIds}isFilterActive={isFilterActive}+ selectedSpan={selectedSpan}+ totalSpansCount={totalSpansCount}/></ResizableBox>),@@ -394,7 +401,7 @@ function TraceDetailsV3(): JSX.Element {</>)}</div>- </TraceProvider>+ </TraceStoreSync>);}diff --git a/frontend/src/pages/TraceDetailsV3/stores/TraceStoreSync.tsx b/frontend/src/pages/TraceDetailsV3/stores/TraceStoreSync.tsxnew file mode 100644index 0000000000..ee4252c6b7--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/stores/TraceStoreSync.tsx@@ -0,0 +1,56 @@+import { ReactNode, useEffect } from 'react';+import { useMutation } from 'react-query';+import updateUserPreferenceAPI from 'api/v1/user/preferences/name/update';+import { useAppContext } from 'providers/App/App';+import { WaterfallAggregationResponse } from 'types/api/trace/getTraceV3';++import {+ setTraceStoreAggregations,+ setTraceStoreCallbacks,+ setTraceStoreUserPreferences,+} from './traceStore';++interface TraceStoreSyncProps {+ aggregations: WaterfallAggregationResponse[] | undefined;+ children: ReactNode;+}++/**+ * Bridges React-managed inputs (the `aggregations` prop, `userPreferences`+ * from AppContext, and the user-pref mutation hook) into the Zustand store.+ *+ * Renders nothing until `userPreferences` resolves so the flamegraph never+ * paints with the default colour first and then swaps to the user's+ * persisted choice. AppProvider fires the prefs query as soon as the user+ * is logged in, so this gate is usually already settled by mount time.+ */+function TraceStoreSync({+ aggregations,+ children,+}: TraceStoreSyncProps): JSX.Element | null {+ const { userPreferences, updateUserPreferenceInContext } = useAppContext();+ const { mutate: mutateUserPreference } = useMutation(updateUserPreferenceAPI);++ useEffect(() => {+ setTraceStoreAggregations(aggregations);+ }, [aggregations]);++ useEffect(() => {+ setTraceStoreUserPreferences(userPreferences ?? null);+ }, [userPreferences]);++ useEffect(() => {+ setTraceStoreCallbacks({+ updateUserPreferenceInContext,+ mutateUserPreference,+ });+ }, [updateUserPreferenceInContext, mutateUserPreference]);++ if (!userPreferences) {+ return null;+ }++ return <>{children}</>;+}++export default TraceStoreSync;diff --git a/frontend/src/pages/TraceDetailsV3/stores/traceStore.ts b/frontend/src/pages/TraceDetailsV3/stores/traceStore.tsnew file mode 100644index 0000000000..0375156459--- /dev/null+++ b/frontend/src/pages/TraceDetailsV3/stores/traceStore.ts@@ -0,0 +1,238 @@+import { USER_PREFERENCES } from 'constants/userPreferences';+import { UserPreference } from 'types/api/preferences/preference';+import { BaseAutocompleteData } from 'types/api/queryBuilder/queryAutocompleteResponse';+import { WaterfallAggregationResponse } from 'types/api/trace/getTraceV3';+import { TelemetryFieldKey } from 'types/api/v5/queryRange';+import { create } from 'zustand';++import {+ COLOR_BY_FIELDS,+ COLOR_BY_OPTIONS,+ ColorByOption,+ DEFAULT_COLOR_BY_FIELD,+} from '../constants';+import {+ AGGREGATIONS,+ getAggregationMap as findAggregationMap,+} from '../utils/aggregations';++interface MutateOptions {+ onSuccess?: () => void;+ onError?: () => void;+}++type UpdateUserPreferenceInContext = (preference: UserPreference) => void;+type MutateUserPreference = (+ variables: { name: string; value: unknown },+ options?: MutateOptions,+) => void;++interface TraceStoreState {+ // --- Inputs synced from React layer via TraceStoreSync ---+ aggregations: WaterfallAggregationResponse[] | undefined;+ userPreferences: UserPreference[] | null;+ updateUserPreferenceInContext: UpdateUserPreferenceInContext | null;+ mutateUserPreference: MutateUserPreference | null;++ // --- Derived state (cached for reference stability) ---+ colorByField: TelemetryFieldKey;+ availableColorByOptions: ColorByOption[];+ previewFields: BaseAutocompleteData[];++ // --- Setters used only by TraceStoreSync ---+ setAggregations: (+ aggregations: WaterfallAggregationResponse[] | undefined,+ ) => void;+ setUserPreferences: (userPreferences: UserPreference[] | null) => void;+ setCallbacks: (callbacks: {+ updateUserPreferenceInContext: UpdateUserPreferenceInContext;+ mutateUserPreference: MutateUserPreference;+ }) => void;++ // --- Public actions (called from components) ---+ setColorByField: (field: TelemetryFieldKey) => void;+ setPreviewFields: (next: BaseAutocompleteData[]) => void;+}++/**+ * Reads the persisted color-by field name from user preferences and resolves+ * it to a `TelemetryFieldKey`. Falls back to default when unset or invalid.+ */+function getPersistedColorByField(+ userPreferences: UserPreference[] | null,+): TelemetryFieldKey {+ const pref = userPreferences?.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_COLOR_BY_ATTRIBUTE,+ );+ const name = (pref?.value as string) || '';+ return COLOR_BY_FIELDS.find((f) => f.name === name) ?? DEFAULT_COLOR_BY_FIELD;+}++/**+ * Re-derives `colorByField` + `availableColorByOptions` from the two inputs.+ * Preserves the "trust persisted while aggregations load" rule so the+ * flamegraph doesn't repaint when the aggregations response arrives.+ */+function deriveColorState(+ aggregations: WaterfallAggregationResponse[] | undefined,+ userPreferences: UserPreference[] | null,+): Pick<TraceStoreState, 'colorByField' | 'availableColorByOptions'> {+ const isFieldAvailable = (fieldName: string): boolean => {+ if (fieldName === DEFAULT_COLOR_BY_FIELD.name) {+ return true;+ }+ const map = findAggregationMap(+ aggregations,+ AGGREGATIONS.EXEC_TIME_PCT,+ fieldName,+ );+ return !!map && Object.keys(map).length > 0;+ };++ const availableColorByOptions = COLOR_BY_OPTIONS.filter((opt) =>+ isFieldAvailable(opt.field.name),+ );++ const persistedColorByField = getPersistedColorByField(userPreferences);+ // While aggregations are loading, trust persisted — don't flip to default+ // just because we haven't confirmed availability yet.+ const colorByField =+ aggregations === undefined || isFieldAvailable(persistedColorByField.name)+ ? persistedColorByField+ : DEFAULT_COLOR_BY_FIELD;++ return { colorByField, availableColorByOptions };+}++/**+ * Reads preview fields from user preferences and filters out malformed entries.+ */+function derivePreviewFields(+ userPreferences: UserPreference[] | null,+): BaseAutocompleteData[] {+ const pref = userPreferences?.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PREVIEW_ATTRIBUTES,+ );+ const raw = (pref?.value as BaseAutocompleteData[] | undefined) ?? [];+ return raw.filter(+ (f): f is BaseAutocompleteData =>+ typeof f === 'object' &&+ f !== null &&+ typeof (f as { key?: unknown }).key === 'string',+ );+}++export const useTraceStore = create<TraceStoreState>()((set, get) => ({+ aggregations: undefined,+ userPreferences: null,+ updateUserPreferenceInContext: null,+ mutateUserPreference: null,++ colorByField: DEFAULT_COLOR_BY_FIELD,+ availableColorByOptions: COLOR_BY_OPTIONS.filter(+ (opt) => opt.field.name === DEFAULT_COLOR_BY_FIELD.name,+ ),+ previewFields: [],++ setAggregations: (aggregations): void => {+ const { userPreferences } = get();+ set({+ aggregations,+ ...deriveColorState(aggregations, userPreferences),+ });+ },++ setUserPreferences: (userPreferences): void => {+ const { aggregations } = get();+ set({+ userPreferences,+ ...deriveColorState(aggregations, userPreferences),+ previewFields: derivePreviewFields(userPreferences),+ });+ },++ setCallbacks: ({+ updateUserPreferenceInContext,+ mutateUserPreference,+ }): void => set({ updateUserPreferenceInContext, mutateUserPreference }),++ setColorByField: (field): void => {+ const {+ userPreferences,+ updateUserPreferenceInContext,+ mutateUserPreference,+ } = get();+ if (+ !userPreferences ||+ !updateUserPreferenceInContext ||+ !mutateUserPreference+ ) {+ return;+ }++ const existing = userPreferences.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_COLOR_BY_ATTRIBUTE,+ );+ if (!existing) {+ return;+ }++ const previousValue = existing.value;+ updateUserPreferenceInContext({ ...existing, value: field.name });+ mutateUserPreference(+ {+ name: USER_PREFERENCES.SPAN_DETAILS_COLOR_BY_ATTRIBUTE,+ value: field.name,+ },+ {+ onError: (): void =>+ updateUserPreferenceInContext({ ...existing, value: previousValue }),+ },+ );+ },++ setPreviewFields: (next): void => {+ const {+ userPreferences,+ updateUserPreferenceInContext,+ mutateUserPreference,+ } = get();+ if (+ !userPreferences ||+ !updateUserPreferenceInContext ||+ !mutateUserPreference+ ) {+ return;+ }++ const existing = userPreferences.find(+ (p) => p.name === USER_PREFERENCES.SPAN_DETAILS_PREVIEW_ATTRIBUTES,+ );+ if (!existing) {+ return;+ }++ const previousValue = existing.value;+ updateUserPreferenceInContext({ ...existing, value: next });+ mutateUserPreference(+ { name: USER_PREFERENCES.SPAN_DETAILS_PREVIEW_ATTRIBUTES, value: next },+ {+ onError: (): void =>+ updateUserPreferenceInContext({ ...existing, value: previousValue }),+ },+ );+ },+}));++export const setTraceStoreAggregations = (+ aggregations: WaterfallAggregationResponse[] | undefined,+): void => useTraceStore.getState().setAggregations(aggregations);++export const setTraceStoreUserPreferences = (+ userPreferences: UserPreference[] | null,+): void => useTraceStore.getState().setUserPreferences(userPreferences);++export const setTraceStoreCallbacks = (callbacks: {+ updateUserPreferenceInContext: UpdateUserPreferenceInContext;+ mutateUserPreference: MutateUserPreference;+}): void => useTraceStore.getState().setCallbacks(callbacks);diff --git a/frontend/src/pages/TraceDetailsV3/utils.ts b/frontend/src/pages/TraceDetailsV3/utils.tsindex 290df9d273..f90ed392d0 100644--- a/frontend/src/pages/TraceDetailsV3/utils.ts+++ b/frontend/src/pages/TraceDetailsV3/utils.ts@@ -1,3 +1,5 @@+import { themeColors } from 'constants/theme';+import { generateColor } from 'lib/uPlotLib/utils/generateColor';import { SpanV3 } from 'types/api/trace/getTraceV3';/**@@ -75,3 +77,33 @@ export function isV3PinnedAttribute(entry: string): boolean {return false;}}++/**+ * Reads the value used to group a span for color-by purposes. Falls back to+ * `"unknown"` so all unattributed spans share a single colour rather than+ * appearing as missing data.+ */+export function getSpanGroupValue(+ span: SpanV3,+ colorByFieldName: string,+): string {+ return getSpanAttribute(span, colorByFieldName) || 'unknown';+}++/**+ * Resolves the rendering colour for a span. Error spans always get the+ * semantic destructive colour; everything else is derived deterministically+ * from its group value via `generateColor`.+ */+export function resolveSpanColor(+ span: SpanV3,+ colorByFieldName: string,+): string {+ if (span.has_error) {+ return 'var(--destructive)';+ }+ return generateColor(+ getSpanGroupValue(span, colorByFieldName),+ themeColors.traceDetailColorsV3,+ );+}diff --git a/frontend/src/periscope/components/PrettyView/PrettyView.tsx b/frontend/src/periscope/components/PrettyView/PrettyView.tsxindex c14006abe5..3e7f372956 100644--- a/frontend/src/periscope/components/PrettyView/PrettyView.tsx+++ b/frontend/src/periscope/components/PrettyView/PrettyView.tsx@@ -39,8 +39,12 @@ export interface PrettyViewAction {label: React.ReactNode;icon?: React.ReactNode;onClick: (context: FieldContext) => void;- /** If provided, action is hidden when this returns true for the field key */- shouldHide?: (key: string) => boolean;+ /**+ * If provided, action is hidden when this returns true. Receives the leaf+ * key plus the full path so callers can hide based on ancestor segments+ * (e.g. anything under `events.*`).+ */+ shouldHide?: (key: string, fieldKeyPath: (string | number)[]) => boolean;}export interface VisibleActionsConfig {@@ -176,7 +180,7 @@ function PrettyView({const visibleCustomActions = actions.filter((action) =>isActionVisible(action.key, context.isNested) &&- !(action.shouldHide && action.shouldHide(leafKey)),+ !(action.shouldHide && action.shouldHide(leafKey, context.fieldKeyPath)),);visibleCustomActions.forEach((action) => {items.push({diff --git a/frontend/src/periscope/components/ResizableBox/ResizableBox.styles.scss b/frontend/src/periscope/components/ResizableBox/ResizableBox.styles.scssindex 0657f39289..742bbe293e 100644--- a/frontend/src/periscope/components/ResizableBox/ResizableBox.styles.scss+++ b/frontend/src/periscope/components/ResizableBox/ResizableBox.styles.scss@@ -27,7 +27,7 @@bottom: 0;left: 0;right: 0;- height: 4px;+ height: 1px;cursor: row-resize;}@@ -35,7 +35,7 @@right: 0;top: 0;bottom: 0;- width: 4px;+ width: 1px;cursor: col-resize;}}