:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
refactor(dashboards): remove dashboard refresh ai analysis (#62181)
Matt Pua563a58c0eb67
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex e8cb6b1a7f10..b97256cc5979 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -415,7 +415,6 @@ export const FEATURE_FLAGS = {POSTHOG_AI_CONVERSATION_FEEDBACK_LLMA_SESSIONS: 'posthog-ai-conversation-feedback-llma-sessions', // owner: #team-posthog-aiPOSTHOG_AI_QUEUE_MESSAGES_SYSTEM: 'posthog-ai-queue-messages-system', // owner: #team-posthog-aiPOSTHOG_CODE_BILLING: 'posthog-code-billing', // owner: #team-posthog-code- PRODUCT_ANALYTICS_DASHBOARD_AI_ANALYSIS: 'product-analytics-dashboard-ai-analysis', // owner: @anirudhpillai #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_COLORS: 'dashboard-colors', // owner: @thmsobrmlr #team-product-analyticsPRODUCT_ANALYTICS_DASHBOARD_MODAL_SMART_DEFAULTS: 'product-analytics-dashboard-modal-smart-defaults', // owner: @sam #team-product-analyticsPRODUCT_ANALYTICS_HIDE_WEEKENDS: 'product-analytics-hide-weekends', // owner: @kliment-slice #team-irl-eventsdiff --git a/frontend/src/scenes/dashboard/Dashboard.tsx b/frontend/src/scenes/dashboard/Dashboard.tsxindex 96741f120134..a82540e27cd7 100644--- a/frontend/src/scenes/dashboard/Dashboard.tsx+++ b/frontend/src/scenes/dashboard/Dashboard.tsx@@ -2,9 +2,6 @@ import './Dashboard.scss'import { BindLogic, useActions, useMountedLogic, useValues } from 'kea'-import { IconThumbsDown, IconThumbsUp } from '@posthog/icons'-import { LemonBanner, LemonButton } from '@posthog/lemon-ui'-import { AccessDenied } from 'lib/components/AccessDenied'import { NotFound } from 'lib/components/NotFound'import { useFileSystemLogView } from 'lib/hooks/useFileSystemLogView'@@ -75,13 +72,10 @@ function DashboardScene({ backTo }: { backTo?: { url: string; name: string } }):dashboardMode,dashboardFailedToLoad,accessDeniedToDashboard,- refreshAnalysisResult,- analysisRating,} = useValues(dashboardLogic)const { layoutZoom } = useValues(dashboardLogic)const { currentTeamId } = useValues(teamLogic)- const { reportDashboardViewed, abortAnyRunningQuery, setRefreshAnalysisResult, setAnalysisRating, setLayoutZoom } =- useActions(dashboardLogic)+ const { reportDashboardViewed, abortAnyRunningQuery, setLayoutZoom } = useActions(dashboardLogic)const { addInsightToDashboardModalVisible } = useValues(addInsightToDashboardLogic)useFileSystemLogView({@@ -123,37 +117,6 @@ function DashboardScene({ backTo }: { backTo?: { url: string; name: string } }):><DashboardOverridesBanner />- {refreshAnalysisResult && (- <LemonBanner- type="info"- onClose={() => setRefreshAnalysisResult(null)}- className="mb-4 [&>.flex]:items-start"- hideIcon- >- <div className="whitespace-pre-wrap">{refreshAnalysisResult}</div>- <div className="flex items-center gap-0.5 mt-2">- {analysisRating ? (- <span className="text-muted text-xs">Thanks for the feedback!</span>- ) : (- <>- <LemonButton- size="xsmall"- icon={<IconThumbsUp />}- tooltip="Helpful"- onClick={() => setAnalysisRating('up')}- />- <LemonButton- size="xsmall"- icon={<IconThumbsDown />}- tooltip="Not helpful"- onClick={() => setAnalysisRating('down')}- />- </>- )}- </div>- </LemonBanner>- )}-<SceneStickyBar showBorderBottom={false} className="flex gap-2 space-y-0"><DashboardFilterBar backTo={backTo} />{dashboardMode === DashboardMode.Edit &&diff --git a/frontend/src/scenes/dashboard/DashboardReloadAction.tsx b/frontend/src/scenes/dashboard/DashboardReloadAction.tsxindex ffcabeffbb4a..ca43b2efbb90 100644--- a/frontend/src/scenes/dashboard/DashboardReloadAction.tsx+++ b/frontend/src/scenes/dashboard/DashboardReloadAction.tsx@@ -1,20 +1,18 @@import { useActions, useValues } from 'kea'import { useEffect, useState } from 'react'-import { IconCheck, IconSparkles, IconX } from '@posthog/icons'+import { IconCheck, IconX } from '@posthog/icons'import { IconRefresh } from '@posthog/icons'-import { LemonBadge, LemonButton, LemonSwitch, Spinner, Tooltip } from '@posthog/lemon-ui'+import { LemonBadge, LemonButton, LemonSwitch, Spinner } from '@posthog/lemon-ui'import { AppShortcut } from 'lib/components/AppShortcuts/AppShortcut'import { keyBinds } from 'lib/components/AppShortcuts/shortcuts'import { TZLabel } from 'lib/components/TZLabel'import { dayjs } from 'lib/dayjs'-import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'import { usePageVisibilityCb } from 'lib/hooks/usePageVisibility'import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu/LemonMenu'import { LemonRadio } from 'lib/lemon-ui/LemonRadio'import { humanFriendlyDuration } from 'lib/utils'-import { cn } from 'lib/utils/css-classes'import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'import { Scene } from 'scenes/sceneTypes'@@ -34,7 +32,7 @@ export const LastRefreshText = (): JSX.Element => {/** Loading / progress / pessimistic last refresh — same as the left side of `DashboardReloadAction`, without refresh controls. */export function DashboardRefreshStatusText(): JSX.Element {- const { itemsLoading, refreshMetrics, dashboardLoadData, isAnalyzing } = useValues(dashboardLogic)+ const { itemsLoading, refreshMetrics, dashboardLoadData } = useValues(dashboardLogic)const isInitialLoad =dashboardLoadData?.action === 'initial_load' || dashboardLoadData?.action === 'initial_load_with_variables'return (@@ -42,9 +40,7 @@ export function DashboardRefreshStatusText(): JSX.Element {{itemsLoading ? (<span className="flex items-center gap-1"><Spinner textColored className="text-sm" />- {isAnalyzing ? (- <>Analyzing...</>- ) : refreshMetrics.total ? (+ {refreshMetrics.total ? (<>{isInitialLoad ? 'Loaded' : 'Refreshed'} {refreshMetrics.completed} out of{' '}{refreshMetrics.total}@@ -70,15 +66,7 @@ const INTERVAL_OPTIONS = Array.from(REFRESH_INTERVAL_SECONDS, (value) => ({}))export function DashboardReloadAction(): JSX.Element {- const {- itemsLoading,- autoRefresh,- blockRefresh,- nextAllowedDashboardRefresh,- hasIntermittentFilters,- hasUrlFilters,- urlVariables,- } = useValues(dashboardLogic)+ const { itemsLoading, autoRefresh, blockRefresh, nextAllowedDashboardRefresh } = useValues(dashboardLogic)const { triggerDashboardRefresh, setAutoRefresh, setPageVisibility, cancelDashboardRefresh } =useActions(dashboardLogic)@@ -92,10 +80,6 @@ export function DashboardReloadAction(): JSX.Element {? `Next bulk refresh possible ${dayjs(nextAllowedDashboardRefresh).fromNow()}`: ''- const hasOverrides = hasIntermittentFilters || hasUrlFilters || Object.keys(urlVariables).length > 0- const dashboardAIRefreshEnabled =- useFeatureFlag('PRODUCT_ANALYTICS_DASHBOARD_AI_ANALYSIS') && !hasOverrides && !refreshDisabledReason-// Force a re-render when nextAllowedDashboardRefresh is reached, since the blockRefresh// selector uses now() which isn't reactive - it only recomputes on dependency changesconst [, setRenderTrigger] = useState(0)@@ -196,24 +180,6 @@ export function DashboardReloadAction(): JSX.Element {>{itemsLoading ? 'Cancel' : 'Refresh'}</LemonButton>- {!itemsLoading && dashboardAIRefreshEnabled && (- <Tooltip title="Refresh and analyze with AI">- <button- className={cn(- 'absolute z-10 flex items-center justify-center w-5 h-5 rounded-full bg-bg-light border border-border cursor-pointer p-0 hover:[&>svg]:animate-hue-rotate',- autoRefresh.enabled ? '-bottom-2 -right-2' : '-top-2 -right-2'- )}- onClick={(e) => {- e.stopPropagation()- triggerDashboardRefresh({ withAnalysis: true })- }}- aria-label="Refresh and analyze with AI"- data-attr="dashboard-items-action-refresh-and-analyze"- >- <IconSparkles className="text-ai size-4" />- </button>- </Tooltip>- )}</div></AppShortcut>diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsxindex 12d2694d6483..ca5e224ee705 100644--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx@@ -16,7 +16,6 @@ import {import { loaders } from 'kea-loaders'import { actionToUrl, router, urlToAction } from 'kea-router'import uniqBy from 'lodash.uniqby'-import posthog from 'posthog-js'import { ResponsiveLayouts } from 'react-grid-layout'import { LemonDialog, lemonToast } from '@posthog/lemon-ui'@@ -247,10 +246,8 @@ export const dashboardLogic = kea<dashboardLogicType>([loadingDashboardItemsStarted: (action: DashboardLoadAction) => ({ action }),/** Expose response size information about the current dashboard load in dashboardLoadData. */setInitialLoadResponseBytes: (responseBytes: number) => ({ responseBytes }),- /** Manually refresh the entire dashboard. Pass withAnalysis: true to also run AI analysis after refresh. */- triggerDashboardRefresh: (payload?: { withAnalysis?: boolean }) => ({- withAnalysis: payload?.withAnalysis ?? false,- }),+ /** Manually refresh the entire dashboard. */+ triggerDashboardRefresh: true,/*** If the latest tile data is older than SHARED_DASHBOARD_AUTO_FORCE_IF_STALE_MINUTES,* queue a single force-blocking refresh on the next microtask. Reads@@ -402,14 +399,6 @@ export const dashboardLogic = kea<dashboardLogicType>([loadLayoutFromServerOnPreview,}),dashboardNotFound: true,-- /**- * AI Dashboard Refresh Analysis.- */- setAnalyzeStatus: (isAnalyzing: boolean) => ({ isAnalyzing }),- setRefreshAnalysisCacheKey: (cacheKey: string | null) => ({ cacheKey }),- setRefreshAnalysisResult: (result: string | null) => ({ result }),- setAnalysisRating: (rating: 'up' | 'down' | null) => ({ rating }),})),loaders(({ actions, props, values, cache }) => ({@@ -1208,35 +1197,6 @@ export const dashboardLogic = kea<dashboardLogicType>([}),},],- refreshAnalysisCacheKey: [- null as string | null,- {- setRefreshAnalysisCacheKey: (_, { cacheKey }) => cacheKey,- triggerDashboardRefresh: () => null,- },- ],- refreshAnalysisResult: [- null as string | null,- {- setRefreshAnalysisResult: (_, { result }) => result,- triggerDashboardRefresh: () => null,- },- ],- analysisRating: [- null as 'up' | 'down' | null,- {- setAnalysisRating: (_, { rating }) => rating,- setRefreshAnalysisResult: () => null,- triggerDashboardRefresh: () => null,- },- ],- isAnalyzing: [- false,- {- setAnalyzeStatus: (_, { isAnalyzing }) => isAnalyzing,- triggerDashboardRefresh: () => false,- },- ],isSavingTags: [false,{@@ -1589,7 +1549,6 @@ export const dashboardLogic = kea<dashboardLogicType>([s.initialVariablesLoaded,s.initialQuickFiltersLoaded,s.dashboardFiltersEnabled,- s.isAnalyzing,],(dashboardLoading,@@ -1597,11 +1556,9 @@ export const dashboardLogic = kea<dashboardLogicType>([refreshStatus,initialVariablesLoaded,initialQuickFiltersLoaded,- dashboardFiltersEnabled,- isAnalyzing+ dashboardFiltersEnabled) => {return (- isAnalyzing ||dashboardLoading ||dashboardStreaming ||Object.values(refreshStatus).some((s) => s.loading || s.queued) ||@@ -1930,12 +1887,6 @@ export const dashboardLogic = kea<dashboardLogicType>([}}},- setAnalysisRating: ({ rating }) => {- posthog.capture('dashboard refresh ai analysis feedback', {- rating: rating === 'up' ? 'thumbs_up' : 'thumbs_down',- analysis_text: values.refreshAnalysisResult,- })- },updateTileColor: async ({ tileId, color }) => {// Defense in depth: shared dashboards (DashboardPlacement.Public)// shouldn't render the tile-color editor, so this listener should@@ -1995,11 +1946,6 @@ export const dashboardLogic = kea<dashboardLogicType>([primary_interaction_id: dashboardQueryId,time_to_see_data_ms: Math.floor(performance.now() - startTime),})-- if (values.isAnalyzing) {- actions.setAnalyzeStatus(false)- actions.setRefreshAnalysisCacheKey(null)- }},tileStreamingFailure: ({ error }) => {if (error?.message?.includes('404') || error?.status === 404) {@@ -2221,43 +2167,8 @@ export const dashboardLogic = kea<dashboardLogicType>([})},/** Triggered from dashboard refresh button, when user refreshes entire dashboard */- triggerDashboardRefresh: async ({ withAnalysis }, breakpoint) => {+ triggerDashboardRefresh: () => {actions.resetInterval()-- if (withAnalysis) {- try {- // Gather current data from the frontend store- const clientResults: Record<number, any> = {}- values.insightTiles.forEach((tile) => {- if (tile.insight && tile.insight.result) {- clientResults[tile.id] = {- insight_name: tile.insight.name || tile.insight.derived_name,- data: tile.insight.result,- }- }- })-- // Snapshot the current cached state ("before") before any refresh happens- const snapshotResponse = await api.create(- `api/environments/${values.currentTeamId}/dashboards/${props.id}/snapshot`,- { client_results: clientResults }- )- const { cache_key: cacheKey } = snapshotResponse-- if (!cacheKey) {- throw new Error('No cache key returned from snapshot')- }-- actions.setRefreshAnalysisCacheKey(cacheKey)- actions.setAnalyzeStatus(true)-- await breakpoint()- } catch (e: any) {- lemonToast.error('Failed to start analysis: ' + String(e))- return- }- }-actions.refreshDashboardItems({ action: RefreshDashboardItemsAction.Refresh, forceRefresh: true })if (values.dashboardWidgetsEnabled &&@@ -2379,8 +2290,6 @@ export const dashboardLogic = kea<dashboardLogicType>([dashboardLoadData,dashboard,lastDashboardRefresh,- isAnalyzing,- refreshAnalysisCacheKey,} = valuesconst fetchSyncInsightFunctions = sortedTilesToRefresh.map((tile) => async () => {@@ -2485,23 +2394,6 @@ export const dashboardLogic = kea<dashboardLogicType>([refreshDurationMs: Math.floor(performance.now() - dashboardRefreshStartTime),})-- // Run AI analysis after tiles finish, if it was requested and refresh wasn't aborted- if (isAnalyzing && refreshAnalysisCacheKey && tilesAbortedCount === 0) {- const cacheKey = refreshAnalysisCacheKey- try {- const analysisResponse = await api.create(- `api/environments/${currentTeamId}/dashboards/${dashboardId}/analyze_refresh_result`,- { cache_key: cacheKey }- )- actions.setRefreshAnalysisResult(analysisResponse.result)- } catch (e: any) {- lemonToast.error('Failed to analyze dashboard changes: ' + String(e))- } finally {- actions.setAnalyzeStatus(false)- actions.setRefreshAnalysisCacheKey(null)- }- }}if (diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.pyindex d720e97df437..c58c57184f42 100644--- a/posthog/api/test/dashboards/test_dashboard.py+++ b/posthog/api/test/dashboards/test_dashboard.py@@ -3143,50 +3143,6 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):self.assertIn(normal.id, ids)self.assertNotIn(template.id, ids)- def test_analyze_refresh_result_with_empty_cache(self):- # Simulate snapshot creating an empty cache entry (e.g. no cached results)- # This happens when the dashboard has no data or no cached results before refresh- self.organization.is_ai_data_processing_approved = True- self.organization.save()- dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard", created_by=self.user)- cache_key = "dashboard_refresh_test_empty"-- cache.set(cache_key, {}, timeout=60)-- response = self.client.post(- f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/analyze_refresh_result",- {"cache_key": cache_key},- )-- # Should return 200 with "No significant changes" instead of 400 error- self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(- response.json(),- {"result": "No significant changes detected in the dashboard data."},- )-- def test_analyze_refresh_result_with_missing_cache(self):- # Simulate cache miss (expired or invalid key)- self.organization.is_ai_data_processing_approved = True- self.organization.save()- dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard", created_by=self.user)- cache_key = "dashboard_refresh_test_missing"-- # Ensure key is not in cache- cache.delete(cache_key)-- response = self.client.post(- f"/api/projects/{self.team.id}/dashboards/{dashboard.id}/analyze_refresh_result",- {"cache_key": cache_key},- )-- # Should return 400 error- self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)- self.assertEqual(- response.json(),- {"error": "Analysis context expired or not found. Please refresh the dashboard again."},- )-def test_reorder_tiles(self):dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")insight1 = Insight.objects.create(team=self.team, name="Insight 1")diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.pyindex 7e3874c8b7d0..9cb03038e0e0 100644--- a/products/dashboards/backend/api/dashboard.py+++ b/products/dashboards/backend/api/dashboard.py@@ -12,7 +12,6 @@ from typing import Any, Optional, TypedDict, castfrom django.conf import settingsfrom django.contrib.postgres.search import TrigramSimilarity, TrigramWordSimilarity-from django.core.cache import cachefrom django.core.exceptions import ValidationError as DjangoValidationErrorfrom django.core.validators import URLValidatorfrom django.db import IntegrityError, transaction@@ -29,7 +28,6 @@ from asgiref.sync import sync_to_asyncfrom drf_spectacular.types import OpenApiTypesfrom drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_viewfrom opentelemetry import trace-from pydantic import BaseModelfrom rest_framework import exceptions, serializers, status, viewsetsfrom rest_framework.permissions import SAFE_METHODS, BasePermissionfrom rest_framework.request import Request@@ -43,13 +41,12 @@ from posthog.api.forbid_destroy_model import ForbidDestroyModelfrom posthog.api.monitoring import Feature, monitorfrom posthog.api.openapi_parameters import make_filters_override_param, make_variables_override_paramfrom posthog.api.routing import TeamAndOrgViewSetMixin-from posthog.api.services.query import process_query_modelfrom posthog.api.shared import UserBasicSerializerfrom posthog.api.tagged_item import TaggedItemSerializerMixin, TaggedItemViewSetMixinfrom posthog.api.utils import actionfrom posthog.clickhouse.client.async_task_chain import task_chain_contextfrom posthog.constants import GENERATED_DASHBOARD_PREFIX-from posthog.event_usage import get_request_analytics_properties, report_user_action+from posthog.event_usage import report_user_actionfrom posthog.exceptions_capture import capture_exceptionfrom posthog.helpers import create_dashboard_from_templatefrom posthog.helpers.dashboard_templates import create_from_template, dashboard_template_from_creation_payload@@ -60,7 +57,6 @@ from posthog.helpers.trigram_search import (MIN_NAME_TRIGRAM_SIMILARITY,normalize_search_term,)-from posthog.hogql_queries.query_runner import ExecutionModefrom posthog.models.activity_logging.activity_log import ActivityScope, Detail, changes_between, log_activityfrom posthog.models.file_system.file_system import create_or_update_file, delete_filefrom posthog.models.quick_filter import QuickFilter@@ -80,7 +76,6 @@ from posthog.utils import filters_override_requested_by_client, str_to_bool, varfrom products.ai_observability.backend.dashboard_templates import get_ai_observability_default_templatefrom products.alerts.backend.models.alert import AlertConfiguration-from products.dashboards.backend.api.dashboard_ai import generate_refresh_analysisfrom products.dashboards.backend.api.dashboard_template_json_schema_parser import (DashboardTemplateCreationJSONSchemaParser,)@@ -117,7 +112,6 @@ from products.product_analytics.backend.api.insight import (InsightSerializer,InsightViewSet,)-from products.product_analytics.backend.api.insight_suggestions import summarize_insight_resultfrom products.product_analytics.backend.models.insight import Insightfrom products.product_analytics.backend.models.insight_variable import InsightVariable@@ -612,29 +606,6 @@ class CanEditDashboard(BasePermission):return view.user_permissions.dashboard(dashboard).can_edit-class ClientResultItemSerializer(serializers.Serializer):- insight_name = serializers.CharField(required=True)-- # `data` shadows Serializer.data so we declare it via get_fields to avoid the mypy conflict- def get_fields(self):- fields = super().get_fields()- fields["data"] = serializers.JSONField(required=True)- return fields-- def validate_data(self, value):- if not value:- raise serializers.ValidationError("Data cannot be empty.")- return value---class DashboardSnapshotSerializer(serializers.Serializer):- client_results = serializers.DictField(- child=ClientResultItemSerializer(),- required=False,- allow_null=True,- )--class TextSerializer(serializers.ModelSerializer):created_by = UserBasicSerializer(read_only=True)last_modified_by = UserBasicSerializer(read_only=True)@@ -2007,54 +1978,6 @@ class DashboardsViewSet(return queryset- def _get_cached_results_for_analysis(self, dashboard: Dashboard, request: Request) -> dict[int, Any]:- """- Fetch currently cached results for all insight tiles on the dashboard.- Uses CACHE_ONLY_NEVER_CALCULATE to ensure we get the 'before' state without triggering recalc.- Returns dict mapping tile_id to summarized result data.- """- results = {}- tiles = dashboard.tiles.filter(insight__isnull=False).select_related("insight")- analytics_props = get_request_analytics_properties(request)-- for tile in tiles:- insight = tile.insight- if not insight or not insight.query:- continue-- try:- query = InsightVizNode.model_validate(insight.query)- except Exception:- logger.warning("dashboard_refresh_analysis_query_validation_failed", tile_id=tile.id)- continue-- try:- result_ctx = process_query_model(- self.team,- query,- execution_mode=ExecutionMode.CACHE_ONLY_NEVER_CALCULATE,- user=request.user if request.user.is_authenticated else None,- analytics_props=analytics_props,- )-- result_data = None- if isinstance(result_ctx, BaseModel):- result_dict = result_ctx.model_dump()- result_data = result_dict.get("results") or result_dict.get("result")- elif isinstance(result_ctx, dict):- result_data = result_ctx.get("results") or result_ctx.get("result")-- if result_data:- results[tile.id] = {- "insight_name": insight.name or insight.derived_name,- "data": summarize_insight_result(result_data),- }- except Exception:- logger.warning("dashboard_refresh_analysis_query_processing_failed", tile_id=tile.id)- continue-- return results-@extend_schema(parameters=[VARIABLES_OVERRIDE_PARAM, FILTERS_OVERRIDE_PARAM])@monitor(feature=Feature.DASHBOARD, endpoint="dashboard", method="GET")def retrieve(self, request: Request, *args: Any, **kwargs: Any) -> Response:@@ -2068,77 +1991,6 @@ class DashboardsViewSet(response = Response(data)return response- def _validate_ai_feature_access(self) -> None:- """Validate that AI data processing is approved by the organization.-- Mirrors `InsightsViewSet._validate_ai_feature_access`. The dashboard refresh- flow is `snapshot` -> `analyze_refresh_result`; both touch the same data the- OpenAI call ultimately sees, so both gate on this check.- """- if not self.organization.is_ai_data_processing_approved:- raise exceptions.PermissionDenied("AI data processing must be approved by your organization")-- @action(methods=["POST"], detail=True)- def snapshot(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """- Snapshot the current dashboard state (from cache) for AI analysis.- Returns a cache_key representing the 'before' state, to be used with analyze_refresh_result.- """- self._validate_ai_feature_access()- dashboard = self.get_object()-- input_serializer = DashboardSnapshotSerializer(data=request.data)- input_serializer.is_valid(raise_exception=True)- client_results = input_serializer.validated_data.get("client_results")-- if client_results:- before_results = {- int(tile_id): {- "insight_name": item["insight_name"],- "data": summarize_insight_result(item["data"]),- }- for tile_id, item in client_results.items()- }- else:- before_results = self._get_cached_results_for_analysis(dashboard, request)-- cache_key = f"dashboard_refresh_before_{dashboard.id}_{request.user.id}_{now().timestamp()}"- cache.set(cache_key, before_results, timeout=1800) # 30 minutes- return Response({"cache_key": cache_key})-- @action(methods=["POST"], detail=True)- def analyze_refresh_result(self, request: Request, *args: Any, **kwargs: Any) -> Response:- """- Generate AI analysis comparing before/after dashboard refresh.- Expects cache_key in request body pointing to the stored 'before' state.- """- self._validate_ai_feature_access()-- dashboard = self.get_object()- cache_key = request.data.get("cache_key")-- if not cache_key:- return Response({"error": "cache_key is required"}, status=status.HTTP_400_BAD_REQUEST)-- # Get 'before' state from cache- before_results = cache.get(cache_key)- if before_results is None:- return Response(- {"error": "Analysis context expired or not found. Please refresh the dashboard again."},- status=status.HTTP_400_BAD_REQUEST,- )-- # Get 'after' state (should be fresh in cache now)- after_results = self._get_cached_results_for_analysis(dashboard, request)-- # Generate AI analysis- analysis = generate_refresh_analysis(before_results, after_results, dashboard)-- if not analysis:- return Response({"result": "No significant changes detected in the dashboard data."})-- return Response({"result": analysis})-# ******************************************# /projects/:id/dashboard/:id/stream_tiles# ******************************************diff --git a/products/dashboards/backend/api/dashboard_ai.py b/products/dashboards/backend/api/dashboard_ai.pydeleted file mode 100644index 2da04e47d99c..000000000000--- a/products/dashboards/backend/api/dashboard_ai.py+++ /dev/null@@ -1,83 +0,0 @@-import json-from typing import Optional--import structlog--from posthog.hogql.ai import hit_openai--from products.annotations.backend.api.annotation_context import build_annotations_block, resolve_dashboard_date_range-from products.dashboards.backend.models.dashboard import Dashboard--logger = structlog.get_logger(__name__)---def generate_refresh_analysis(before_results: dict, after_results: dict, dashboard: Dashboard) -> Optional[str]:- """- Compare before/after dashboard refresh results and return an AI summary of what changed.- Returns None if there are no significant changes or the AI call fails.- """- changes = []-- for tile_id, before in before_results.items():- after = after_results.get(tile_id)- if not after:- continue-- # Skip if data is identical (using default=str to handle datetime and other non-serializable types)- if json.dumps(before["data"], sort_keys=True, default=str) == json.dumps(- after["data"], sort_keys=True, default=str- ):- continue-- changes.append(- {- "insight_name": before.get("insight_name", f"Tile {tile_id}"),- "before": before["data"],- "after": after["data"],- }- )-- if not changes:- return None-- annotations_block = build_annotations_block(- dashboard.team,- resolve_dashboard_date_range(dashboard.filters, dashboard.team),- dashboard_id=dashboard.id,- )-- # Limit verbosity for large dashboards- prioritization_instruction = (- "List ONLY the top 3-5 most significant changes." if len(changes) > 5 else "List the significant changes."- )-- prompt = (- "You are a product data analyst. A user just refreshed their dashboard. "- "Compare the 'before' and 'after' data for the following insights and summarize what changed.\n\n"- "Style Rules:\n"- "- Focus ONLY on significant changes (drops, spikes, trend reversals).\n"- "- If including a summary, put it at the beginning of the response."- "- If nothing significant changed, say so.\n"- f"{prioritization_instruction}\n"- "- Group related findings.\n"- "- Use concise bullet points.\n"- "- Be direct and quantify changes when possible (e.g., '+15%', 'dropped by 30%').\n"- "- Do NOT use markdown formatting (no bold, italics, etc). Use plain text.\n\n"- f"{annotations_block}"- f"Changes:\n{json.dumps(changes, default=str)}"- )-- messages = [{"role": "user", "content": prompt}]- try:- content, _, _ = hit_openai(- messages,- f"team/{dashboard.team_id}/dashboard_refresh",- posthog_properties={- "ai_product": "product_analytics",- "ai_feature": "dashboard-refresh-analysis",- },- )- return content- except Exception:- logger.exception("dashboard_refresh_analysis_failed")- return Nonediff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.tsindex cd9a6c7ee475..be5200046aa7 100644--- a/products/dashboards/frontend/generated/api.schemas.ts+++ b/products/dashboards/frontend/generated/api.schemas.ts@@ -8268,18 +8268,6 @@ export const DashboardsDestroyFormat = {Txt: 'txt',} as const-export type DashboardsAnalyzeRefreshResultCreateParams = {- format?: DashboardsAnalyzeRefreshResultCreateFormat-}--export type DashboardsAnalyzeRefreshResultCreateFormat =- (typeof DashboardsAnalyzeRefreshResultCreateFormat)[keyof typeof DashboardsAnalyzeRefreshResultCreateFormat]--export const DashboardsAnalyzeRefreshResultCreateFormat = {- Json: 'json',- Txt: 'txt',-} as const-export type DashboardsCopyTileCreateParams = {format?: DashboardsCopyTileCreateFormat}@@ -8412,18 +8400,6 @@ export const DashboardsRunWidgetsRetrieveFormat = {Txt: 'txt',} as const-export type DashboardsSnapshotCreateParams = {- format?: DashboardsSnapshotCreateFormat-}--export type DashboardsSnapshotCreateFormat =- (typeof DashboardsSnapshotCreateFormat)[keyof typeof DashboardsSnapshotCreateFormat]--export const DashboardsSnapshotCreateFormat = {- Json: 'json',- Txt: 'txt',-} as const-export type DashboardsStreamTilesRetrieveParams = {/*** Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.diff --git a/products/dashboards/frontend/generated/api.ts b/products/dashboards/frontend/generated/api.tsindex 4b2503080dd1..6eaa97808e38 100644--- a/products/dashboards/frontend/generated/api.ts+++ b/products/dashboards/frontend/generated/api.ts@@ -21,7 +21,6 @@ import type {DashboardTemplateApi,DashboardTemplatesListParams,DashboardTileApi,- DashboardsAnalyzeRefreshResultCreateParams,DashboardsBulkUpdateTagsCreateParams,DashboardsCopyTileCreateParams,DashboardsCreateFromTemplateJsonCreateParams,@@ -38,7 +37,6 @@ import type {DashboardsRetrieveParams,DashboardsRunInsightsRetrieveParams,DashboardsRunWidgetsRetrieveParams,- DashboardsSnapshotCreateParams,DashboardsStreamTilesRetrieveParams,DashboardsUpdateParams,DashboardsUpdateTextTileCreateParams,@@ -455,45 +453,6 @@ export const dashboardsDestroy = async (})}-export const getDashboardsAnalyzeRefreshResultCreateUrl = (- projectId: string,- id: number,- params?: DashboardsAnalyzeRefreshResultCreateParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/dashboards/${id}/analyze_refresh_result/?${stringifiedParams}`- : `/api/projects/${projectId}/dashboards/${id}/analyze_refresh_result/`-}--/**- * Generate AI analysis comparing before/after dashboard refresh.-Expects cache_key in request body pointing to the stored 'before' state.- */-export const dashboardsAnalyzeRefreshResultCreate = async (- projectId: string,- id: number,- dashboardApi?: NonReadonly<DashboardApi>,- params?: DashboardsAnalyzeRefreshResultCreateParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getDashboardsAnalyzeRefreshResultCreateUrl(projectId, id, params), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dashboardApi),- })-}-export const getDashboardsCopyTileCreateUrl = (projectId: string,id: number,@@ -783,45 +742,6 @@ export const dashboardsRunWidgetsRetrieve = async (})}-export const getDashboardsSnapshotCreateUrl = (- projectId: string,- id: number,- params?: DashboardsSnapshotCreateParams-) => {- const normalizedParams = new URLSearchParams()-- Object.entries(params || {}).forEach(([key, value]) => {- if (value !== undefined) {- normalizedParams.append(key, value === null ? 'null' : value.toString())- }- })-- const stringifiedParams = normalizedParams.toString()-- return stringifiedParams.length > 0- ? `/api/projects/${projectId}/dashboards/${id}/snapshot/?${stringifiedParams}`- : `/api/projects/${projectId}/dashboards/${id}/snapshot/`-}--/**- * Snapshot the current dashboard state (from cache) for AI analysis.-Returns a cache_key representing the 'before' state, to be used with analyze_refresh_result.- */-export const dashboardsSnapshotCreate = async (- projectId: string,- id: number,- dashboardApi?: NonReadonly<DashboardApi>,- params?: DashboardsSnapshotCreateParams,- options?: RequestInit-): Promise<void> => {- return apiMutator<void>(getDashboardsSnapshotCreateUrl(projectId, id, params), {- ...options,- method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(dashboardApi),- })-}-export const getDashboardsStreamTilesRetrieveUrl = (projectId: string,id: number,diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.tsindex 93693ea4051e..6c39201958b8 100644--- a/products/dashboards/frontend/generated/api.zod.ts+++ b/products/dashboards/frontend/generated/api.zod.ts@@ -246,48 +246,6 @@ export const DashboardsPartialUpdateBody = /* @__PURE__ */ zod}).describe('Serializer mixin that handles tags for objects.')-/**- * Generate AI analysis comparing before/after dashboard refresh.-Expects cache_key in request body pointing to the stored 'before' state.- */-export const dashboardsAnalyzeRefreshResultCreateBodyNameMax = 400--export const dashboardsAnalyzeRefreshResultCreateBodyDeleteInsightsDefault = false--export const DashboardsAnalyzeRefreshResultCreateBody = /* @__PURE__ */ zod- .object({- name: zod.string().max(dashboardsAnalyzeRefreshResultCreateBodyNameMax).nullish(),- description: zod.string().optional(),- pinned: zod.boolean().optional(),- last_accessed_at: zod.iso.datetime({ offset: true }).nullish(),- deleted: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),- data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),- tags: zod.array(zod.unknown()).optional(),- restriction_level: zod- .union([zod.literal(21), zod.literal(37)])- .optional()- .describe(- '\* `21` - Everyone in the project can edit\n\* `37` - Only those invited to this dashboard can edit'- ),- last_refresh: zod.iso.datetime({ offset: true }).nullish(),- quick_filter_ids: zod- .array(zod.string())- .nullish()- .describe('List of quick filter IDs associated with this dashboard'),- use_template: zod- .string()- .optional()- .describe('Template key to create the dashboard from a predefined template.'),- use_dashboard: zod.number().nullish().describe('ID of an existing dashboard to duplicate.'),- delete_insights: zod- .boolean()- .default(dashboardsAnalyzeRefreshResultCreateBodyDeleteInsightsDefault)- .describe('When deleting, also delete insights that are only on this dashboard.'),- _create_in_folder: zod.string().optional(),- })- .describe('Serializer mixin that handles tags for objects.')-/*** Copy an existing dashboard tile to another dashboard (insight, text card, or widget tile).*/@@ -392,48 +350,6 @@ export const DashboardsReorderTilesCreateBody = /* @__PURE__ */ zod.object({),})-/**- * Snapshot the current dashboard state (from cache) for AI analysis.-Returns a cache_key representing the 'before' state, to be used with analyze_refresh_result.- */-export const dashboardsSnapshotCreateBodyNameMax = 400--export const dashboardsSnapshotCreateBodyDeleteInsightsDefault = false--export const DashboardsSnapshotCreateBody = /* @__PURE__ */ zod- .object({- name: zod.string().max(dashboardsSnapshotCreateBodyNameMax).nullish(),- description: zod.string().optional(),- pinned: zod.boolean().optional(),- last_accessed_at: zod.iso.datetime({ offset: true }).nullish(),- deleted: zod.boolean().optional(),- breakdown_colors: zod.unknown().optional().describe('Custom color mapping for breakdown values.'),- data_color_theme_id: zod.number().nullish().describe('ID of the color theme used for chart visualizations.'),- tags: zod.array(zod.unknown()).optional(),- restriction_level: zod- .union([zod.literal(21), zod.literal(37)])- .optional()- .describe(- '\* `21` - Everyone in the project can edit\n\* `37` - Only those invited to this dashboard can edit'- ),- last_refresh: zod.iso.datetime({ offset: true }).nullish(),- quick_filter_ids: zod- .array(zod.string())- .nullish()- .describe('List of quick filter IDs associated with this dashboard'),- use_template: zod- .string()- .optional()- .describe('Template key to create the dashboard from a predefined template.'),- use_dashboard: zod.number().nullish().describe('ID of an existing dashboard to duplicate.'),- delete_insights: zod- .boolean()- .default(dashboardsSnapshotCreateBodyDeleteInsightsDefault)- .describe('When deleting, also delete insights that are only on this dashboard.'),- _create_in_folder: zod.string().optional(),- })- .describe('Serializer mixin that handles tags for objects.')-/*** Update the markdown body, layout, or color of an existing text tile on a dashboard.*/diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yamlindex 236ced9d76ef..a8992721b528 100644--- a/products/dashboards/mcp/tools.yaml+++ b/products/dashboards/mcp/tools.yaml@@ -414,9 +414,6 @@ tools:id:cast: string-intfeature_flag: dashboard-widgets- dashboards-analyze-refresh-result-create:- operation: dashboards_analyze_refresh_result_create- enabled: falsedashboards-bulk-update-tags-create:operation: dashboards_bulk_update_tags_createenabled: false@@ -496,9 +493,6 @@ tools:dashboards-sharing-refresh-create:operation: dashboards_sharing_refresh_createenabled: false- dashboards-snapshot-create:- operation: dashboards_snapshot_create- enabled: falsedashboards-stream-tiles-retrieve:operation: dashboards_stream_tiles_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex b25d38572484..1a0c4495775d 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42278,18 +42278,6 @@ export namespace Schemas {Txt: 'txt',} as const;- export type EnvironmentsDashboardsAnalyzeRefreshResultCreateParams = {- format?: EnvironmentsDashboardsAnalyzeRefreshResultCreateFormat;- };-- export type EnvironmentsDashboardsAnalyzeRefreshResultCreateFormat = typeof EnvironmentsDashboardsAnalyzeRefreshResultCreateFormat[keyof typeof EnvironmentsDashboardsAnalyzeRefreshResultCreateFormat];--- export const EnvironmentsDashboardsAnalyzeRefreshResultCreateFormat = {- Json: 'json',- Txt: 'txt',- } as const;-export type EnvironmentsDashboardsCopyTileCreateParams = {format?: EnvironmentsDashboardsCopyTileCreateFormat;};@@ -42423,18 +42411,6 @@ export namespace Schemas {Txt: 'txt',} as const;- export type EnvironmentsDashboardsSnapshotCreateParams = {- format?: EnvironmentsDashboardsSnapshotCreateFormat;- };-- export type EnvironmentsDashboardsSnapshotCreateFormat = typeof EnvironmentsDashboardsSnapshotCreateFormat[keyof typeof EnvironmentsDashboardsSnapshotCreateFormat];--- export const EnvironmentsDashboardsSnapshotCreateFormat = {- Json: 'json',- Txt: 'txt',- } as const;-export type EnvironmentsDashboardsStreamTilesRetrieveParams = {/*** Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.@@ -47592,18 +47568,6 @@ export namespace Schemas {Txt: 'txt',} as const;- export type DashboardsAnalyzeRefreshResultCreateParams = {- format?: DashboardsAnalyzeRefreshResultCreateFormat;- };-- export type DashboardsAnalyzeRefreshResultCreateFormat = typeof DashboardsAnalyzeRefreshResultCreateFormat[keyof typeof DashboardsAnalyzeRefreshResultCreateFormat];--- export const DashboardsAnalyzeRefreshResultCreateFormat = {- Json: 'json',- Txt: 'txt',- } as const;-export type DashboardsCopyTileCreateParams = {format?: DashboardsCopyTileCreateFormat;};@@ -47737,18 +47701,6 @@ export namespace Schemas {Txt: 'txt',} as const;- export type DashboardsSnapshotCreateParams = {- format?: DashboardsSnapshotCreateFormat;- };-- export type DashboardsSnapshotCreateFormat = typeof DashboardsSnapshotCreateFormat[keyof typeof DashboardsSnapshotCreateFormat];--- export const DashboardsSnapshotCreateFormat = {- Json: 'json',- Txt: 'txt',- } as const;-export type DashboardsStreamTilesRetrieveParams = {/*** Object (or pre-encoded JSON string) to override dashboard filters for this request only (not persisted). Top-level keys replace; nested values are not deep-merged — pass the complete value for any key you override. Accepts the same keys as the dashboard filters schema (e.g., `date_from`, `date_to`, `properties`). Ignored when accessed via a sharing token.