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
fix(dashboard-v2): stop false 'updated elsewhere' prompts on your own edits (#12035)
Ashwin Bhatkalff3ec133b4ff
diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardStaleCheck.test.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardStaleCheck.test.tsindex 2196f93284..44a056339d 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardStaleCheck.test.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/__tests__/useDashboardStaleCheck.test.ts@@ -1,74 +1,196 @@-import { act, renderHook } from '@testing-library/react';+import { act, renderHook, waitFor } from '@testing-library/react';+import { getDashboardV2 } from 'api/generated/services/dashboard';+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';import { useDashboardStaleCheck } from '../useDashboardStaleCheck';-const mockUseQuery = jest.fn();const mockUseIsMutating = jest.fn();jest.mock('react-query', () => ({- useQuery: (...args: unknown[]): unknown => mockUseQuery(...args),useIsMutating: (): number => mockUseIsMutating(),- useQueryClient: (): unknown => ({ getQueryData: jest.fn() }),}));jest.mock('api/generated/services/dashboard', () => ({getDashboardV2: jest.fn(),- getGetDashboardV2QueryKey: jest.fn(() => ['/api/v2/dashboards/d1']),}));-function setServerUpdatedAt(updatedAt: string | undefined): void {- mockUseQuery.mockReturnValue({ data: { data: { updatedAt } } });+const mockGetDashboard = getDashboardV2 as jest.Mock;++const SPEC_A = { panels: { p1: {} } };+const SPEC_B = { panels: { p1: {}, p2: {} } };++interface Content {+ spec?: unknown;+ tags?: unknown;+ locked?: boolean;+}++// Defaults make loaded and server content identical unless a field is overridden.+function withDefaults(content: Content): Record<string, unknown> {+ return { spec: SPEC_A, tags: [], locked: false, ...content };+}++function loaded(+ updatedAt: string,+ content: Content = {},+): DashboardtypesGettableDashboardV2DTO {+ return {+ id: 'd1',+ updatedAt,+ ...withDefaults(content),+ } as unknown as DashboardtypesGettableDashboardV2DTO;+}++function setVisibility(state: 'visible' | 'hidden'): void {+ Object.defineProperty(document, 'visibilityState', {+ configurable: true,+ get: () => state,+ });+}++/** Simulate the tab/window coming back with the given server copy. */+async function comeBack(+ serverUpdatedAt: string,+ content: Content = {},+ via: 'visibilitychange' | 'focus' = 'visibilitychange',+): Promise<void> {+ mockGetDashboard.mockResolvedValueOnce({+ data: { updatedAt: serverUpdatedAt, ...withDefaults(content) },+ });+ setVisibility('visible');+ await act(async () => {+ if (via === 'focus') {+ window.dispatchEvent(new Event('focus'));+ } else {+ document.dispatchEvent(new Event('visibilitychange'));+ }+ });}describe('useDashboardStaleCheck', () => {beforeEach(() => {jest.clearAllMocks();mockUseIsMutating.mockReturnValue(0);+ setVisibility('visible');+ });++ it('does not fetch on first load — only when the tab/window returns', async () => {+ renderHook(() =>+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),+ );+ expect(mockGetDashboard).not.toHaveBeenCalled();++ await comeBack('2026-07-08T09:00:00Z');+ expect(mockGetDashboard).toHaveBeenCalledWith({ id: 'd1' });+ });++ it('also probes on window focus (returning from another app)', async () => {+ renderHook(() =>+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),+ );+ await comeBack('2026-07-08T09:00:00Z', {}, 'focus');+ expect(mockGetDashboard).toHaveBeenCalledTimes(1);+ });++ it('prompts when newer and the spec differs', async () => {+ const { result } = renderHook(() =>+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),+ );+ await comeBack('2026-07-08T10:00:00Z', { spec: SPEC_B });+ await waitFor(() => expect(result.current.showPrompt).toBe(true));+ });++ it('prompts when newer and the lock state differs (external lock)', async () => {+ const { result } = renderHook(() =>+ useDashboardStaleCheck(+ loaded('2026-07-08T09:00:00Z', { locked: false }),+ jest.fn(),+ ),+ );+ await comeBack('2026-07-08T10:00:00Z', { locked: true });+ await waitFor(() => expect(result.current.showPrompt).toBe(true));+ });++ it('prompts when newer and the tags differ', async () => {+ const { result } = renderHook(() =>+ useDashboardStaleCheck(+ loaded('2026-07-08T09:00:00Z', { tags: [] }),+ jest.fn(),+ ),+ );+ await comeBack('2026-07-08T10:00:00Z', {+ tags: [{ key: 'env', value: 'prod' }],+ });+ await waitFor(() => expect(result.current.showPrompt).toBe(true));});- it('prompts when the server copy is newer than the loaded one', () => {- setServerUpdatedAt('2026-07-08T10:00:00Z');+ it('does NOT prompt when newer but content (spec/tags/locked) is unchanged', async () => {const { result } = renderHook(() =>- useDashboardStaleCheck('d1', '2026-07-08T09:00:00Z', jest.fn()),+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),);- expect(result.current.showPrompt).toBe(true);+ // updatedAt bumped but every content field matches — e.g. our own lock, already+ // reflected in the render cache.+ await comeBack('2026-07-08T10:00:00Z');+ expect(result.current.showPrompt).toBe(false);});- it('does not prompt when the versions match', () => {- setServerUpdatedAt('2026-07-08T09:00:00Z');+ it('does not prompt when the loaded copy is newer (own edit)', async () => {const { result } = renderHook(() =>- useDashboardStaleCheck('d1', '2026-07-08T09:00:00Z', jest.fn()),+ useDashboardStaleCheck(loaded('2026-07-08T10:00:00Z'), jest.fn()),);+ await comeBack('2026-07-08T09:00:00Z', { spec: SPEC_B });expect(result.current.showPrompt).toBe(false);});- it('does not prompt while a mutation is in flight (optimistic save)', () => {+ it('does not prompt while a mutation is in flight (optimistic save)', async () => {mockUseIsMutating.mockReturnValue(1);- setServerUpdatedAt('2026-07-08T10:00:00Z');const { result } = renderHook(() =>- useDashboardStaleCheck('d1', '2026-07-08T09:00:00Z', jest.fn()),+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),);+ await comeBack('2026-07-08T10:00:00Z', { spec: SPEC_B });expect(result.current.showPrompt).toBe(false);});- it('stops prompting for a version once dismissed', () => {- setServerUpdatedAt('2026-07-08T10:00:00Z');+ it('does not probe while the tab is hidden', async () => {+ renderHook(() =>+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),+ );+ setVisibility('hidden');+ await act(async () => {+ document.dispatchEvent(new Event('visibilitychange'));+ });+ expect(mockGetDashboard).not.toHaveBeenCalled();+ });++ it('stops prompting for a version once dismissed', async () => {const { result } = renderHook(() =>- useDashboardStaleCheck('d1', '2026-07-08T09:00:00Z', jest.fn()),+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),);- expect(result.current.showPrompt).toBe(true);+ await comeBack('2026-07-08T10:00:00Z', { spec: SPEC_B });+ await waitFor(() => expect(result.current.showPrompt).toBe(true));act(() => result.current.dismiss());expect(result.current.showPrompt).toBe(false);});- it('reload refetches and clears the dismissed state', () => {- setServerUpdatedAt('2026-07-08T10:00:00Z');+ it('reload refetches and closes the prompt immediately', async () => {const refetch = jest.fn();const { result } = renderHook(() =>- useDashboardStaleCheck('d1', '2026-07-08T09:00:00Z', refetch),+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), refetch),);- act(() => result.current.dismiss());- expect(result.current.showPrompt).toBe(false);+ await comeBack('2026-07-08T10:00:00Z', { spec: SPEC_B });+ await waitFor(() => expect(result.current.showPrompt).toBe(true));act(() => result.current.reload());expect(refetch).toHaveBeenCalledTimes(1);- expect(result.current.showPrompt).toBe(true);+ expect(result.current.showPrompt).toBe(false);+ });++ it('re-prompts when a newer, different version appears after a reload', async () => {+ const { result } = renderHook(() =>+ useDashboardStaleCheck(loaded('2026-07-08T09:00:00Z'), jest.fn()),+ );+ await comeBack('2026-07-08T10:00:00Z', { spec: SPEC_B });+ act(() => result.current.reload());+ expect(result.current.showPrompt).toBe(false);++ await comeBack('2026-07-08T10:05:00Z', { spec: { panels: { p3: {} } } });+ await waitFor(() => expect(result.current.showPrompt).toBe(true));});});diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardStaleCheck.ts b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardStaleCheck.tsindex b3346ee78e..7dfe2170cc 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardStaleCheck.ts+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/hooks/useDashboardStaleCheck.ts@@ -1,65 +1,92 @@-import { useCallback, useState } from 'react';-import { useIsMutating, useQuery, useQueryClient } from 'react-query';-import {- getDashboardV2,- getGetDashboardV2QueryKey,-} from 'api/generated/services/dashboard';-import type { GetDashboardV2200 } from 'api/generated/services/sigNoz.schemas';+import { getDashboardV2 } from 'api/generated/services/dashboard';+import type { DashboardtypesGettableDashboardV2DTO } from 'api/generated/services/sigNoz.schemas';+import { isEqual } from 'lodash-es';+import { useCallback, useEffect, useMemo, useState } from 'react';+import { useIsMutating } from 'react-query';interface UseDashboardStaleCheck {- // Server copy has a newer updatedAt than the loaded one, and not yet dismissed.+ // Server copy is a newer version with different content, and not yet dismissed.showPrompt: boolean;reload: () => void;dismiss: () => void;}/**- * Detects when the open dashboard changed on the server (another tab/user) without- * touching the render cache: a separate query (own key) refetches on window focus- * and its updatedAt is compared to the loaded copy's. Guarded by in-flight- * mutations so an optimistic save doesn't false-positive.+ * Prompts when another tab/user changed the open dashboard. The page's own query is frozen+ * (`staleTime: Infinity`), so we re-probe the server on tab/app return (not on first load) and+ * prompt only when it's strictly newer AND its content (spec, tags, or lock state) differs from+ * what we're viewing — so our own edits, which advance the render cache, don't trip it.+ * In-flight mutations are skipped.*/export function useDashboardStaleCheck(- dashboardId: string,- loadedUpdatedAt: string | undefined,+ dashboard: DashboardtypesGettableDashboardV2DTO,refetch: () => void,): UseDashboardStaleCheck {+ const {+ id: dashboardId,+ updatedAt: loadedUpdatedAt,+ spec: loadedSpec,+ tags: loadedTags,+ locked: loadedLocked,+ } = dashboard;const isMutating = useIsMutating() > 0;- const queryClient = useQueryClient();+ const [server, setServer] = useState<DashboardtypesGettableDashboardV2DTO>();const [dismissedAt, setDismissedAt] = useState<string | null>(null);- const { data } = useQuery(- ['dashboard-freshness', dashboardId],- ({ signal }) => getDashboardV2({ id: dashboardId }, signal),- {- enabled: !!dashboardId,- refetchOnWindowFocus: true,- refetchOnMount: false,- retry: false,- // Seed from the already-loaded dashboard so mount makes no extra GET; the- // query only hits the network on a later window focus.- initialData: () =>- queryClient.getQueryData<GetDashboardV2200>(- getGetDashboardV2QueryKey({ id: dashboardId }),- ),- },+ useEffect(() => {+ if (!dashboardId) {+ return undefined;+ }+ const probe = async (): Promise<void> => {+ // `visibilitychange` also fires on the hidden transition — only probe on return.+ if (document.visibilityState !== 'visible') {+ return;+ }+ try {+ const response = await getDashboardV2({ id: dashboardId });+ setServer(response.data);+ } catch {+ // A failed freshness probe must never surface to the viewer.+ }+ };+ // `visibilitychange` catches tab switches; `focus` catches app/window switches.+ document.addEventListener('visibilitychange', probe);+ window.addEventListener('focus', probe);+ return (): void => {+ document.removeEventListener('visibilitychange', probe);+ window.removeEventListener('focus', probe);+ };+ }, [dashboardId]);++ const serverUpdatedAt = server?.updatedAt;++ // Content the viewer cares about: panels/layout/variables (spec), tags, and lock state.+ // Deep, order-independent so an optimistic patch's key reordering isn't read as a change.+ const contentDiffers = useMemo(+ () =>+ !!server &&+ (!isEqual(server.spec, loadedSpec) ||+ !isEqual(server.tags, loadedTags) ||+ server.locked !== loadedLocked),+ [server, loadedSpec, loadedTags, loadedLocked],);- const serverUpdatedAt = data?.data?.updatedAt;const changed =!isMutating &&!!serverUpdatedAt &&!!loadedUpdatedAt &&- serverUpdatedAt !== loadedUpdatedAt;+ new Date(serverUpdatedAt).getTime() > new Date(loadedUpdatedAt).getTime() &&+ contentDiffers;const dismiss = useCallback((): void => setDismissedAt(serverUpdatedAt ?? null),[serverUpdatedAt],);+ // Dismiss + refetch: close on click and pull the latest; a newer, different version re-prompts.const reload = useCallback((): void => {+ setDismissedAt(serverUpdatedAt ?? null);refetch();- setDismissedAt(null);- }, [refetch]);+ }, [refetch, serverUpdatedAt]);return {showPrompt: changed && serverUpdatedAt !== dismissedAt,diff --git a/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx b/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsxindex de672dd12d..b373b35031 100644--- a/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx+++ b/frontend/src/pages/DashboardPageV2/DashboardContainer/index.tsx@@ -55,11 +55,7 @@ function DashboardContainer({// suggests them ($variable) in the panel editor and dashboards-page builder.useSyncVariablesForSuggestions(dashboard);- const staleCheck = useDashboardStaleCheck(- dashboard.id,- dashboard.updatedAt,- refetch,- );+ const staleCheck = useDashboardStaleCheck(dashboard, refetch);// In full screen show only the sections and panels — the header/toolbar chrome// is hidden for a clean presentation view (exit with Esc).