Skip to content

: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.

feat(replay_vision): promote an existing summary to the featured digest (#75144)

Kim Svatos Dugane1d1733557b3
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
index 74b3c37c37e8..98a4a04427fb 100644
--- a/products/replay_vision/backend/api/vision_actions.py
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -384,7 +384,7 @@ class VisionActionSerializer(serializers.ModelSerializer):
def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
self._validate_schedule(attrs)
self._validate_unique_name(attrs)
- self._validate_unique_digest(attrs)
+ self._validate_digest(attrs)
self._validate_alert(attrs)
self._validate_scanner_access(attrs)
return attrs
@@ -495,23 +495,55 @@ class VisionActionSerializer(serializers.ModelSerializer):
if duplicates.exists():
raise serializers.ValidationError({"name": "An action with this name already exists in this team."})
- def _validate_unique_digest(self, attrs: dict[str, Any]) -> None:
- # Surface the one-digest-per-scanner constraint as a 400 instead of letting the DB raise 500.
+ def _validate_digest(self, attrs: dict[str, Any]) -> None:
+ # The overview card renders the featured digest as a synthesized summary, so an alert can't
+ # occupy that slot. Promoting to the featured slot is otherwise always allowed — create()/update()
+ # atomically demote the scanner's current digest, so the one-per-scanner index never trips.
if not attrs.get("is_scanner_digest"):
return
- scanner = attrs.get("scanner") or getattr(self.instance, "scanner", None)
- if scanner is None:
- return
+ mode = attrs.get("mode", getattr(self.instance, "mode", ActionMode.GROUP_SUMMARY))
+ if mode == ActionMode.ALERT:
+ raise serializers.ValidationError({"is_scanner_digest": "Only summaries can be the featured digest."})
+
+ def _demote_existing_digest(self, scanner: ReplayScanner) -> None:
+ # Clear any current featured digest on this scanner before promoting another, so the partial
+ # unique index (vision_action_unique_scanner_digest) sees at most one flagged row. Runs in the
+ # caller's transaction (perform_create/perform_update wrap save() in transaction.atomic).
team = self.context["get_team"]()
- duplicates = VisionAction.objects.for_team(team.id).filter(scanner=scanner, is_scanner_digest=True)
+ demote = VisionAction.objects.for_team(team.id).filter(scanner=scanner, is_scanner_digest=True)
if self.instance is not None:
- duplicates = duplicates.exclude(pk=self.instance.pk)
- if duplicates.exists():
- raise serializers.ValidationError({"is_scanner_digest": "This scanner already has a daily digest."})
+ demote = demote.exclude(pk=self.instance.pk)
+ # This bulk update is a write to the current digest. A direct PATCH to it would run
+ # _validate_scanner_access; authorize the same way here so promoting can't be a back door to
+ # modifying a digest whose selection reads from a scanner the requesting user can't access.
+ self._authorize_demotions(demote)
+ demote.update(is_scanner_digest=False)
+
+ def _authorize_demotions(self, actions: QuerySet[VisionAction]) -> None:
+ request = self.context.get("request")
+ if request is None or not getattr(request.user, "is_authenticated", False):
+ return
+ # The bound scanner is the promotion target (already editor-checked upstream); the exposure is
+ # each demoted digest's selection.scanner_ids, which _validate_scanner_access guards on a direct
+ # write. Gather every scanner these actions read from and require read access to all of them.
+ requested: set[str] = set()
+ for demoted in actions:
+ requested.add(str(demoted.scanner_id))
+ requested.update(str(s) for s in (demoted.selection or {}).get("scanner_ids") or [])
+ if not requested:
+ return
+ team = self.context["get_team"]()
+ readable = set(readable_scanner_ids(request.user, team, list(requested)))
+ if requested - readable:
+ raise serializers.ValidationError(
+ {"is_scanner_digest": "You don't have access to a scanner the current digest reads from."}
+ )
def create(self, validated_data: dict[str, Any]) -> VisionAction:
team = self.context["get_team"]()
user = cast(User, self.context["request"].user)
+ if validated_data.get("is_scanner_digest"):
+ self._demote_existing_digest(validated_data["scanner"])
try:
# for_team()'s filter doesn't propagate into create(), so team is still passed explicitly.
return VisionAction.objects.for_team(team.id).create(team=team, created_by=user, **validated_data)
@@ -519,6 +551,8 @@ class VisionActionSerializer(serializers.ModelSerializer):
self._reraise_unique_violation(e)
def update(self, instance: VisionAction, validated_data: dict[str, Any]) -> VisionAction:
+ if validated_data.get("is_scanner_digest"):
+ self._demote_existing_digest(validated_data.get("scanner", instance.scanner))
try:
return super().update(instance, validated_data)
except IntegrityError as e:
diff --git a/products/replay_vision/backend/tests/test_vision_actions_api.py b/products/replay_vision/backend/tests/test_vision_actions_api.py
index 19f2f9e68dbf..4c5ab3adb3d9 100644
--- a/products/replay_vision/backend/tests/test_vision_actions_api.py
+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py
@@ -182,17 +182,96 @@ class TestVisionActionViewSet(_VisionActionAPITestCase):
resp = self.client.patch(f"{self.actions_url}{resp.json()['id']}/", data={"enabled": True}, format="json")
self.assertEqual(resp.status_code, 400, resp.content)
- def test_second_digest_for_scanner_rejected(self) -> None:
+ def _flagged_digest_ids(self) -> list[str]:
+ return [
+ str(pk)
+ for pk in VisionAction.all_teams.filter(scanner=self.scanner, is_scanner_digest=True).values_list(
+ "id", flat=True
+ )
+ ]
+
+ def test_promote_existing_summary_to_digest(self) -> None:
+ # The user's case: no digest exists (deleted), a plain summary does — promoting it via PATCH
+ # should make it the featured digest.
+ created = self.client.post(self.actions_url, data=self._create_payload(name="my-summary"), format="json")
+ self.assertEqual(created.status_code, 201, created.content)
+ summary_id = created.json()["id"]
+ self.assertFalse(created.json()["is_scanner_digest"])
+
+ promoted = self.client.patch(
+ f"{self.actions_url}{summary_id}/", data={"is_scanner_digest": True}, format="json"
+ )
+ self.assertEqual(promoted.status_code, 200, promoted.content)
+ self.assertTrue(promoted.json()["is_scanner_digest"])
+ self.assertEqual(self._flagged_digest_ids(), [summary_id])
+
+ def test_promoting_a_summary_demotes_the_current_digest(self) -> None:
+ old = self.client.post(
+ self.actions_url, data=self._create_payload(name="digest-1", is_scanner_digest=True), format="json"
+ )
+ self.assertEqual(old.status_code, 201, old.content)
+ new = self.client.post(self.actions_url, data=self._create_payload(name="summary-2"), format="json")
+ self.assertEqual(new.status_code, 201, new.content)
+ new_id = new.json()["id"]
+
+ promoted = self.client.patch(f"{self.actions_url}{new_id}/", data={"is_scanner_digest": True}, format="json")
+ self.assertEqual(promoted.status_code, 200, promoted.content)
+ # Exactly one featured digest per scanner, and it's the newly promoted one.
+ self.assertEqual(self._flagged_digest_ids(), [new_id])
+
+ def test_creating_a_digest_swaps_the_existing_one(self) -> None:
first = self.client.post(
self.actions_url, data=self._create_payload(name="digest-1", is_scanner_digest=True), format="json"
)
self.assertEqual(first.status_code, 201, first.content)
- self.assertTrue(first.json()["is_scanner_digest"])
second = self.client.post(
self.actions_url, data=self._create_payload(name="digest-2", is_scanner_digest=True), format="json"
)
- self.assertEqual(second.status_code, 400, second.content)
- self.assertIn("daily digest", second.json()["detail"].lower())
+ self.assertEqual(second.status_code, 201, second.content)
+ self.assertEqual(self._flagged_digest_ids(), [second.json()["id"]])
+
+ def test_promotion_blocked_when_current_digest_reads_a_restricted_scanner(self) -> None:
+ # Demoting the current digest is a write to it. If that digest's selection reads from a scanner
+ # the promoting user can't access, a direct PATCH would be rejected — promoting must not be a
+ # back door around that check, and the restricted digest must stay put.
+ hidden = self._create_scanner(name="restricted")
+ current = VisionAction.all_teams.create(
+ team=self.team,
+ scanner=self.scanner,
+ name="current-digest",
+ is_scanner_digest=True,
+ selection={"scanner_ids": [str(hidden.id)]},
+ trigger_config={"rrule": "FREQ=DAILY", "timezone": "UTC"},
+ )
+ summary = VisionAction.all_teams.create(
+ team=self.team,
+ scanner=self.scanner,
+ name="promote-me",
+ trigger_config={"rrule": "FREQ=DAILY", "timezone": "UTC"},
+ )
+ with patch(
+ "products.replay_vision.backend.scanner_access.UserAccessControl.filter_queryset_by_access_level",
+ side_effect=lambda qs, **_: qs.exclude(pk=hidden.pk),
+ ):
+ resp = self.client.patch(
+ f"{self.actions_url}{summary.id}/", data={"is_scanner_digest": True}, format="json"
+ )
+ self.assertEqual(resp.status_code, 400, resp.content)
+ self.assertIn("access", resp.json()["detail"])
+ # The promotion rolled back: the restricted digest is untouched and the summary wasn't flagged.
+ self.assertEqual(self._flagged_digest_ids(), [str(current.id)])
+
+ def test_alert_cannot_be_featured_digest(self) -> None:
+ payload = self._create_payload(
+ name="an-alert",
+ mode="alert",
+ alert_config={"frequency": "every_match", "metric": "count"},
+ selection={},
+ is_scanner_digest=True,
+ )
+ resp = self.client.post(self.actions_url, data=payload, format="json")
+ self.assertEqual(resp.status_code, 400, resp.content)
+ self.assertIn("summaries", resp.json()["detail"].lower())
def test_list(self) -> None:
self.client.post(self.actions_url, data=self._create_payload(), format="json")
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx
index a61b69586f00..cc9056007978 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx
@@ -7,6 +7,15 @@ import { LemonButton } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuGroup,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from 'lib/ui/quill'
import { urls } from 'scenes/urls'
import { getReplayVisionEditDisabledReason } from '../../utils/accessControl'
@@ -25,7 +34,7 @@ function CardShell({ children }: { children: React.ReactNode }): JSX.Element {
function CardHeader({ meta }: { meta?: React.ReactNode }): JSX.Element {
return (
<div className="flex items-baseline justify-between gap-2">
- <span className="text-sm font-medium">Daily digest</span>
+ <span className="text-sm font-medium">Featured digest</span>
{meta && <span className="text-xs text-muted">{meta}</span>}
</div>
)
@@ -46,12 +55,14 @@ export function ScannerDigestCard({
latestRun,
latestRunLoading,
digestCreating,
+ promotableSummaries,
+ promoting,
expanded,
visionActionsLoading,
runningNow,
runInProgress,
} = useValues(logic)
- const { createDigest, toggleExpanded, toggleActionEnabled, runNow } = useActions(logic)
+ const { createDigest, promoteDigest, toggleExpanded, toggleActionEnabled, runNow } = useActions(logic)
const { scanner } = useValues(replayScannerLogic({ id: scannerId }))
const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)
// Disable Run now while a run is actually processing (not just during the trigger request). A
@@ -70,17 +81,54 @@ export function ScannerDigestCard({
<span className="text-sm text-muted">
Get a daily AI summary of what this scanner finds, right here.
</span>
- <LemonButton
- type="primary"
- size="small"
- icon={<IconPlus />}
- onClick={createDigest}
- loading={digestCreating}
- disabledReason={editDisabledReason}
- data-attr="vision-scanner-digest-create"
- >
- Turn on daily digest
- </LemonButton>
+ {promotableSummaries.length > 0 ? (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconPlus />}
+ loading={digestCreating || promoting}
+ disabledReason={editDisabledReason}
+ data-attr="vision-scanner-digest-setup"
+ />
+ }
+ >
+ Set up digest
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="min-w-[220px]">
+ <DropdownMenuItem onClick={createDigest} data-attr="vision-scanner-digest-create">
+ Create a new daily digest
+ </DropdownMenuItem>
+ <DropdownMenuSeparator />
+ <DropdownMenuGroup>
+ <DropdownMenuLabel>Or feature an existing digest</DropdownMenuLabel>
+ {promotableSummaries.map((summary) => (
+ <DropdownMenuItem
+ key={summary.id}
+ onClick={() => promoteDigest(summary.id)}
+ data-attr="vision-scanner-digest-promote"
+ >
+ {summary.name}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ ) : (
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconPlus />}
+ onClick={createDigest}
+ loading={digestCreating}
+ disabledReason={editDisabledReason}
+ data-attr="vision-scanner-digest-create"
+ >
+ Turn on daily digest
+ </LemonButton>
+ )}
</div>
</CardShell>
)
@@ -91,7 +139,7 @@ export function ScannerDigestCard({
<CardShell>
<CardHeader />
<div className="flex flex-wrap items-center justify-between gap-2">
- <span className="text-sm text-muted">The daily digest is paused.</span>
+ <span className="text-sm text-muted">The featured digest is paused.</span>
<LemonButton
type="secondary"
size="small"
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
index 66d87d0b0226..959c578f6872 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
@@ -164,7 +164,7 @@ function VisionActionsTable({
>
{action.name}
</Link>
- {action.is_scanner_digest && <LemonTag type="highlight">Daily digest</LemonTag>}
+ {action.is_scanner_digest && <LemonTag type="highlight">Featured digest</LemonTag>}
{action.mode === 'alert' && <LemonTag type="warning">Alert</LemonTag>}
</span>
),
diff --git a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.test.ts
index 37f906139036..fbdf014fa0c0 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.test.ts
@@ -12,6 +12,7 @@ const DIGEST = {
scanner: 's1',
enabled: true,
is_scanner_digest: true,
+ mode: 'group_summary',
trigger_config: { rrule: 'FREQ=DAILY;BYHOUR=8;BYMINUTE=0', timezone: 'UTC' },
delivery_config: [],
} as unknown as VisionActionApi
@@ -22,10 +23,22 @@ const OTHER_SUMMARY = {
scanner: 's1',
enabled: true,
is_scanner_digest: false,
+ mode: 'group_summary',
trigger_config: { rrule: 'FREQ=DAILY' },
delivery_config: [],
} as unknown as VisionActionApi
+const ALERT = {
+ id: 'al1',
+ name: 'checkout alert',
+ scanner: 's1',
+ enabled: true,
+ is_scanner_digest: false,
+ mode: 'alert',
+ trigger_config: { rrule: 'FREQ=HOURLY' },
+ delivery_config: [],
+} as unknown as VisionActionApi
+
const RUNS = [
{ id: 'r-skip', status: 'skipped', scheduled_at: '2026-01-02T08:00:00Z', observation_count: 0 },
{ id: 'r-done', status: 'completed', scheduled_at: '2026-01-01T08:00:00Z', observation_count: 4 },
@@ -110,6 +123,35 @@ describe('scannerDigestLogic', () => {
expect(logic.values.latestRunLoading).toEqual(false)
})
+ it('offers only non-digest group summaries as promotion candidates', async () => {
+ // Alerts don't produce a renderable summary, and the current digest isn't its own candidate.
+ useMocks(mocksFor([DIGEST, OTHER_SUMMARY, ALERT]))
+ mountLogic()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.promotableSummaries.map((a) => a.id)).toEqual(['a1'])
+ })
+
+ it('promoteDigest flags the chosen summary and reloads the list', async () => {
+ useMocks(mocksFor([OTHER_SUMMARY]))
+ mountLogic()
+ await expectLogic(logic).toFinishAllListeners()
+ let body: any = null
+ useMocks({
+ patch: {
+ '/api/projects/:team/vision/actions/:action/': async ({ request }) => {
+ body = await request.json()
+ return [200, { ...OTHER_SUMMARY, is_scanner_digest: true }]
+ },
+ },
+ })
+ await expectLogic(logic, () => {
+ logic.actions.promoteDigest('a1')
+ })
+ .toDispatchActions(['promoteDigestSuccess', 'loadActions'])
+ .toFinishAllListeners()
+ expect(body).toEqual({ is_scanner_digest: true })
+ })
+
it('runNow posts to the digest run endpoint and clears its loading state', async () => {
useMocks(mocksFor([DIGEST]))
mountLogic()
diff --git a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts
index b18f7ceec050..90e38aaef62c 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts
@@ -5,6 +5,7 @@ import { teamLogic } from 'scenes/teamLogic'
import {
visionActionsCreate,
+ visionActionsPartialUpdate,
visionActionsRunCreate,
visionActionsRunsList,
visionActionsRunsRetrieve,
@@ -35,6 +36,8 @@ export interface scannerDigestLogicValues {
latestRun: VisionActionRunApi | null
latestRunLoading: boolean
pollUntil: number
+ promotableSummaries: VisionActionApi[]
+ promoting: boolean
runInProgress: boolean
runningNow: boolean
shouldPoll: boolean
@@ -72,6 +75,15 @@ export interface scannerDigestLogicActions {
loadLatestRunSuccess: (run: VisionActionRunApi | null) => {
run: VisionActionRunApi | null
}
+ promoteDigest: (actionId: string) => {
+ actionId: string
+ }
+ promoteDigestFailure: () => {
+ value: true
+ }
+ promoteDigestSuccess: () => {
+ value: true
+ }
runNow: () => {
value: true
}
@@ -91,6 +103,7 @@ export interface scannerDigestLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
digest: (visionActions: VisionActionApi[]) => VisionActionApi | null
+ promotableSummaries: (visionActions: VisionActionApi[]) => VisionActionApi[]
shouldPoll: (runInProgress: boolean, pollUntil: number) => boolean
}
}
@@ -122,6 +135,9 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
createDigest: true,
createDigestSuccess: true,
createDigestFailure: true,
+ promoteDigest: (actionId: string) => ({ actionId }),
+ promoteDigestSuccess: true,
+ promoteDigestFailure: true,
runNow: true,
runNowDone: true,
setRunInProgress: (inProgress: boolean) => ({ inProgress }),
@@ -152,6 +168,15 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
createDigestFailure: () => false,
},
],
+ // In-flight promotion of an existing summary into the featured slot; disables the dropdown.
+ promoting: [
+ false,
+ {
+ promoteDigest: () => true,
+ promoteDigestSuccess: () => false,
+ promoteDigestFailure: () => false,
+ },
+ ],
expanded: [
false,
{
@@ -189,6 +214,13 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
(visionActions: VisionActionApi[]): VisionActionApi | null =>
visionActions.find((a) => a.is_scanner_digest) ?? null,
],
+ // Summaries eligible to be promoted into the featured slot: scheduled group summaries that
+ // aren't already the digest (alerts don't produce a summary the card can render).
+ promotableSummaries: [
+ (s) => [s.visionActions],
+ (visionActions: VisionActionApi[]): VisionActionApi[] =>
+ visionActions.filter((a) => a.mode === 'group_summary' && !a.is_scanner_digest),
+ ],
shouldPoll: [
(s) => [s.runInProgress, s.pollUntil],
(runInProgress: boolean, pollUntil: number): boolean => shouldPollObservations(runInProgress, pollUntil),
@@ -271,6 +303,25 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
}
},
+ promoteDigest: async ({ actionId }) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.promoteDigestFailure()
+ return
+ }
+ try {
+ // Server atomically demotes the scanner's current digest (if any) before flagging this one.
+ await visionActionsPartialUpdate(String(teamId), actionId, { is_scanner_digest: true })
+ actions.promoteDigestSuccess()
+ lemonToast.success('Featured digest updated')
+ // Refetch rather than patch locally: promotion also demotes the previous digest row.
+ actions.loadActions()
+ } catch (error: any) {
+ actions.promoteDigestFailure()
+ lemonToast.error(`Couldn't update the featured digest${error?.detail ? `: ${error.detail}` : ''}`)
+ }
+ },
+
runNow: async () => {
const teamId = teamLogic.values.currentTeamId
const digest = values.digest