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): add create/edit form for vision actions (#65264)

Kim Svatos Duganfd5248437f63
diff --git a/products/replay_vision/backend/temporal/vision_actions/synthesis.py b/products/replay_vision/backend/temporal/vision_actions/synthesis.py
index e28b624c091f..23a9e1d7e2f2 100644
--- a/products/replay_vision/backend/temporal/vision_actions/synthesis.py
+++ b/products/replay_vision/backend/temporal/vision_actions/synthesis.py
@@ -21,7 +21,7 @@ from posthog.sync import database_sync_to_async
from products.replay_vision.backend.max_tools import _EVENT_ID_CITATION_RE, _as_untrusted_data
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ReplayObservation
from products.replay_vision.backend.models.replay_scanner import ScannerModel
-from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun
+from products.replay_vision.backend.models.vision_action import VisionAction, VisionActionRun, VisionActionRunStatus
from products.replay_vision.backend.temporal.constants import replay_vision_distinct_id
from products.replay_vision.backend.temporal.decorators import track_activity
from products.replay_vision.backend.temporal.gemini import gemini_api_key
@@ -89,7 +89,7 @@ def _synthesize(inputs: SynthesizeGroupSummaryInputs) -> SynthesizeGroupSummaryR
logger.info("vision_action.synthesis.over_credit_budget", vision_action_id=str(action.id))
return SynthesizeGroupSummaryResult(status=SynthesisStatus.SKIPPED_OVER_BUDGET)
- lines = _fetch_observation_lines(team, action)
+ lines = _fetch_observation_lines(team, action, run)
if not lines:
return SynthesizeGroupSummaryResult(status=SynthesisStatus.SKIPPED_EMPTY)
@@ -111,10 +111,42 @@ def _synthesize(inputs: SynthesizeGroupSummaryInputs) -> SynthesizeGroupSummaryR
return SynthesizeGroupSummaryResult(status=SynthesisStatus.SYNTHESIZED, observation_count=len(lines))
-def _fetch_observation_lines(team: Team, action: VisionAction) -> list[str]:
- """Fetch observations matching the action's `selection` and format them as untrusted-data lines.
+def _window_start(team: Team, action: VisionAction, run: VisionActionRun) -> datetime:
+ """Start of the observation window for this run: the previous successful run, else 24h back.
- Models the summarizer fetch in `max_tools._fetch_and_format`, applying the selection window.
+ Each run summarizes everything new since the last delivered summary, so the cadence itself defines
+ the period (a daily action covers ~a day, a weekly one ~a week) with no manual lookback. The first
+ run — or the first after a gap of failures — looks back 24h. Anchoring on the last *completed* run
+ (not merely the previous run) means a failed run's observations are picked up by the next success
+ rather than dropped.
+ """
+ previous_run_at = (
+ VisionActionRun.objects.for_team(team.id)
+ .filter(vision_action_id=action.id, status=VisionActionRunStatus.COMPLETED, scheduled_at__isnull=False)
+ .exclude(pk=run.pk)
+ .order_by("-scheduled_at")
+ .values_list("scheduled_at", flat=True)
+ .first()
+ )
+ return previous_run_at or (datetime.now(UTC) - timedelta(hours=24))
+
+
+def _window_end(run: VisionActionRun) -> datetime:
+ """End of the observation window for this run: its scheduled tick (exclusive).
+
+ The next run anchors its window_start on this run's scheduled_at, so capping the upper bound on
+ the same value makes consecutive windows tile exactly: an observation created after a run's
+ scheduled tick but before the run actually executes (the scheduling/queue lag) is deferred to the
+ next run instead of being summarized by both. Falls back to now() when scheduled_at is unset
+ (non-scheduled runs), preserving the previous open-ended upper bound.
+ """
+ return run.scheduled_at or datetime.now(UTC)
+
+
+def _fetch_observation_lines(team: Team, action: VisionAction, run: VisionActionRun) -> list[str]:
+ """Fetch the bound scanner's observations since the last run and format them as untrusted-data lines.
+
+ Models the summarizer fetch in `max_tools._fetch_and_format`.
"""
selection: dict[str, Any] = action.selection or {}
scanner_ids = selection.get("scanner_ids") or ([str(action.scanner_id)] if action.scanner_id else [])
@@ -122,13 +154,13 @@ def _fetch_observation_lines(team: Team, action: VisionAction) -> list[str]:
return []
observations_qs = ReplayObservation.objects.filter(
- team_id=team.id, scanner_id__in=scanner_ids, status=ObservationStatus.SUCCEEDED
+ team_id=team.id,
+ scanner_id__in=scanner_ids,
+ status=ObservationStatus.SUCCEEDED,
+ created_at__gte=_window_start(team, action, run),
+ created_at__lt=_window_end(run),
)
- window_days = selection.get("window_days")
- if isinstance(window_days, int) and window_days > 0:
- observations_qs = observations_qs.filter(created_at__gte=datetime.now(UTC) - timedelta(days=window_days))
-
rows = observations_qs.order_by("-created_at").values_list("scanner_result", "created_at")[:MAX_OBSERVATIONS]
lines: list[str] = []
diff --git a/products/replay_vision/backend/tests/test_vision_action_synthesis.py b/products/replay_vision/backend/tests/test_vision_action_synthesis.py
index 0b437a3eec61..1c8368b49e35 100644
--- a/products/replay_vision/backend/tests/test_vision_action_synthesis.py
+++ b/products/replay_vision/backend/tests/test_vision_action_synthesis.py
@@ -11,6 +11,7 @@ from parameterized import parameterized
from products.replay_vision.backend.models import ReplayObservation, ReplayScanner, VisionAction, VisionActionRun
from products.replay_vision.backend.models.replay_observation import ObservationStatus, ObservationTrigger
from products.replay_vision.backend.models.replay_scanner import ScannerModel, ScannerType
+from products.replay_vision.backend.models.vision_action import VisionActionRunStatus
from products.replay_vision.backend.temporal.vision_actions.synthesis import _markdown_to_slack, _synthesize
from products.replay_vision.backend.temporal.vision_actions.types import SynthesisStatus, SynthesizeGroupSummaryInputs
from products.replay_vision.backend.tests.helpers import snapshot_for
@@ -137,9 +138,10 @@ class TestVisionActionSynthesis(BaseTest):
def test_short_circuit_gates(self, gate: str, expected: SynthesisStatus) -> None:
# Each gate must return early without persisting markdown and without ever touching the LLM.
if gate == "empty_window":
+ # First run looks back 24h; a 10-day-old observation falls outside it.
obs = self._observation("old news")
ReplayObservation.objects.filter(pk=obs.pk).update(created_at=datetime.now(UTC) - timedelta(days=10))
- action = self._action(selection={"scanner_type": "summarizer", "window_days": 1})
+ action = self._action()
else:
self._observation("something")
action = self._action(created_by=None if gate == "no_creator" else self.user)
@@ -192,16 +194,67 @@ class TestVisionActionSynthesis(BaseTest):
self.assertNotIn("https://evil.example.com)", run.synthesized_markdown) # link target gone
self.assertIn("`https://evil.example.com`", run.synthesized_markdown) # bare url defanged
- def test_window_days_omitted_includes_all(self) -> None:
- obs = self._observation("ancient")
- ReplayObservation.objects.filter(pk=obs.pk).update(created_at=datetime.now(UTC) - timedelta(days=365))
- action = self._action(selection={}) # no window_days → no time filter
+ def test_first_run_looks_back_24h(self) -> None:
+ # No previous run → the window is the last 24h; anything older is excluded.
+ self._observation("today", session_id="recent")
+ old = self._observation("ancient", session_id="old")
+ ReplayObservation.objects.filter(pk=old.pk).update(created_at=datetime.now(UTC) - timedelta(days=2))
+ action = self._action()
+ run = self._run_for(action)
+
+ result = self._synthesize(action, run)
+ self.assertEqual(result.status, SynthesisStatus.SYNTHESIZED)
+ self.assertEqual(result.observation_count, 1) # only the recent observation
+
+ def test_window_starts_at_previous_completed_run(self) -> None:
+ # A prior completed run extends the window back to its scheduled_at, beyond the 24h default.
+ action = self._action()
+ previous = VisionActionRun(
+ vision_action=action,
+ team=self.team,
+ idempotency_key="prev",
+ status=VisionActionRunStatus.COMPLETED,
+ scheduled_at=datetime.now(UTC) - timedelta(days=3),
+ )
+ previous.save()
+ obs = self._observation("two days ago")
+ ReplayObservation.objects.filter(pk=obs.pk).update(created_at=datetime.now(UTC) - timedelta(days=2))
run = self._run_for(action)
result = self._synthesize(action, run)
self.assertEqual(result.status, SynthesisStatus.SYNTHESIZED)
self.assertEqual(result.observation_count, 1)
+ def test_window_excludes_observations_after_this_runs_scheduled_tick(self) -> None:
+ # The window is half-open [prev.scheduled_at, this.scheduled_at). An observation created after
+ # this run's scheduled tick (during the scheduling/execution lag) is deferred to the next run
+ # rather than summarized by both — guarding against double-counting across consecutive runs.
+ action = self._action()
+ previous = VisionActionRun(
+ vision_action=action,
+ team=self.team,
+ idempotency_key="prev",
+ status=VisionActionRunStatus.COMPLETED,
+ scheduled_at=datetime.now(UTC) - timedelta(days=2),
+ )
+ previous.save()
+ in_window = self._observation("inside the window", session_id="in")
+ ReplayObservation.objects.filter(pk=in_window.pk).update(created_at=datetime.now(UTC) - timedelta(hours=12))
+ after_tick = self._observation("created during execution lag", session_id="after")
+ ReplayObservation.objects.filter(pk=after_tick.pk).update(created_at=datetime.now(UTC))
+
+ run = VisionActionRun(
+ vision_action=action,
+ team=self.team,
+ idempotency_key="k1",
+ scheduled_at=datetime.now(UTC) - timedelta(hours=1),
+ )
+ run.save()
+
+ result = self._synthesize(action, run)
+ self.assertEqual(result.status, SynthesisStatus.SYNTHESIZED)
+ self.assertEqual(result.observation_count, 1) # only the in-window one; the post-tick one waits for next run
+
def test_prompt_guide_passed_to_llm(self) -> None:
self._observation("something")
action = self._action(synthesis_config={"prompt_guide": "focus on rage clicks"})
diff --git a/products/replay_vision/frontend/replay_scanners/cadence.test.ts b/products/replay_vision/frontend/replay_scanners/cadence.test.ts
new file mode 100644
index 000000000000..9a5631b9733d
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/cadence.test.ts
@@ -0,0 +1,62 @@
+import { CadenceState, cadenceToRrule, DEFAULT_CADENCE, humanizeCadence, parseRruleToCadence } from './cadence'
+
+describe('cadence', () => {
+ it('builds a daily rrule (all seven weekdays) with the time of day in BYHOUR/BYMINUTE', () => {
+ expect(cadenceToRrule({ weekdays: [0, 1, 2, 3, 4, 5, 6], hour: 9, minute: 0 })).toBe(
+ 'FREQ=DAILY;BYHOUR=9;BYMINUTE=0'
+ )
+ })
+
+ it('builds a weekly rrule with sorted BYDAY', () => {
+ expect(cadenceToRrule({ weekdays: [2, 0], hour: 14, minute: 30 })).toBe(
+ 'FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=14;BYMINUTE=30'
+ )
+ })
+
+ it('omits BYDAY when no weekdays are selected', () => {
+ expect(cadenceToRrule({ weekdays: [], hour: 8, minute: 0 })).toBe('FREQ=WEEKLY;BYHOUR=8;BYMINUTE=0')
+ })
+
+ it.each<[string, CadenceState]>([
+ ['daily (all seven)', { weekdays: [0, 1, 2, 3, 4, 5, 6], hour: 9, minute: 0 }],
+ ['weekly subset', { weekdays: [0, 2, 4], hour: 14, minute: 30 }],
+ ['single day', { weekdays: [6], hour: 23, minute: 59 }],
+ ])('round-trips %s', (_label, state) => {
+ expect(parseRruleToCadence(cadenceToRrule(state))).toEqual(state)
+ })
+
+ it('parses FREQ=DAILY back to all seven weekdays', () => {
+ expect(parseRruleToCadence('FREQ=DAILY;BYHOUR=9;BYMINUTE=0')).toEqual({
+ weekdays: [0, 1, 2, 3, 4, 5, 6],
+ hour: 9,
+ minute: 0,
+ })
+ })
+
+ it('normalizes legacy weekly-without-BYDAY to all seven weekdays', () => {
+ expect(parseRruleToCadence('FREQ=WEEKLY;BYHOUR=8;BYMINUTE=0')).toEqual({
+ weekdays: [0, 1, 2, 3, 4, 5, 6],
+ hour: 8,
+ minute: 0,
+ })
+ })
+
+ it('falls back to the default cadence on empty, monthly, or unrecognized rrule', () => {
+ expect(parseRruleToCadence(undefined)).toEqual(DEFAULT_CADENCE)
+ expect(parseRruleToCadence('')).toEqual(DEFAULT_CADENCE)
+ expect(parseRruleToCadence('FREQ=MONTHLY;BYHOUR=7;BYMINUTE=15')).toEqual(DEFAULT_CADENCE)
+ expect(parseRruleToCadence('FREQ=YEARLY;BYHOUR=9;BYMINUTE=0')).toEqual(DEFAULT_CADENCE)
+ })
+
+ it('clamps out-of-range time components back to the default', () => {
+ const parsed = parseRruleToCadence('FREQ=DAILY;BYHOUR=99;BYMINUTE=0')
+ expect(parsed.hour).toBe(DEFAULT_CADENCE.hour)
+ expect(parsed.minute).toBe(0)
+ })
+
+ it('humanizes the cadence from the selected weekdays', () => {
+ expect(humanizeCadence({ weekdays: [0, 1, 2, 3, 4, 5, 6], hour: 9, minute: 5 })).toBe('Daily at 09:05')
+ expect(humanizeCadence({ weekdays: [0, 2], hour: 14, minute: 0 })).toBe('Weekly on Mon, Wed at 14:00')
+ expect(humanizeCadence({ weekdays: [], hour: 8, minute: 0 })).toBe('Pick at least one day')
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/cadence.ts b/products/replay_vision/frontend/replay_scanners/cadence.ts
new file mode 100644
index 000000000000..80fa8854924d
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/cadence.ts
@@ -0,0 +1,110 @@
+// Cadence helpers for the vision-action create/edit form.
+//
+// Self-contained — we only need a set of weekdays + a time of day, not the full
+// recurring machinery (interval, monthly modes, end conditions) that the Workflows
+// RecurringSchedulePicker offers. The Workflows backend made the same copy-not-import
+// call for its rrule date math (see products/replay_vision/backend/rrule.py).
+//
+// The schedule is expressed as the days of the week it runs on: pick a subset for a
+// weekly cadence, or all seven for a daily one. There is no separate daily/weekly mode —
+// the frequency is implied by how many days are selected, and all seven normalizes to
+// FREQ=DAILY. At least one day must be selected (enforced by the form).
+//
+// The backend's trigger_config is only { rrule, timezone } with no DTSTART — the
+// scheduler derives starts_at from the action's created_at, so the run time of day must
+// live in the rrule itself via BYHOUR/BYMINUTE (dateutil honors those over the dtstart
+// time component).
+
+export interface CadenceState {
+ /** Days of week the action runs on. 0=Mon … 6=Sun. Must contain at least one; all seven = daily. */
+ weekdays: number[]
+ /** Hour of day, 0–23, in the action's timezone. */
+ hour: number
+ /** Minute of hour, 0–59. */
+ minute: number
+}
+
+// 0=Mon … 6=Sun, matching CadenceState.weekdays.
+const ALL_WEEKDAYS = [0, 1, 2, 3, 4, 5, 6]
+const RRULE_DAYS = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'] as const
+const WEEKDAY_SHORT = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'] as const
+
+export const DEFAULT_CADENCE: CadenceState = {
+ weekdays: [...ALL_WEEKDAYS],
+ hour: 9,
+ minute: 0,
+}
+
+function pad2(n: number): string {
+ return n.toString().padStart(2, '0')
+}
+
+function sortedWeekdays(weekdays: number[]): number[] {
+ return [...weekdays].sort((a, b) => a - b)
+}
+
+export function cadenceToRrule(state: CadenceState): string {
+ const isDaily = state.weekdays.length === 7
+ const parts = [`FREQ=${isDaily ? 'DAILY' : 'WEEKLY'}`]
+ if (!isDaily && state.weekdays.length > 0) {
+ parts.push(
+ `BYDAY=${sortedWeekdays(state.weekdays)
+ .map((d) => RRULE_DAYS[d])
+ .join(',')}`
+ )
+ }
+ parts.push(`BYHOUR=${state.hour}`, `BYMINUTE=${state.minute}`)
+ return parts.join(';')
+}
+
+function parseWeekdays(rrule: string): number[] {
+ const byday = /BYDAY=([A-Z,]+)/.exec(rrule)?.[1]
+ if (!byday) {
+ return []
+ }
+ return byday
+ .split(',')
+ .map((d) => RRULE_DAYS.indexOf(d.trim() as (typeof RRULE_DAYS)[number]))
+ .filter((i) => i >= 0)
+ .sort((a, b) => a - b)
+}
+
+function parseClampedInt(rrule: string, key: string, max: number, fallback: number): number {
+ const raw = new RegExp(`${key}=(\\d+)`).exec(rrule)?.[1]
+ if (raw === undefined) {
+ return fallback
+ }
+ const value = parseInt(raw, 10)
+ return Number.isNaN(value) || value < 0 || value > max ? fallback : value
+}
+
+export function parseRruleToCadence(rrule: string | undefined | null): CadenceState {
+ const freq = rrule ? /FREQ=([A-Z]+)/.exec(rrule)?.[1] : undefined
+ // Only DAILY/WEEKLY are produced by this form; anything else (legacy monthly, yearly,
+ // empty) falls back to the default daily cadence.
+ if (freq !== 'DAILY' && freq !== 'WEEKLY') {
+ return { ...DEFAULT_CADENCE }
+ }
+ const hour = parseClampedInt(rrule!, 'BYHOUR', 23, DEFAULT_CADENCE.hour)
+ const minute = parseClampedInt(rrule!, 'BYMINUTE', 59, DEFAULT_CADENCE.minute)
+ if (freq === 'DAILY') {
+ return { weekdays: [...ALL_WEEKDAYS], hour, minute }
+ }
+ // Weekly with no BYDAY is a legacy "every day" — normalize to all seven.
+ const weekdays = parseWeekdays(rrule!)
+ return { weekdays: weekdays.length > 0 ? weekdays : [...ALL_WEEKDAYS], hour, minute }
+}
+
+export function humanizeCadence(state: CadenceState): string {
+ const time = `${pad2(state.hour)}:${pad2(state.minute)}`
+ if (state.weekdays.length === 0) {
+ return 'Pick at least one day'
+ }
+ if (state.weekdays.length === 7) {
+ return `Daily at ${time}`
+ }
+ const days = sortedWeekdays(state.weekdays)
+ .map((d) => WEEKDAY_SHORT[d])
+ .join(', ')
+ return `Weekly on ${days} at ${time}`
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsx
new file mode 100644
index 000000000000..44ed357d82d3
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionForm.tsx
@@ -0,0 +1,227 @@
+import { useActions, useValues } from 'kea'
+import { Form } from 'kea-forms'
+import { useMemo } from 'react'
+
+import { LemonButton, LemonInput, LemonModal } from '@posthog/lemon-ui'
+
+import { IntegrationChoice } from 'lib/components/CyclotronJob/integrations/IntegrationChoice'
+import { integrationsLogic } from 'lib/integrations/integrationsLogic'
+import { SlackChannelPicker, SlackNotConfiguredBanner } from 'lib/integrations/SlackIntegrationHelpers'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+import { LemonSearchableSelect } from 'lib/lemon-ui/LemonSelect/LemonSearchableSelect'
+import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea/LemonTextArea'
+import { timeZoneLabel } from 'lib/utils/timezones'
+import { preflightLogic } from 'scenes/PreflightCheck/preflightLogic'
+
+import { DEFAULT_CADENCE, humanizeCadence } from '../cadence'
+import { visionActionsLogic } from '../visionActionsLogic'
+
+// 0=Mon … 6=Sun, matching CadenceState.weekdays.
+const WEEKDAY_PILLS = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su']
+const ALL_WEEKDAYS = [0, 1, 2, 3, 4, 5, 6]
+const WEEKDAYS_MON_FRI = [0, 1, 2, 3, 4]
+
+function TimezoneSelect({ value, onChange }: { value: string; onChange: (tz: string) => void }): JSX.Element {
+ const { preflight } = useValues(preflightLogic)
+ const options = useMemo(
+ () =>
+ Object.entries(preflight?.available_timezones || {}).map(([tz, offset]) => ({
+ value: tz,
+ label: timeZoneLabel(tz, offset),
+ })),
+ [preflight?.available_timezones]
+ )
+ return (
+ <LemonSearchableSelect
+ value={value}
+ options={options}
+ onChange={(val) => val && onChange(val)}
+ placeholder="Select a timezone"
+ fullWidth
+ />
+ )
+}
+
+function ScheduleSection(): JSX.Element {
+ const { visionActionForm } = useValues(visionActionsLogic)
+ const { setVisionActionFormValue } = useActions(visionActionsLogic)
+ const { cadence, timezone } = visionActionForm
+
+ const timeValue = `${cadence.hour.toString().padStart(2, '0')}:${cadence.minute.toString().padStart(2, '0')}`
+
+ const setWeekdays = (weekdays: number[]): void => setVisionActionFormValue('cadence', { ...cadence, weekdays })
+
+ const toggleWeekday = (day: number): void =>
+ setWeekdays(
+ cadence.weekdays.includes(day) ? cadence.weekdays.filter((d) => d !== day) : [...cadence.weekdays, day]
+ )
+
+ const noDays = cadence.weekdays.length === 0
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div>
+ <div className="flex items-center justify-between">
+ <label className="text-sm font-semibold">Runs on</label>
+ <div className="flex gap-1">
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={() => setWeekdays([...ALL_WEEKDAYS])}
+ data-attr="vision-action-cadence-everyday"
+ >
+ Every day
+ </LemonButton>
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={() => setWeekdays([...WEEKDAYS_MON_FRI])}
+ data-attr="vision-action-cadence-weekdays"
+ >
+ Weekdays
+ </LemonButton>
+ </div>
+ </div>
+ <div className="flex gap-1">
+ {WEEKDAY_PILLS.map((label, day) => (
+ <LemonButton
+ key={day}
+ size="small"
+ type={cadence.weekdays.includes(day) ? 'primary' : 'secondary'}
+ onClick={() => toggleWeekday(day)}
+ data-attr={`vision-action-cadence-day-${day}`}
+ >
+ {label}
+ </LemonButton>
+ ))}
+ </div>
+ {noDays && <span className="text-xs text-danger">Pick at least one day</span>}
+ </div>
+
+ <div className="w-32">
+ <label className="text-sm font-semibold">At</label>
+ <LemonInput
+ type="time"
+ value={timeValue}
+ onChange={(val) => {
+ const [h, m] = (val || '').split(':').map((n) => parseInt(n, 10))
+ // isFinite (not isNaN) so a cleared/partial input — where h or m is `undefined`,
+ // which isNaN() does not catch — falls back to the default rather than undefined.
+ setVisionActionFormValue('cadence', {
+ ...cadence,
+ hour: Number.isFinite(h) ? h : DEFAULT_CADENCE.hour,
+ minute: Number.isFinite(m) ? m : DEFAULT_CADENCE.minute,
+ })
+ }}
+ />
+ </div>
+
+ <div>
+ <label className="text-sm font-semibold">Timezone</label>
+ <TimezoneSelect value={timezone} onChange={(tz) => setVisionActionFormValue('timezone', tz)} />
+ </div>
+
+ <span className="text-xs text-muted">{humanizeCadence(cadence)}</span>
+ </div>
+ )
+}
+
+function DeliverySection(): JSX.Element {
+ const { visionActionForm } = useValues(visionActionsLogic)
+ const { setVisionActionFormValue } = useActions(visionActionsLogic)
+ const { slackIntegrations } = useValues(integrationsLogic)
+ const { integration_id } = visionActionForm
+
+ if (!slackIntegrations?.length) {
+ return <SlackNotConfiguredBanner />
+ }
+
+ const selectedIntegration = slackIntegrations.find((i) => i.id === integration_id)
+
+ return (
+ <div className="flex flex-col gap-2">
+ <IntegrationChoice
+ integration="slack"
+ value={integration_id ?? undefined}
+ onChange={(value) => {
+ setVisionActionFormValue('integration_id', value)
+ setVisionActionFormValue('channel', '')
+ }}
+ />
+ {selectedIntegration && (
+ <LemonField name="channel" label="Channel">
+ {({ value, onChange }) => (
+ <SlackChannelPicker
+ integration={selectedIntegration}
+ value={value}
+ onChange={(next) => onChange(next ?? '')}
+ />
+ )}
+ </LemonField>
+ )}
+ </div>
+ )
+}
+
+export function VisionActionForm({ scannerId }: { scannerId: string }): JSX.Element {
+ const { formVisible, editingAction, isVisionActionFormSubmitting, visionActionForm } = useValues(visionActionsLogic)
+ const { closeForm } = useActions(visionActionsLogic)
+
+ const noDays = visionActionForm.cadence.weekdays.length === 0
+
+ return (
+ <LemonModal
+ isOpen={formVisible}
+ onClose={closeForm}
+ width={640}
+ title={editingAction ? 'Edit action' : 'New action'}
+ description="Schedule an AI summary of this scanner's observations and deliver it to Slack."
+ footer={
+ <div className="flex gap-2 justify-end">
+ <LemonButton type="secondary" onClick={closeForm}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ htmlType="submit"
+ form="vision-action-form"
+ loading={isVisionActionFormSubmitting}
+ disabledReason={noDays ? 'Pick at least one day to run on' : undefined}
+ >
+ {editingAction ? 'Save' : 'Create action'}
+ </LemonButton>
+ </div>
+ }
+ >
+ <Form
+ logic={visionActionsLogic}
+ props={{ scannerId }}
+ formKey="visionActionForm"
+ id="vision-action-form"
+ enableFormOnSubmit
+ className="flex flex-col gap-4"
+ >
+ <LemonField name="name" label="Name">
+ <LemonInput placeholder="Daily checkout summary" autoFocus />
+ </LemonField>
+
+ <div>
+ <h4 className="mb-1">Schedule</h4>
+ <ScheduleSection />
+ </div>
+
+ <LemonField name="prompt_guide" label="Guidance" info="Optional. Steers how the AI writes the summary.">
+ <LemonTextArea
+ placeholder="Optional. e.g. focus on issues, bugs, and friction users face — or focus on general user behavior and flows."
+ maxLength={500}
+ />
+ </LemonField>
+
+ <div>
+ <h4 className="mb-1">Deliver to Slack</h4>
+ <DeliverySection />
+ </div>
+ </Form>
+ </LemonModal>
+ )
+}
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
index f586dd188bed..997f4212602d 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
@@ -1,6 +1,6 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { IconPlus, IconTrash } from '@posthog/icons'
+import { IconPencil, IconPlus, IconTrash } from '@posthog/icons'
import { LemonButton, LemonSwitch, LemonTable } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
@@ -13,24 +13,35 @@ import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import type { VisionActionApi } from '../../generated/api.schemas'
+import { humanizeCadence, parseRruleToCadence } from '../cadence'
import { visionActionsLogic } from '../visionActionsLogic'
-
-const FREQ_LABELS: Record<string, string> = {
- HOURLY: 'Hourly',
- DAILY: 'Daily',
- WEEKLY: 'Weekly',
- MONTHLY: 'Monthly',
- YEARLY: 'Yearly',
-}
+import { VisionActionForm } from './VisionActionForm'
function humanizeSchedule(action: VisionActionApi): string {
const rrule = action.trigger_config?.rrule
if (!rrule) {
return '—'
}
- // Light-touch label for the common case; the full cadence editor lands with the create form (PR6).
+ // parseRruleToCadence only understands DAILY/WEEKLY; for anything else (a legacy monthly/hourly
+ // rrule) it falls back to the default daily cadence, which would mislabel the schedule — show the
+ // raw rrule instead of a fabricated "Daily".
const freq = /FREQ=([A-Z]+)/.exec(rrule)?.[1]
- return (freq && FREQ_LABELS[freq]) || rrule
+ if (freq !== 'DAILY' && freq !== 'WEEKLY') {
+ return rrule
+ }
+ return humanizeCadence(parseRruleToCadence(rrule))
+}
+
+// Every write control on this tab gates on the same session-recording Editor access — wrap once.
+function EditorGate({ children }: { children: JSX.Element }): JSX.Element {
+ return (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.SessionRecording}
+ minAccessLevel={AccessControlLevel.Editor}
+ >
+ {children}
+ </AccessControlAction>
+ )
}
function deliverySummary(action: VisionActionApi): string {
@@ -42,13 +53,14 @@ export function VisionActionsTab({ scannerId }: { scannerId: string }): JSX.Elem
return (
<BindLogic logic={visionActionsLogic} props={{ scannerId }}>
<VisionActionsTable />
+ <VisionActionForm scannerId={scannerId} />
</BindLogic>
)
}
function VisionActionsTable(): JSX.Element {
const { visionActions, visionActionsLoading, togglingIds } = useValues(visionActionsLogic)
- const { toggleActionEnabled, deleteAction } = useActions(visionActionsLogic)
+ const { toggleActionEnabled, deleteAction, openCreateForm, openEditForm } = useActions(visionActionsLogic)
if (!visionActionsLoading && visionActions.length === 0) {
return (
@@ -59,14 +71,16 @@ function VisionActionsTable(): JSX.Element {
customHog={XRayHog}
description="Set up scheduled summaries of this scanner's observations — synthesized by AI and delivered to Slack on the cadence you choose. Great for a daily digest of what the scanner has been finding."
actionElementOverride={
- <LemonButton
- type="primary"
- icon={<IconPlus />}
- disabledReason="Action creation is coming soon"
- data-attr="vision-action-new-empty"
- >
- New action
- </LemonButton>
+ <EditorGate>
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={() => openCreateForm()}
+ data-attr="vision-action-new-empty"
+ >
+ New action
+ </LemonButton>
+ </EditorGate>
}
/>
)
@@ -93,10 +107,7 @@ function VisionActionsTable(): JSX.Element {
key: 'enabled',
render: (_, action) => (
<div className="flex items-center gap-2">
- <AccessControlAction
- resourceType={AccessControlResourceType.SessionRecording}
- minAccessLevel={AccessControlLevel.Editor}
- >
+ <EditorGate>
<LemonSwitch
checked={!!action.enabled}
onChange={() => toggleActionEnabled(action.id)}
@@ -104,7 +115,7 @@ function VisionActionsTable(): JSX.Element {
size="small"
data-attr="vision-action-toggle-enabled"
/>
- </AccessControlAction>
+ </EditorGate>
<span className={`inline-block min-w-[4.5rem] ${action.enabled ? 'text-success' : 'text-muted'}`}>
{action.enabled ? 'Enabled' : 'Disabled'}
</span>
@@ -130,47 +141,71 @@ function VisionActionsTable(): JSX.Element {
),
},
{
- title: '',
+ title: 'Actions',
key: 'actions',
+ width: 0, // shrink to content so the buttons hug the right instead of floating in a wide column
render: (_, action) => (
- <AccessControlAction
- resourceType={AccessControlResourceType.SessionRecording}
- minAccessLevel={AccessControlLevel.Editor}
- >
- <LemonButton
- size="small"
- type="secondary"
- status="danger"
- icon={<IconTrash />}
- tooltip="Delete"
- data-attr="vision-action-delete"
- onClick={() =>
- LemonDialog.open({
- title: `Delete "${action.name}"?`,
- description:
- 'This stops its scheduled summaries and removes its delivery destinations. This cannot be undone.',
- primaryButton: {
- children: 'Delete',
- status: 'danger',
- onClick: () => deleteAction(action.id),
- },
- secondaryButton: { children: 'Cancel' },
- })
- }
- />
- </AccessControlAction>
+ <div className="flex gap-1">
+ <EditorGate>
+ <LemonButton
+ size="small"
+ type="secondary"
+ icon={<IconPencil />}
+ tooltip="Edit"
+ data-attr="vision-action-edit"
+ onClick={() => openEditForm(action)}
+ />
+ </EditorGate>
+ <EditorGate>
+ <LemonButton
+ size="small"
+ type="secondary"
+ status="danger"
+ icon={<IconTrash />}
+ tooltip="Delete"
+ data-attr="vision-action-delete"
+ onClick={() =>
+ LemonDialog.open({
+ title: `Delete "${action.name}"?`,
+ description:
+ 'This stops its scheduled summaries and removes its delivery destinations. This cannot be undone.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deleteAction(action.id),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }
+ />
+ </EditorGate>
+ </div>
),
},
]
return (
- <LemonTable
- columns={columns}
- dataSource={visionActions}
- loading={visionActionsLoading}
- rowKey="id"
- data-attr="vision-actions-table"
- emptyState="No actions yet — this scanner has no scheduled summaries."
- />
+ <div className="flex flex-col gap-2">
+ <div className="flex justify-end">
+ <EditorGate>
+ <LemonButton
+ type="primary"
+ icon={<IconPlus />}
+ onClick={() => openCreateForm()}
+ data-attr="vision-action-new"
+ >
+ New action
+ </LemonButton>
+ </EditorGate>
+ </div>
+ <LemonTable
+ columns={columns}
+ dataSource={visionActions}
+ loading={visionActionsLoading}
+ rowKey="id"
+ data-attr="vision-actions-table"
+ emptyState="No actions yet — this scanner has no scheduled summaries."
+ />
+ </div>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts
index a301ae3b549c..38be20140667 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.test.ts
@@ -1,10 +1,13 @@
import { expectLogic } from 'kea-test-utils'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import type { VisionActionApi } from '../generated/api.schemas'
-import { visionActionsLogic } from './visionActionsLogic'
+import { DeliveryTargetTypeEnumApi } from '../generated/api.schemas'
+import { buildActionBody, type VisionActionForm, visionActionsLogic } from './visionActionsLogic'
const action = (id: string, enabled = true): VisionActionApi => ({
id,
@@ -29,6 +32,9 @@ describe('visionActionsLogic', () => {
get: {
'/api/projects/:team/vision/actions/': { results: [action('a'), action('b')], count: 2 },
},
+ post: {
+ '/api/projects/:team/vision/actions/': () => [201, action('new')],
+ },
patch: {
'/api/projects/:team/vision/actions/:id/': () => [200, {}],
},
@@ -83,4 +89,85 @@ describe('visionActionsLogic', () => {
visionActions: [expect.objectContaining({ id: 'b' })],
})
})
+
+ it('creating an action submits, closes the form, and reloads', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.openCreateForm()
+ logic.actions.setVisionActionFormValue('name', 'My action')
+ logic.actions.submitVisionActionForm()
+ })
+ .toDispatchActions(['submitVisionActionFormSuccess', 'closeForm', 'loadActions'])
+ .toMatchValues({ formVisible: false })
+ })
+
+ it('openEditForm prefills the form from an existing action', async () => {
+ const existing: VisionActionApi = {
+ ...action('e'),
+ trigger_config: { rrule: 'FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=14;BYMINUTE=30', timezone: 'Europe/Prague' },
+ synthesis_config: { prompt_guide: 'focus on checkout' },
+ delivery_config: [{ type: 'slack', integration_id: 5, channel: 'C123' }],
+ }
+ await expectLogic(logic, () => {
+ logic.actions.openEditForm(existing)
+ }).toMatchValues({
+ formVisible: true,
+ editingAction: expect.objectContaining({ id: 'e' }),
+ visionActionForm: {
+ name: 'action-e',
+ cadence: { weekdays: [0, 2], hour: 14, minute: 30 },
+ timezone: 'Europe/Prague',
+ prompt_guide: 'focus on checkout',
+ integration_id: 5,
+ channel: 'C123',
+ },
+ })
+ })
+
+ it('keeps the form open and surfaces the API error detail when the submit fails', async () => {
+ useMocks({
+ post: {
+ '/api/projects/:team/vision/actions/': () => [400, { detail: 'nope' }],
+ },
+ })
+ const errorToast = jest.spyOn(lemonToast, 'error')
+ await expectLogic(logic, () => {
+ logic.actions.openCreateForm()
+ logic.actions.setVisionActionFormValue('name', 'My action')
+ logic.actions.submitVisionActionForm()
+ })
+ .toDispatchActions(['submitVisionActionFormFailure'])
+ .toMatchValues({ formVisible: true })
+ // The toast must surface the API's `detail` so the user sees why it failed, not a generic message.
+ expect(errorToast).toHaveBeenCalledWith(expect.stringContaining('nope'))
+ })
+
+ it('buildActionBody maps the form to the API body, including a Slack delivery target', () => {
+ const form: VisionActionForm = {
+ name: ' Daily digest ',
+ cadence: { weekdays: [0, 2], hour: 14, minute: 30 },
+ timezone: 'Europe/Prague',
+ prompt_guide: 'focus on checkout',
+ integration_id: 5,
+ channel: 'C123|#general',
+ }
+ expect(buildActionBody(form, 's1')).toEqual({
+ name: 'Daily digest', // trimmed
+ scanner: 's1',
+ trigger_config: { rrule: 'FREQ=WEEKLY;BYDAY=MO,WE;BYHOUR=14;BYMINUTE=30', timezone: 'Europe/Prague' },
+ synthesis_config: { prompt_guide: 'focus on checkout' },
+ delivery_config: [{ type: DeliveryTargetTypeEnumApi.Slack, integration_id: 5, channel: 'C123' }],
+ })
+ })
+
+ it('buildActionBody emits an empty delivery_config when no integration/channel is set', () => {
+ const form: VisionActionForm = {
+ name: 'No delivery',
+ cadence: { weekdays: [0, 1, 2, 3, 4, 5, 6], hour: 9, minute: 0 },
+ timezone: 'UTC',
+ prompt_guide: '',
+ integration_id: null,
+ channel: '',
+ }
+ expect(buildActionBody(form, 's1').delivery_config).toEqual([])
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts
index 212acf70f212..a091fa9a0d4d 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionsLogic.ts
@@ -1,16 +1,67 @@
import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { forms } from 'kea-forms'
+import { dayjs } from 'lib/dayjs'
+import { slackChannelId } from 'lib/integrations/slackChannel'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { visionActionsDestroy, visionActionsList, visionActionsPartialUpdate } from '../generated/api'
+import {
+ visionActionsCreate,
+ visionActionsDestroy,
+ visionActionsList,
+ visionActionsPartialUpdate,
+} from '../generated/api'
+import { DeliveryTargetTypeEnumApi } from '../generated/api.schemas'
import type { VisionActionApi } from '../generated/api.schemas'
+import { CadenceState, cadenceToRrule, DEFAULT_CADENCE, parseRruleToCadence } from './cadence'
import type { visionActionsLogicType } from './visionActionsLogicType'
export interface VisionActionsLogicProps {
scannerId: string
}
+// UI-shaped form values, mapped to/from the API shape on submit/edit.
+export interface VisionActionForm {
+ name: string
+ cadence: CadenceState
+ timezone: string
+ prompt_guide: string
+ integration_id: number | null
+ channel: string
+}
+
+const NEW_ACTION_FORM = (): VisionActionForm => ({
+ name: '',
+ cadence: { ...DEFAULT_CADENCE },
+ timezone: dayjs.tz.guess(),
+ prompt_guide: '',
+ integration_id: null,
+ channel: '',
+})
+
+// Map the UI form shape to the API body shared by create + partial-update. Kept standalone so the
+// rrule + delivery-target mapping (the part most likely to grow beyond a single Slack target) is
+// unit-testable without the form machinery.
+export function buildActionBody(form: VisionActionForm, scannerId: string): Parameters<typeof visionActionsCreate>[1] {
+ return {
+ name: form.name.trim(),
+ scanner: scannerId,
+ trigger_config: { rrule: cadenceToRrule(form.cadence), timezone: form.timezone },
+ synthesis_config: { prompt_guide: form.prompt_guide },
+ delivery_config:
+ form.integration_id && form.channel
+ ? [
+ {
+ type: DeliveryTargetTypeEnumApi.Slack,
+ integration_id: form.integration_id,
+ channel: slackChannelId(form.channel),
+ },
+ ]
+ : [],
+ }
+}
+
export const visionActionsLogic = kea<visionActionsLogicType>([
path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'visionActionsLogic']),
props({} as VisionActionsLogicProps),
@@ -25,6 +76,9 @@ export const visionActionsLogic = kea<visionActionsLogicType>([
toggleActionEnabledDone: (id: string) => ({ id }),
deleteAction: (id: string) => ({ id }),
deleteActionSuccess: (id: string) => ({ id }),
+ openCreateForm: true,
+ openEditForm: (action: VisionActionApi) => ({ action }),
+ closeForm: true,
}),
reducers({
@@ -56,8 +110,52 @@ export const visionActionsLogic = kea<visionActionsLogicType>([
revertActionEnabled: (state, { id }) => state.filter((i) => i !== id),
},
],
+ formVisible: [
+ false,
+ {
+ openCreateForm: () => true,
+ openEditForm: () => true,
+ closeForm: () => false,
+ },
+ ],
+ editingAction: [
+ null as VisionActionApi | null,
+ {
+ openCreateForm: () => null,
+ openEditForm: (_, { action }) => action,
+ closeForm: () => null,
+ },
+ ],
}),
+ forms(({ props, values }) => ({
+ visionActionForm: {
+ defaults: NEW_ACTION_FORM(),
+ errors: ({ name, cadence, integration_id, channel }) => ({
+ name: !name?.trim() ? 'Give this action a name' : undefined,
+ // weekdays is a number[], which kea-forms can't carry a string error on, so we hang
+ // the "pick a day" error on the cadence object via `hour` to mark the form invalid.
+ // This blocks Enter-to-submit (enableFormOnSubmit); the user-facing message is the
+ // inline danger text + the submit button's disabledReason.
+ cadence: cadence.weekdays.length === 0 ? { hour: 'Pick at least one day' } : undefined,
+ channel: integration_id && !channel ? 'Pick a channel' : undefined,
+ }),
+ submit: async (form) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ throw new Error('No team selected')
+ }
+ const body = buildActionBody(form, props.scannerId)
+ const editing = values.editingAction
+ if (editing) {
+ await visionActionsPartialUpdate(String(teamId), editing.id, body)
+ } else {
+ await visionActionsCreate(String(teamId), body)
+ }
+ },
+ },
+ })),
+
listeners(({ actions, props, values }) => ({
loadActions: async () => {
const teamId = teamLogic.values.currentTeamId
@@ -104,6 +202,35 @@ export const visionActionsLogic = kea<visionActionsLogicType>([
lemonToast.error(`Failed to delete action${error.detail ? `: ${error.detail}` : ''}`)
}
},
+
+ openCreateForm: () => {
+ actions.resetVisionActionForm(NEW_ACTION_FORM())
+ },
+
+ openEditForm: ({ action }) => {
+ actions.setVisionActionFormValues({
+ name: action.name,
+ cadence: parseRruleToCadence(action.trigger_config?.rrule),
+ timezone: action.trigger_config?.timezone || dayjs.tz.guess(),
+ prompt_guide: action.synthesis_config?.prompt_guide ?? '',
+ integration_id: action.delivery_config?.[0]?.integration_id ?? null,
+ channel: action.delivery_config?.[0]?.channel ?? '',
+ })
+ },
+
+ closeForm: () => {
+ actions.resetVisionActionForm(NEW_ACTION_FORM())
+ },
+
+ submitVisionActionFormSuccess: () => {
+ lemonToast.success(values.editingAction ? 'Action updated' : 'Action created')
+ actions.closeForm()
+ actions.loadActions()
+ },
+
+ submitVisionActionFormFailure: ({ error }: { error?: Error & { detail?: string } }) => {
+ lemonToast.error(`Failed to save action${error?.detail ? `: ${error.detail}` : ''}`)
+ },
})),
afterMount(({ actions }) => {