: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
feat(error-tracking): add missing source maps recommendation (#58306)
Aleksander Błaszkiewicz6a10fbc54bb6
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 7e0322342e37..0e3bcaed8495 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1059,7 +1059,7 @@ snapshots:components-playerinspector--with-logs-filter--dark:hash: v1.k794b7964.537624adca851ef7e40b2919c9a4f1210f889d52e7252a2d9872b7e5505699c4.FPTbSCzHxm_zEN6ukUKgJmKnxcxa8lUCeRMeXkiKQ6gcomponents-playerinspector--with-logs-filter--light:- hash: v1.k794b7964.fc1e747bd67f854c0af094265d80864fbf4d5209a58f51ed3a687505e1f07ec1.D72cCuWMnCuMOTIlraogIRFg4FGpFNvO7dmSuiku2sc+ hash: v1.k794b7964.e4a2b000ff9ea9e18a9474d1924a797f9893a9581dc66533aaf628ee52fc68cf.E5TauuBHMLbTsqudJivv3X0OISOKJcmgfPlp6Gdg15Mcomponents-playerinspector--with-logs-filter-upsell--dark:hash: v1.k794b7964.31676235fb000d8f24fa2d59f359f5c873a51574d5d923738c276e783cf464de.Vcyb2UICIL3mRG4QCqh_Uz9cp7kLVRPTgsGJrDZ8R6Ecomponents-playerinspector--with-logs-filter-upsell--light:diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex 875d4508aaaa..0e5a3bbe2c1f 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -286,6 +286,7 @@ export const FEATURE_FLAGS = {ERROR_TRACKING_RATE_LIMITING_PER_ISSUE: 'error-tracking-rate-limiting-per-issue', // owner: @ablaszkiewicz #team-error-trackingERROR_TRACKING_RECOMMENDATIONS: 'error-tracking-recommendations', // owner: @ablaszkiewicz #team-error-trackingERROR_TRACKING_RELATED_ISSUES: 'error-tracking-related-issues', // owner: #team-error-tracking+ ERROR_TRACKING_SOURCE_MAPS_BANNER: 'error-tracking-source-maps-banner', // owner: @ablaszkiewicz #team-error-trackingERROR_TRACKING_WEEKLY_DIGEST: 'error-tracking-weekly-digest', // owner: #team-error-trackingEVENT_MEDIA_PREVIEWS: 'event-media-previews', // owner: @alexliderEXPERIMENT_CUPED: 'experiment-cuped', // owner: @andehen #team-experimentsdiff --git a/products/error_tracking/backend/api/test/test_recommendations.py b/products/error_tracking/backend/api/test/test_recommendations.pyindex c93c4bd7ed17..099e31e493af 100644--- a/products/error_tracking/backend/api/test/test_recommendations.py+++ b/products/error_tracking/backend/api/test/test_recommendations.py@@ -16,10 +16,12 @@ from products.error_tracking.backend.models import (ErrorTrackingIssue,ErrorTrackingIssueFingerprintV2,ErrorTrackingRecommendation,+ ErrorTrackingStackFrame,sync_issues_to_clickhouse,)from products.error_tracking.backend.recommendations.alerts import AlertsRecommendationfrom products.error_tracking.backend.recommendations.long_running_issues import LongRunningIssuesRecommendation+from products.error_tracking.backend.recommendations.source_maps import SourceMapsRecommendationfrom ee.clickhouse.materialized_columns.columns import materialize@@ -69,15 +71,15 @@ class TestRecommendationsAPI(ClickhouseTestMixin, APIBaseTest):"products.error_tracking.backend.recommendations.alerts.AlertsRecommendation.compute",return_value=MOCK_ALERTS_META,)- def test_first_list_creates_both_recommendations(self, mock_alerts, mock_long_running):+ def test_first_list_creates_all_recommendations(self, mock_alerts, mock_long_running):self.assertEqual(ErrorTrackingRecommendation.objects.filter(team=self.team).count(), 0)response = self._list()self.assertEqual(response.status_code, status.HTTP_200_OK)- self.assertEqual(ErrorTrackingRecommendation.objects.filter(team=self.team).count(), 2)+ self.assertEqual(ErrorTrackingRecommendation.objects.filter(team=self.team).count(), 3)types = {r["type"] for r in response.json()["results"]}- self.assertEqual(types, {"alerts", "long_running_issues"})+ self.assertEqual(types, {"alerts", "long_running_issues", "source_maps"})@patch("products.error_tracking.backend.recommendations.long_running_issues.LongRunningIssuesRecommendation.compute",@@ -349,7 +351,7 @@ class TestRecommendationsAPI(ClickhouseTestMixin, APIBaseTest):self.assertEqual(response.status_code, status.HTTP_200_OK)statuses = {r["type"]: r["status"] for r in response.json()["results"]}- self.assertEqual(statuses, {"alerts": "ready", "long_running_issues": "ready"})+ self.assertEqual(statuses, {"alerts": "ready", "long_running_issues": "ready", "source_maps": "ready"})# Each recommendation row should have been computed exactly once via the celery task path.self.assertEqual(mock_alerts.call_count, 1)self.assertEqual(mock_long_running.call_count, 1)@@ -373,6 +375,101 @@ class TestRecommendationsAPI(ClickhouseTestMixin, APIBaseTest):mock_alerts.assert_not_called()mock_long_running.assert_not_called()+ def _make_frame(self, lang: str, resolved: bool, created_hours_ago: int = 1) -> ErrorTrackingStackFrame:+ frame = ErrorTrackingStackFrame.objects.create(+ team=self.team,+ raw_id=str(uuid4()),+ contents={"lang": lang},+ resolved=resolved,+ )+ ErrorTrackingStackFrame.objects.filter(id=frame.id).update(+ created_at=timezone.now() - timedelta(hours=created_hours_ago)+ )+ return frame++ def test_source_maps_compute_with_no_frames(self):+ meta = SourceMapsRecommendation().compute(self.team)++ self.assertEqual(meta["total_frames"], 0)+ self.assertEqual(meta["unresolved_frames"], 0)+ self.assertEqual(meta["unresolved_pct"], 0.0)++ def test_source_maps_compute_counts_unresolved_js_frames(self):+ for _ in range(8):+ self._make_frame(lang="javascript", resolved=True)+ for _ in range(2):+ self._make_frame(lang="javascript", resolved=False)++ meta = SourceMapsRecommendation().compute(self.team)++ self.assertEqual(meta["total_frames"], 10)+ self.assertEqual(meta["unresolved_frames"], 2)+ self.assertEqual(meta["unresolved_pct"], 0.2)++ def test_source_maps_compute_ignores_non_js_frames(self):+ self._make_frame(lang="python", resolved=False)+ self._make_frame(lang="ruby", resolved=False)+ self._make_frame(lang="javascript", resolved=True)++ meta = SourceMapsRecommendation().compute(self.team)++ self.assertEqual(meta["total_frames"], 1)+ self.assertEqual(meta["unresolved_frames"], 0)++ def test_source_maps_compute_ignores_frames_outside_lookback(self):+ self._make_frame(lang="javascript", resolved=False, created_hours_ago=48)+ self._make_frame(lang="javascript", resolved=True, created_hours_ago=1)++ meta = SourceMapsRecommendation().compute(self.team)++ self.assertEqual(meta["total_frames"], 1)+ self.assertEqual(meta["unresolved_frames"], 0)++ def test_source_maps_compute_ignores_other_teams_frames(self):+ other_team = self.organization.teams.create(name="other")+ ErrorTrackingStackFrame.objects.create(+ team=other_team,+ raw_id=str(uuid4()),+ contents={"lang": "javascript"},+ resolved=False,+ )++ meta = SourceMapsRecommendation().compute(self.team)++ self.assertEqual(meta["total_frames"], 0)++ def test_source_maps_is_completed_when_below_threshold(self):+ # 5% unresolved, threshold is 30%+ meta = {+ "total_frames": 100,+ "unresolved_frames": 5,+ "unresolved_pct": 0.05,+ "threshold_pct": 0.30,+ "min_sample_frames": 20,+ }+ self.assertTrue(SourceMapsRecommendation().is_completed(meta))++ def test_source_maps_is_completed_false_when_above_threshold(self):+ meta = {+ "total_frames": 100,+ "unresolved_frames": 45,+ "unresolved_pct": 0.45,+ "threshold_pct": 0.30,+ "min_sample_frames": 20,+ }+ self.assertFalse(SourceMapsRecommendation().is_completed(meta))++ def test_source_maps_is_completed_when_below_min_sample(self):+ # Even at 100% unresolved, with too few frames we don't fire the recommendation.+ meta = {+ "total_frames": 5,+ "unresolved_frames": 5,+ "unresolved_pct": 1.0,+ "threshold_pct": 0.30,+ "min_sample_frames": 20,+ }+ self.assertTrue(SourceMapsRecommendation().is_completed(meta))+@patch("products.error_tracking.backend.recommendations.long_running_issues.LongRunningIssuesRecommendation.compute",return_value={"issues": []},diff --git a/products/error_tracking/backend/recommendations/__init__.py b/products/error_tracking/backend/recommendations/__init__.pyindex 6e0ac3b0061e..2d90ca2630d1 100644--- a/products/error_tracking/backend/recommendations/__init__.py+++ b/products/error_tracking/backend/recommendations/__init__.py@@ -1,10 +1,12 @@from .alerts import AlertsRecommendationfrom .base import Recommendationfrom .long_running_issues import LongRunningIssuesRecommendation+from .source_maps import SourceMapsRecommendationRECOMMENDATIONS: list[Recommendation] = [AlertsRecommendation(),LongRunningIssuesRecommendation(),+ SourceMapsRecommendation(),]RECOMMENDATIONS_BY_TYPE: dict[str, Recommendation] = {r.type: r for r in RECOMMENDATIONS}diff --git a/products/error_tracking/backend/recommendations/source_maps.py b/products/error_tracking/backend/recommendations/source_maps.pynew file mode 100644index 000000000000..44302c674ecb--- /dev/null+++ b/products/error_tracking/backend/recommendations/source_maps.py@@ -0,0 +1,63 @@+from datetime import timedelta+from typing import Any++from django.db.models import Count, Q+from django.utils import timezone++from posthog.models.team.team import Team++from products.error_tracking.backend.models import ErrorTrackingStackFrame++from .base import Recommendation++# Don't fire the recommendation unless we have a meaningful sample.+# Tiny teams with a couple of errors shouldn't get a noisy card.+MIN_SAMPLE_FRAMES = 20++# Show the card when more than this fraction of recent JS/TS frames are unresolved.+UNRESOLVED_THRESHOLD = 0.30++LOOKBACK_HOURS = 24+++class SourceMapsRecommendation(Recommendation):+ type = "source_maps"+ refresh_interval = timedelta(hours=6)++ def compute(self, team: Team) -> dict[str, Any]:+ # `lang` is set on the resolved frame contents by cymbal — both browser JS+ # and Node frames are tagged "javascript". TypeScript frames also surface+ # as "javascript" pre-resolution; the source map is what would map them+ # back to the original .ts source, so they're exactly the population we+ # care about here.+ since = timezone.now() - timedelta(hours=LOOKBACK_HOURS)++ counts = ErrorTrackingStackFrame.objects.filter(+ team=team,+ created_at__gte=since,+ contents__lang="javascript",+ ).aggregate(+ total=Count("id"),+ unresolved=Count("id", filter=Q(resolved=False)),+ )++ total = counts["total"] or 0+ unresolved = counts["unresolved"] or 0+ unresolved_pct = (unresolved / total) if total > 0 else 0.0++ return {+ "total_frames": total,+ "unresolved_frames": unresolved,+ "unresolved_pct": unresolved_pct,+ "threshold_pct": UNRESOLVED_THRESHOLD,+ "min_sample_frames": MIN_SAMPLE_FRAMES,+ "lookback_hours": LOOKBACK_HOURS,+ }++ def is_completed(self, meta: dict[str, Any]) -> bool:+ total = meta.get("total_frames") or 0+ if total < MIN_SAMPLE_FRAMES:+ return True+ unresolved_pct = meta.get("unresolved_pct") or 0.0+ threshold = meta.get("threshold_pct") or UNRESOLVED_THRESHOLD+ return unresolved_pct <= thresholddiff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene.tsxindex 62acb945ab85..df749cb24bb7 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/ErrorTrackingScene.tsx@@ -32,6 +32,7 @@ import {import { ErrorTrackingInsights } from './tabs/insights/ErrorTrackingInsights'import { IssuesFilters } from './tabs/issues/IssuesFilters'import { IssuesList } from './tabs/issues/IssuesList'+import { SourceMapsBanner } from './tabs/issues/SourceMapsBanner'import { RecommendationsTab } from './tabs/recommendations/RecommendationsTab'const ERROR_TRACKING_ALERT_FILTER_GROUPS: CyclotronJobFiltersType[] = [@@ -50,6 +51,7 @@ export function ErrorTrackingScene(): JSX.Element {const { activeTab } = useValues(errorTrackingSceneLogic)const { setActiveTab } = useActions(errorTrackingSceneLogic)const hasRecommendations = useFeatureFlag('ERROR_TRACKING_RECOMMENDATIONS')+ const hasSourceMapsBanner = useFeatureFlag('ERROR_TRACKING_SOURCE_MAPS_BANNER')useOnMountEffect(() => {const utmSource = new URLSearchParams(window.location.search).get('utm_source')@@ -75,6 +77,7 @@ export function ErrorTrackingScene(): JSX.Element {<ErrorTrackingSetupPrompt><ErrorTrackingIssueFilteringTool />{hasSentExceptionEventLoading || hasSentExceptionEvent ? null : <IngestionStatusCheck />}+ {hasSourceMapsBanner ? <SourceMapsBanner /> : null}<div className="border rounded bg-surface-primary p-2"><IssuesFilters /></div>diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/SourceMapsBanner.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/SourceMapsBanner.tsxnew file mode 100644index 000000000000..ff2c3b7e9d17--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/issues/SourceMapsBanner.tsx@@ -0,0 +1,45 @@+import { useActions, useValues } from 'kea'++import { IconMagicWand } from '@posthog/icons'+import { LemonBanner } from '@posthog/lemon-ui'++import { isSourceMapsRecommendation, recommendationsTabLogic } from '../recommendations/recommendationsTabLogic'+import { SourceMapsFixModal } from '../recommendations/SourceMapsFixModal'+import { sourceMapsFixWizardLogic } from '../recommendations/sourceMapsFixWizardLogic'++// Dismissal is independent of the source maps recommendation's own dismissed_at —+// dismissing here only hides this banner, via the standard localStorage-backed pattern.+const DISMISS_KEY = 'error-tracking-source-maps-banner'++export function SourceMapsBanner(): JSX.Element | null {+ const { recommendations } = useValues(recommendationsTabLogic)+ const { openModal } = useActions(sourceMapsFixWizardLogic)++ const sourceMaps = recommendations.find(isSourceMapsRecommendation)+ // Show only once computed and while there's an actual problem (not completed),+ // regardless of whether the recommendation itself was dismissed.+ if (!sourceMaps || sourceMaps.computed_at === null || sourceMaps.completed) {+ return null+ }++ const percent = Math.round((sourceMaps.meta.unresolved_pct ?? 0) * 100)++ return (+ <>+ <LemonBanner+ type="warning"+ className="mb-2"+ dismissKey={DISMISS_KEY}+ action={{+ children: 'Fix with wizard',+ icon: <IconMagicWand />,+ onClick: () => openModal('issues_list'),+ }}+ >+ We detected that {percent}% of your stack frames in the last {sourceMaps.meta.lookback_hours} hours are+ missing source maps, so their stack traces aren't readable. Run the setup wizard to upload them.+ </LemonBanner>+ <SourceMapsFixModal />+ </>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/RecommendationsTab.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/RecommendationsTab.tsxindex e98aa16812f5..22e7a16a86fe 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/RecommendationsTab.tsx+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/RecommendationsTab.tsx@@ -8,8 +8,10 @@ import { LongRunningIssuesRecommendationCard } from './LongRunningIssuesRecommenimport {isAlertsRecommendation,isLongRunningIssuesRecommendation,+ isSourceMapsRecommendation,recommendationsTabLogic,} from './recommendationsTabLogic'+import { SourceMapsRecommendationCard } from './SourceMapsRecommendationCard'import type { ErrorTrackingRecommendation } from './types'function RecommendationCardForType({@@ -25,6 +27,9 @@ function RecommendationCardForType({if (isLongRunningIssuesRecommendation(recommendation)) {return <LongRunningIssuesRecommendationCard recommendation={recommendation} dismissed={dismissed} />}+ if (isSourceMapsRecommendation(recommendation)) {+ return <SourceMapsRecommendationCard recommendation={recommendation} dismissed={dismissed} />+ }return null}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/SourceMapsFixModal.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/SourceMapsFixModal.tsxnew file mode 100644index 000000000000..e0a141b90c88--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/SourceMapsFixModal.tsx@@ -0,0 +1,117 @@+import { useActions, useValues } from 'kea'++import { IconCheckCircle, IconThumbsDown, IconThumbsUp } from '@posthog/icons'+import { LemonButton, LemonModal, LemonSegmentedButton, LemonTextArea } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { Popover } from 'lib/lemon-ui/Popover'+import { cn } from 'lib/utils/css-classes'++import { RATING_SCALE, sourceMapsFixWizardLogic } from './sourceMapsFixWizardLogic'++export function SourceMapsFixModal(): JSX.Element {+ const { isModalOpen, wizardCommand, feedbackRevealed, rating, ratingScore, feedbackText, feedbackSubmitted } =+ useValues(sourceMapsFixWizardLogic)+ const { closeModal, rateWizard, setRatingScore, setFeedbackText, submitFeedback, dismissFeedback } =+ useActions(sourceMapsFixWizardLogic)++ const positiveRating = ratingScore !== null && ratingScore > Math.ceil(RATING_SCALE / 2)++ return (+ <LemonModal isOpen={isModalOpen} onClose={closeModal} width={540} title="Let the wizard set up source maps">+ <div className="flex flex-col gap-4">+ <div className="flex items-start gap-3">+ <p className="text-secondary mb-0">+ The PostHog wizard detects your framework and wires up source map uploads, and verifies+ everything works. Just run this in your project's root directory:+ </p>+ </div>++ <CodeSnippet language={Language.Bash}>{wizardCommand}</CodeSnippet>++ <div+ className={cn(+ 'grid transition-all duration-500 ease-out',+ feedbackRevealed ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'+ )}+ >+ <div className="overflow-hidden">+ <div className="flex items-center justify-between gap-2 border-t border-primary pt-3 mt-1">+ <span className="font-medium">How did the wizard do?</span>+ <Popover+ visible={rating !== null}+ onClickOutside={dismissFeedback}+ placement="top-end"+ overlay={+ <div className="flex flex-col gap-3 p-3 w-80">+ {feedbackSubmitted ? (+ <div className="flex items-center gap-2 py-1 font-medium text-success">+ <IconCheckCircle className="text-lg" />+ Thanks for the feedback!+ </div>+ ) : (+ <>+ <div className="flex flex-col gap-1">+ <span className="font-medium">How did the wizard do?</span>+ <LemonSegmentedButton+ fullWidth+ size="small"+ value={ratingScore ?? undefined}+ onChange={setRatingScore}+ options={Array.from({ length: RATING_SCALE }, (_, i) => ({+ value: i + 1,+ label: String(i + 1),+ }))}+ />+ <div className="flex justify-between text-xs text-muted">+ <span>Very bad</span>+ <span>Awesome</span>+ </div>+ </div>+ <LemonTextArea+ placeholder={+ positiveRating+ ? 'Nice! Anything that stood out? (optional)'+ : 'Sorry about that — what went wrong? (optional)'+ }+ value={feedbackText}+ onChange={setFeedbackText}+ minRows={3}+ autoFocus+ />+ <div className="flex justify-end">+ <LemonButton type="primary" size="small" onClick={submitFeedback}>+ Send+ </LemonButton>+ </div>+ </>+ )}+ </div>+ }+ >+ <div className="flex gap-1">+ <LemonButton+ icon={<IconThumbsUp />}+ type="secondary"+ size="small"+ active={rating === 'good'}+ onClick={() => rateWizard('good')}+ tooltip="It worked"+ />+ <LemonButton+ icon={<IconThumbsDown />}+ type="secondary"+ size="small"+ active={rating === 'bad'}+ onClick={() => rateWizard('bad')}+ tooltip="Didn't work"+ />+ </div>+ </Popover>+ </div>+ </div>+ </div>+ </div>+ </LemonModal>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/SourceMapsRecommendationCard.tsx b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/SourceMapsRecommendationCard.tsxnew file mode 100644index 000000000000..fafafef0639f--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/SourceMapsRecommendationCard.tsx@@ -0,0 +1,51 @@+import { useActions } from 'kea'++import { IconMagicWand } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { RecommendationCard } from './RecommendationCard'+import { SourceMapsFixModal } from './SourceMapsFixModal'+import { sourceMapsFixWizardLogic } from './sourceMapsFixWizardLogic'+import type { SourceMapsRecommendation } from './types'++export function SourceMapsRecommendationCard({+ recommendation,+ dismissed,+}: {+ recommendation: SourceMapsRecommendation+ dismissed?: boolean+}): JSX.Element | null {+ const { unresolved_pct, lookback_hours } = recommendation.meta+ const { openModal } = useActions(sourceMapsFixWizardLogic)+ const isFirstLoad = recommendation.computed_at === null++ if (isFirstLoad) {+ return (+ <RecommendationCard+ recommendationId={recommendation.id}+ title="Missing source maps"+ description="Upload source maps so JavaScript stack traces show your original source code."+ dismissed={dismissed}+ />+ )+ }++ const percent = Math.round((unresolved_pct ?? 0) * 100)++ return (+ <RecommendationCard recommendationId={recommendation.id} title="Missing source maps" dismissed={dismissed}>+ <div className="flex flex-col items-center gap-1 py-2">+ <div className="text-5xl font-bold leading-none">{percent}%</div>+ <div className="text-xs text-secondary">+ of frames were unresolved in the last {lookback_hours} hours+ </div>+ </div>+ <div className="flex justify-center mt-2">+ <LemonButton type="primary" icon={<IconMagicWand />} onClick={() => openModal('recommendations')}>+ Fix with wizard+ </LemonButton>+ </div>+ <SourceMapsFixModal />+ </RecommendationCard>+ )+}diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/recommendationsTabLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/recommendationsTabLogic.tsindex 669b889313e8..ca8821946b1b 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/recommendationsTabLogic.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/recommendationsTabLogic.ts@@ -7,7 +7,12 @@ import api from 'lib/api'import { HogFunctionSubTemplateIdType } from '~/types'import type { recommendationsTabLogicType } from './recommendationsTabLogicType'-import type { AlertsRecommendation, ErrorTrackingRecommendation, LongRunningIssuesRecommendation } from './types'+import type {+ AlertsRecommendation,+ ErrorTrackingRecommendation,+ LongRunningIssuesRecommendation,+ SourceMapsRecommendation,+} from './types'export const isAlertsRecommendation = (recommendation: ErrorTrackingRecommendation@@ -17,6 +22,10 @@ export const isLongRunningIssuesRecommendation = (recommendation: ErrorTrackingRecommendation): recommendation is LongRunningIssuesRecommendation => recommendation.type === 'long_running_issues'+export const isSourceMapsRecommendation = (+ recommendation: ErrorTrackingRecommendation+): recommendation is SourceMapsRecommendation => recommendation.type === 'source_maps'+const POLL_INTERVAL_MS = 500// The backend `status` field is the single source of truth for "is this recommendationdiff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsFixWizardLogic.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsFixWizardLogic.tsnew file mode 100644index 000000000000..56699f2650e5--- /dev/null+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/sourceMapsFixWizardLogic.ts@@ -0,0 +1,139 @@+import { actions, kea, listeners, path, reducers, selectors } from 'kea'+import posthog from 'posthog-js'++import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'+import { getSurveyIdBasedResponseKey, getSurveyResponseKey } from 'scenes/surveys/utils'++import { Region, SurveyEventName, SurveyEventProperties } from '~/types'++import type { sourceMapsFixWizardLogicType } from './sourceMapsFixWizardLogicType'++export type WizardRating = 'good' | 'bad'+export type WizardOpenSource = 'issues_list' | 'recommendations'++// Delay before we ask "how did the wizard do?" — long enough that the user has+// actually had a chance to copy the command and kick the wizard off.+const FEEDBACK_REVEAL_DELAY_MS = 1000++export const RATING_SCALE = 5+const GOOD_RATING = 5+const BAD_RATING = 1++// API survey that collects source maps wizard feedback: a 1-5 rating question+// followed by an open feedback question.+const SURVEY_ID = '019e7335-af36-0000-42a8-ad5add623630'+const RATING_QUESTION_ID = '030dde7d-0dee-4d79-b568-ed16e85b431c'+const FEEDBACK_QUESTION_ID = '03e1255c-6daf-46a2-9629-2354bcd230ff'++export const sourceMapsFixWizardLogic = kea<sourceMapsFixWizardLogicType>([+ path([+ 'products',+ 'error_tracking',+ 'scenes',+ 'ErrorTrackingScene',+ 'tabs',+ 'recommendations',+ 'sourceMapsFixWizardLogic',+ ]),++ actions({+ openModal: (source: WizardOpenSource) => ({ source }),+ closeModal: true,+ revealFeedback: true,+ rateWizard: (rating: WizardRating) => ({ rating }),+ setRatingScore: (ratingScore: number) => ({ ratingScore }),+ setFeedbackText: (feedbackText: string) => ({ feedbackText }),+ submitFeedback: true,+ dismissFeedback: true,+ }),++ reducers({+ isModalOpen: [+ false,+ {+ openModal: () => true,+ closeModal: () => false,+ },+ ],+ feedbackRevealed: [+ false,+ {+ openModal: () => false,+ closeModal: () => false,+ revealFeedback: () => true,+ },+ ],+ rating: [+ null as WizardRating | null,+ {+ openModal: () => null,+ closeModal: () => null,+ dismissFeedback: () => null,+ rateWizard: (_, { rating }) => rating,+ },+ ],+ // Not reset on dismissFeedback: the popover stays mounted during its+ // fade-out, so clearing these here would flash the content back to the+ // input form mid-transition. rateWizard/openModal/closeModal reset them.+ ratingScore: [+ null as number | null,+ {+ openModal: () => null,+ closeModal: () => null,+ rateWizard: (_, { rating }) => (rating === 'good' ? GOOD_RATING : BAD_RATING),+ setRatingScore: (_, { ratingScore }) => ratingScore,+ },+ ],+ feedbackText: [+ '',+ {+ openModal: () => '',+ closeModal: () => '',+ rateWizard: () => '',+ setFeedbackText: (_, { feedbackText }) => feedbackText,+ },+ ],+ feedbackSubmitted: [+ false,+ {+ openModal: () => false,+ closeModal: () => false,+ rateWizard: () => false,+ submitFeedback: () => true,+ },+ ],+ }),++ selectors({+ wizardCommand: [+ () => [preflightLogic.selectors.preflight],+ (preflight): string =>+ `npx -y @posthog/wizard@latest upload-sourcemaps${preflight?.region === Region.EU ? ' --region eu' : ''}`,+ ],+ }),++ listeners(({ actions, values, cache }) => ({+ openModal: ({ source }) => {+ posthog.capture('error_tracking_source_maps_wizard_opened', { source })+ cache.disposables.dispose('feedback-reveal')+ cache.disposables.add(() => {+ const timeout = setTimeout(() => actions.revealFeedback(), FEEDBACK_REVEAL_DELAY_MS)+ return () => clearTimeout(timeout)+ }, 'feedback-reveal')+ },+ closeModal: () => {+ cache.disposables.dispose('feedback-reveal')+ },+ submitFeedback: () => {+ const feedback = values.feedbackText.trim()+ posthog.capture(SurveyEventName.SENT, {+ [SurveyEventProperties.SURVEY_ID]: SURVEY_ID,+ [getSurveyResponseKey(0)]: values.ratingScore,+ [getSurveyIdBasedResponseKey(RATING_QUESTION_ID)]: values.ratingScore,+ [getSurveyResponseKey(1)]: feedback,+ [getSurveyIdBasedResponseKey(FEEDBACK_QUESTION_ID)]: feedback,+ [SurveyEventProperties.SURVEY_COMPLETED]: true,+ })+ },+ })),+])diff --git a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/types.ts b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/types.tsindex 7b1108e59d44..abfc28239c97 100644--- a/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/types.ts+++ b/products/error_tracking/frontend/scenes/ErrorTrackingScene/tabs/recommendations/types.ts@@ -1,7 +1,7 @@import { ErrorTrackingIssue } from '~/queries/schema/schema-general'import { HogFunctionSubTemplateIdType } from '~/types'-export type ErrorTrackingRecommendationType = 'alerts' | 'long_running_issues'+export type ErrorTrackingRecommendationType = 'alerts' | 'long_running_issues' | 'source_maps'export type ErrorTrackingRecommendationStatus = 'ready' | 'computing'@@ -62,3 +62,14 @@ export interface LongRunningIssuesRecommendationMeta extends Record<string, unkn}export type LongRunningIssuesRecommendation = ErrorTrackingRecommendation<LongRunningIssuesRecommendationMeta>++export interface SourceMapsRecommendationMeta extends Record<string, unknown> {+ total_frames: number+ unresolved_frames: number+ unresolved_pct: number+ threshold_pct: number+ min_sample_frames: number+ lookback_hours: number+}++export type SourceMapsRecommendation = ErrorTrackingRecommendation<SourceMapsRecommendationMeta>