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): show and run the daily digest on demand (#73062)

Kim Svatos Dugan9b9e64731e49
diff --git a/products/replay_vision/backend/api/trigger.py b/products/replay_vision/backend/api/trigger.py
index ea9ea3c0ec6e..7c414d894829 100644
--- a/products/replay_vision/backend/api/trigger.py
+++ b/products/replay_vision/backend/api/trigger.py
@@ -1,6 +1,7 @@
"""Shared Temporal trigger for on-demand scanner applications (observe and retry)."""
import enum
+from datetime import datetime
from uuid import UUID
from django.conf import settings
@@ -26,7 +27,10 @@ from products.replay_vision.backend.temporal.constants import (
APPLY_SCANNER_EXECUTION_TIMEOUT,
APPLY_SCANNER_WORKFLOW_NAME,
MAX_IN_FLIGHT_APPLIES_PER_TEAM,
+ PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
+ PROCESS_VISION_ACTION_WORKFLOW_NAME,
build_apply_scanner_workflow_id,
+ build_process_vision_action_workflow_id,
)
from products.replay_vision.backend.temporal.types import ApplyScannerInputs
@@ -105,3 +109,48 @@ def start_apply_scanner_workflow(
logger.exception("replay_vision.observe.workflow_start_failed", workflow_id=workflow_id)
return workflow_id, WorkflowStartOutcome.FAILED
return workflow_id, WorkflowStartOutcome.STARTED
+
+
+def start_process_vision_action_workflow(
+ vision_action_id: UUID,
+ team_id: int,
+ *,
+ scheduled_at: datetime,
+) -> tuple[str, WorkflowStartOutcome]:
+ """Start the per-action processing workflow on demand ("Run now"); never raises.
+
+ Reuses the same deterministic workflow id as the scheduled sweep, so a manual run coalesces with
+ an already-running run (scheduled or manual) rather than double-charging — ALREADY_RUNNING is
+ returned in that case. The workflow never advances next_run_at, so the recurring schedule is
+ untouched; passing scheduled_at=now just anchors this run's observation window at the present.
+ """
+ # Deferred: importing this triggers the vision_actions package __init__, which pulls the whole
+ # engine (workflows + activities + LLM clients). Keep that off the API module-load path — only
+ # the web process, only when Run now is actually invoked, pays for it.
+ from products.replay_vision.backend.temporal.vision_actions.types import ProcessVisionActionInputs # noqa: PLC0415
+
+ workflow_id = build_process_vision_action_workflow_id(vision_action_id)
+ try:
+ client = sync_connect()
+ async_to_sync(client.start_workflow)( # type: ignore[misc]
+ PROCESS_VISION_ACTION_WORKFLOW_NAME, # type: ignore[arg-type]
+ ProcessVisionActionInputs( # type: ignore[arg-type]
+ vision_action_id=vision_action_id,
+ team_id=team_id,
+ scheduled_at=scheduled_at,
+ mode="group_summary",
+ ),
+ id=workflow_id,
+ task_queue=settings.REPLAY_VISION_TASK_QUEUE,
+ execution_timeout=PROCESS_VISION_ACTION_EXECUTION_TIMEOUT,
+ )
+ except WorkflowAlreadyStartedError as exc:
+ if exc.workflow_id != workflow_id:
+ logger.exception("replay_vision.run_now.workflow_id_mismatch", workflow_id=workflow_id)
+ return workflow_id, WorkflowStartOutcome.FAILED
+ logger.info("replay_vision.run_now.workflow_already_started", workflow_id=workflow_id)
+ return workflow_id, WorkflowStartOutcome.ALREADY_RUNNING
+ except Exception:
+ logger.exception("replay_vision.run_now.workflow_start_failed", workflow_id=workflow_id)
+ return workflow_id, WorkflowStartOutcome.FAILED
+ return workflow_id, WorkflowStartOutcome.STARTED
diff --git a/products/replay_vision/backend/api/vision_actions.py b/products/replay_vision/backend/api/vision_actions.py
index a844cc75ce2c..2d38006506f2 100644
--- a/products/replay_vision/backend/api/vision_actions.py
+++ b/products/replay_vision/backend/api/vision_actions.py
@@ -4,12 +4,14 @@ from typing import Any, NoReturn, cast, get_args
from django.db import IntegrityError, transaction
from django.db.models import QuerySet
from django.shortcuts import get_object_or_404
+from django.utils import timezone
import structlog
from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import OpenApiParameter, extend_schema, extend_schema_field, extend_schema_view
-from rest_framework import mixins, serializers, viewsets
-from rest_framework.exceptions import NotFound, PermissionDenied
+from rest_framework import mixins, serializers, status, viewsets
+from rest_framework.decorators import action
+from rest_framework.exceptions import NotFound, PermissionDenied, ValidationError
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework.serializers import BaseSerializer
@@ -21,6 +23,7 @@ from posthog.models.integration import Integration
from posthog.models.user import User
from products.replay_vision.backend.api.delivery import archive_delivery, provision_delivery
+from products.replay_vision.backend.api.trigger import WorkflowStartOutcome, start_process_vision_action_workflow
from products.replay_vision.backend.feature_flag import (
ReplayVisionActionsEnabledPermission,
ReplayVisionEnabledPermission,
@@ -482,6 +485,20 @@ def _check_action_scanner_access(
raise PermissionDenied("You don't have access to one or more scanners this action targets.")
+class RunActionResponseSerializer(serializers.Serializer):
+ """Async-accepted response for POST /vision/actions/{id}/run/."""
+
+ workflow_id = serializers.CharField(
+ help_text="Temporal workflow id for the run; the resulting run appears under the action's run history."
+ )
+ already_running = serializers.BooleanField(
+ help_text=(
+ "True when a run for this action was already in progress (scheduled or manual), so this "
+ "request coalesced onto it rather than starting a second run."
+ )
+ )
+
+
@extend_schema_view(
list=extend_schema(
parameters=[
@@ -601,6 +618,42 @@ class VisionActionViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
archive_delivery(instance, team=self.team)
super().perform_destroy(instance)
+ @extend_schema(request=None, responses={202: RunActionResponseSerializer})
+ @action(
+ detail=True,
+ methods=["post"],
+ url_path="run",
+ required_scopes=["vision_action:write", "session_recording:read"],
+ )
+ def run(self, request: Request, **kwargs: Any) -> Response:
+ """Run this summary now, without waiting for its schedule — synthesizes a group summary over the
+ observations since the last summary (or the last 24h). The recurring schedule is untouched: the
+ engine advances next_run_at only at scheduled claim time, never in the run itself."""
+ # get_object() runs safely_get_object, which object-checks the bound scanner's access.
+ action_obj = self.get_object()
+ # The summary reads recording-derived observations and delivers off-platform, so require
+ # session_recording read — same gate as configuring an action.
+ if not self.user_access_control.check_access_level_for_resource("session_recording", required_level="viewer"):
+ raise PermissionDenied("Running a Replay Vision summary requires session_recording read access.")
+ if action_obj.mode != ActionMode.GROUP_SUMMARY:
+ # Alerts check continuously on the sweep; there's no meaningful "run now" for them.
+ raise ValidationError("Only scheduled summaries can be run on demand.")
+
+ workflow_id, outcome = start_process_vision_action_workflow(
+ action_obj.id, self.team_id, scheduled_at=timezone.now()
+ )
+ if outcome is WorkflowStartOutcome.FAILED:
+ return Response(
+ {"error": "Failed to start the summary run."},
+ status=status.HTTP_503_SERVICE_UNAVAILABLE,
+ )
+ return Response(
+ RunActionResponseSerializer(
+ {"workflow_id": workflow_id, "already_running": outcome is WorkflowStartOutcome.ALREADY_RUNNING}
+ ).data,
+ status=status.HTTP_202_ACCEPTED,
+ )
+
# Human-readable copy for the engine's controlled skip/abort reasons (see temporal.vision_actions —
# _validate skip reasons and SynthesisStatus). Unmapped values fall through to the raw string.
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 86534f751a4d..b89b4b49ad61 100644
--- a/products/replay_vision/backend/tests/test_vision_actions_api.py
+++ b/products/replay_vision/backend/tests/test_vision_actions_api.py
@@ -1,7 +1,7 @@
from typing import Any
from posthog.test.base import APIBaseTest
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
from parameterized import parameterized
@@ -519,3 +519,94 @@ class TestVisionActionRunCrossTeamIDOR(_VisionActionAPITestCase):
# The action belongs to another team, so the nested route must 404 rather than leak its runs.
resp = self.client.get(f"/api/projects/{self.team.id}/vision/actions/{self.other_action.id}/runs/")
self.assertEqual(resp.status_code, 404)
+
+
+class TestVisionActionRunNow(_VisionActionAPITestCase):
+ """POST /vision/actions/{id}/run/ starts the processing workflow now without touching the schedule."""
+
+ def _summary(self, **overrides: Any) -> VisionAction:
+ defaults: dict[str, Any] = {
+ "team_id": self.team.id,
+ "scanner": self.scanner,
+ "name": "daily digest",
+ "created_by": self.user,
+ "trigger_config": {"rrule": "FREQ=DAILY;BYHOUR=8", "timezone": "UTC"},
+ }
+ defaults.update(overrides)
+ return VisionAction.objects.for_team(self.team.id).create(**defaults)
+
+ def _run_url(self, action_id: str) -> str:
+ return f"{self.actions_url}{action_id}/run/"
+
+ @patch("products.replay_vision.backend.api.trigger.async_to_sync")
+ @patch("products.replay_vision.backend.api.trigger.sync_connect")
+ def test_run_starts_the_workflow_now_and_leaves_the_schedule_untouched(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ from products.replay_vision.backend.temporal.constants import (
+ PROCESS_VISION_ACTION_WORKFLOW_NAME,
+ build_process_vision_action_workflow_id,
+ )
+
+ mock_sync_connect.return_value = MagicMock()
+ start_workflow = MagicMock()
+ mock_async_to_sync.return_value = start_workflow
+
+ action = self._summary()
+ next_run_before = action.next_run_at
+
+ resp = self.client.post(self._run_url(str(action.id)), format="json")
+ self.assertEqual(resp.status_code, 202, resp.content)
+ body = resp.json()
+ self.assertFalse(body["already_running"])
+ self.assertEqual(body["workflow_id"], build_process_vision_action_workflow_id(action.id))
+
+ args, kwargs = start_workflow.call_args
+ self.assertEqual(args[0], PROCESS_VISION_ACTION_WORKFLOW_NAME)
+ inputs = args[1]
+ self.assertEqual(inputs.vision_action_id, action.id)
+ self.assertEqual(inputs.mode, "group_summary")
+ self.assertIsNotNone(inputs.scheduled_at) # anchors the window at "now"
+
+ # The run must not advance the recurring schedule — that only happens at scheduled claim time.
+ action.refresh_from_db()
+ self.assertEqual(action.next_run_at, next_run_before)
+
+ @patch("products.replay_vision.backend.api.trigger.async_to_sync")
+ @patch("products.replay_vision.backend.api.trigger.sync_connect")
+ def test_run_coalesces_onto_an_already_running_workflow(
+ self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock
+ ) -> None:
+ from temporalio.exceptions import WorkflowAlreadyStartedError
+
+ from products.replay_vision.backend.temporal.constants import (
+ PROCESS_VISION_ACTION_WORKFLOW_NAME,
+ build_process_vision_action_workflow_id,
+ )
+
+ action = self._summary()
+ mock_sync_connect.return_value = MagicMock()
+ mock_async_to_sync.return_value = MagicMock(
+ side_effect=WorkflowAlreadyStartedError(
+ workflow_id=build_process_vision_action_workflow_id(action.id),
+ workflow_type=PROCESS_VISION_ACTION_WORKFLOW_NAME,
+ )
+ )
+
+ resp = self.client.post(self._run_url(str(action.id)), format="json")
+ self.assertEqual(resp.status_code, 202, resp.content)
+ self.assertTrue(resp.json()["already_running"])
+
+ @patch("products.replay_vision.backend.api.trigger.async_to_sync")
+ @patch("products.replay_vision.backend.api.trigger.sync_connect")
+ def test_run_rejects_alerts(self, mock_sync_connect: MagicMock, mock_async_to_sync: MagicMock) -> None:
+ # Alerts check continuously on the sweep, so there's no meaningful on-demand run for them.
+ alert = self._summary(
+ name="rage alert",
+ mode="alert",
+ alert_config={"frequency": "every_match", "metric": "count"},
+ )
+ resp = self.client.post(self._run_url(str(alert.id)), format="json")
+ self.assertEqual(resp.status_code, 400, resp.content)
+ start_workflow = mock_async_to_sync.return_value
+ start_workflow.assert_not_called()
diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.ts
index 3ac00049e123..e6ef3d269586 100644
--- a/products/replay_vision/frontend/generated/api.schemas.ts
+++ b/products/replay_vision/frontend/generated/api.schemas.ts
@@ -369,6 +369,16 @@ export interface PatchedVisionActionApi {
readonly updated_at?: string
}
+/**
+ * Async-accepted response for POST /vision/actions/{id}/run/.
+ */
+export interface RunActionResponseApi {
+ /** Temporal workflow id for the run; the resulting run appears under the action's run history. */
+ workflow_id: string
+ /** True when a run for this action was already in progress (scheduled or manual), so this request coalesced onto it rather than starting a second run. */
+ already_running: boolean
+}
+
/**
* * `running` - Running
* * `completed` - Completed
diff --git a/products/replay_vision/frontend/generated/api.ts b/products/replay_vision/frontend/generated/api.ts
index 154e4b493bb3..f33c48023b25 100644
--- a/products/replay_vision/frontend/generated/api.ts
+++ b/products/replay_vision/frontend/generated/api.ts
@@ -34,6 +34,7 @@ import type {
ReplayScannerApi,
ReplayScannerPromptSuggestionApi,
RetryResponseApi,
+ RunActionResponseApi,
ScannerCreatorsResponseApi,
ScannerImpactApi,
ScannerStatsResponseApi,
@@ -174,6 +175,26 @@ export const visionActionsDestroy = async (projectId: string, id: string, option
})
}
+export const getVisionActionsRunCreateUrl = (projectId: string, id: string) => {
+ return `/api/projects/${projectId}/vision/actions/${id}/run/`
+}
+
+/**
+ * Run this summary now, without waiting for its schedule — synthesizes a group summary over the
+ * observations since the last summary (or the last 24h). The recurring schedule is untouched: the
+ * engine advances next_run_at only at scheduled claim time, never in the run itself.
+ */
+export const visionActionsRunCreate = async (
+ projectId: string,
+ id: string,
+ options?: RequestInit
+): Promise<RunActionResponseApi> => {
+ return apiMutator<RunActionResponseApi>(getVisionActionsRunCreateUrl(projectId, id), {
+ ...options,
+ method: 'POST',
+ })
+}
+
export const getVisionActionsRunsListUrl = (
projectId: string,
visionActionId: string,
diff --git a/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx b/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx
index 58ce20d22226..694babb0828d 100644
--- a/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/VisionActionScene.tsx
@@ -1,6 +1,6 @@
-import { BindLogic, useValues } from 'kea'
+import { BindLogic, useActions, useValues } from 'kea'
-import { IconPencil } from '@posthog/icons'
+import { IconPencil, IconPlay } from '@posthog/icons'
import { LemonButton, LemonCard, SpinnerOverlay } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
@@ -44,6 +44,9 @@ function ActionOverview({
// `action.scanner` is only the id — the action's own user_access_level would just reflect the
// replay_scanner resource default, not a per-scanner object grant, so load the scanner itself.
const { scanner } = useValues(replayScannerLogic({ id: action.scanner }))
+ const { runningNow, runInProgress } = useValues(visionActionRunsLogic)
+ const { runNow } = useActions(visionActionRunsLogic)
+ const editDisabledReason = getReplayVisionEditDisabledReason(scanner?.user_access_level)
return (
<>
@@ -60,15 +63,31 @@ function ActionOverview({
}
resourceType={{ type: 'replay_vision' }}
actions={
- <LemonButton
- type="secondary"
- icon={<IconPencil />}
- to={urls.replayVisionActionEdit(action.id)}
- disabledReason={getReplayVisionEditDisabledReason(scanner?.user_access_level)}
- data-attr="vision-action-edit-from-page"
- >
- Edit
- </LemonButton>
+ <>
+ {!isAlert && (
+ <LemonButton
+ type="secondary"
+ icon={<IconPlay />}
+ onClick={runNow}
+ loading={runningNow}
+ disabledReason={
+ editDisabledReason ?? (runInProgress ? 'A run is already in progress' : undefined)
+ }
+ data-attr="vision-action-run-now"
+ >
+ {runInProgress ? 'Running…' : 'Run now'}
+ </LemonButton>
+ )}
+ <LemonButton
+ type="secondary"
+ icon={<IconPencil />}
+ to={urls.replayVisionActionEdit(action.id)}
+ disabledReason={editDisabledReason}
+ data-attr="vision-action-edit-from-page"
+ >
+ Edit
+ </LemonButton>
+ </>
}
/>
{!isAlert && (
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx
index 890aa8e0bb60..a61b69586f00 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerDigestCard.tsx
@@ -41,10 +41,22 @@ export function ScannerDigestCard({
scannerName: string
}): JSX.Element | null {
const logic = scannerDigestLogic({ scannerId, scannerName })
- const { digest, latestRun, latestRunLoading, digestCreating, expanded, visionActionsLoading } = useValues(logic)
- const { createDigest, toggleExpanded, toggleActionEnabled } = useActions(logic)
+ const {
+ digest,
+ latestRun,
+ latestRunLoading,
+ digestCreating,
+ expanded,
+ visionActionsLoading,
+ runningNow,
+ runInProgress,
+ } = useValues(logic)
+ const { createDigest, 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
+ // second run coalesces server-side anyway, but disabling makes that obvious and stops spam clicks.
+ const runNowDisabledReason = editDisabledReason ?? (runInProgress ? 'A run is already in progress' : undefined)
if (visionActionsLoading && !digest) {
return null
@@ -112,14 +124,26 @@ export function ScannerDigestCard({
</>
)}
</span>
- <LemonButton
- type="secondary"
- size="small"
- to={urls.replayVisionActionEdit(digest.id)}
- data-attr="vision-scanner-digest-edit"
- >
- Edit schedule
- </LemonButton>
+ <div className="flex items-center gap-2">
+ <LemonButton
+ type="primary"
+ size="small"
+ onClick={runNow}
+ loading={runningNow}
+ disabledReason={runNowDisabledReason}
+ data-attr="vision-scanner-digest-run-now-empty"
+ >
+ {runInProgress ? 'Running…' : 'Run now'}
+ </LemonButton>
+ <LemonButton
+ type="secondary"
+ size="small"
+ to={urls.replayVisionActionEdit(digest.id)}
+ data-attr="vision-scanner-digest-edit"
+ >
+ Edit schedule
+ </LemonButton>
+ </div>
</div>
</CardShell>
)
@@ -167,6 +191,16 @@ export function ScannerDigestCard({
{expanded ? 'Show less' : 'Show more'}
</LemonButton>
<div className="flex-1" />
+ <LemonButton
+ size="xsmall"
+ type="secondary"
+ onClick={runNow}
+ loading={runningNow}
+ disabledReason={runNowDisabledReason}
+ data-attr="vision-scanner-digest-run-now"
+ >
+ {runInProgress ? 'Running…' : 'Run now'}
+ </LemonButton>
{!delivers && (
<LemonButton
size="xsmall"
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
index 10630ef6cc2e..4d3776afa6f0 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionActionsTab.tsx
@@ -106,11 +106,10 @@ function VisionActionsTable({
const { visionActions, visionActionsLoading, togglingIds } = useValues(visionActionsLogic)
const { toggleActionEnabled, deleteAction } = useActions(visionActionsLogic)
- // The scanner's built-in daily digest lives on the Observations tab (ScannerDigestCard), not this
- // table — so this table lists only the summaries and alerts a user created, and its empty state is
- // meaningful again. Filtered here, not in visionActionsLogic, so the digest stays in the shared
- // list the card reads from.
- const rows = visionActions.filter((a) => !a.is_scanner_digest)
+ // The scanner's built-in daily digest is listed here alongside user-created summaries and alerts
+ // (marked with a "Daily digest" chip), so this page is the one place to see and manage every
+ // automation on the scanner. It also has its own hero surface on the Observations tab.
+ const rows = visionActions
if (!visionActionsLoading && rows.length === 0) {
return (
@@ -161,6 +160,7 @@ function VisionActionsTable({
>
{action.name}
</Link>
+ {action.is_scanner_digest && <LemonTag type="highlight">Daily 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 d21dca6ca309..37f906139036 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.test.ts
@@ -109,4 +109,24 @@ describe('scannerDigestLogic', () => {
expect(logic.values.digest?.id).toEqual('d-new')
expect(logic.values.latestRunLoading).toEqual(false)
})
+
+ it('runNow posts to the digest run endpoint and clears its loading state', async () => {
+ useMocks(mocksFor([DIGEST]))
+ mountLogic()
+ await expectLogic(logic).toFinishAllListeners()
+ let posted = false
+ useMocks({
+ post: {
+ '/api/projects/:team/vision/actions/:action/run/': ({ request }: { request: Request }) => {
+ // Runs the digest itself (d1), not some other action.
+ expect(request.url).toContain('/vision/actions/d1/run/')
+ posted = true
+ return [202, { workflow_id: 'wf-1', already_running: false }]
+ },
+ },
+ })
+ await expectLogic(logic, () => logic.actions.runNow()).toFinishAllListeners()
+ expect(posted).toBe(true)
+ expect(logic.values.runningNow).toBe(false)
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts
index 95bf346d74f1..b18f7ceec050 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerDigestLogic.ts
@@ -3,9 +3,15 @@ import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path,
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { visionActionsCreate, visionActionsRunsList, visionActionsRunsRetrieve } from '../generated/api'
+import {
+ visionActionsCreate,
+ visionActionsRunCreate,
+ visionActionsRunsList,
+ visionActionsRunsRetrieve,
+} from '../generated/api'
import { VisionActionRunStatusEnumApi } from '../generated/api.schemas'
import type { VisionActionApi, VisionActionRunApi } from '../generated/api.schemas'
+import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'
import { visionActionsLogic } from './visionActionsLogic'
export interface ScannerDigestLogicProps {
@@ -28,6 +34,10 @@ export interface scannerDigestLogicValues {
expanded: boolean
latestRun: VisionActionRunApi | null
latestRunLoading: boolean
+ pollUntil: number
+ runInProgress: boolean
+ runningNow: boolean
+ shouldPoll: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -62,6 +72,15 @@ export interface scannerDigestLogicActions {
loadLatestRunSuccess: (run: VisionActionRunApi | null) => {
run: VisionActionRunApi | null
}
+ runNow: () => {
+ value: true
+ }
+ runNowDone: () => {
+ value: true
+ }
+ setRunInProgress: (inProgress: boolean) => {
+ inProgress: boolean
+ }
toggleExpanded: () => {
value: true
}
@@ -72,6 +91,7 @@ export interface scannerDigestLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
digest: (visionActions: VisionActionApi[]) => VisionActionApi | null
+ shouldPoll: (runInProgress: boolean, pollUntil: number) => boolean
}
}
@@ -102,6 +122,9 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
createDigest: true,
createDigestSuccess: true,
createDigestFailure: true,
+ runNow: true,
+ runNowDone: true,
+ setRunInProgress: (inProgress: boolean) => ({ inProgress }),
toggleExpanded: true,
}),
@@ -135,6 +158,29 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
toggleExpanded: (state) => !state,
},
],
+ // Loading state for the digest card's "Run now" button (the ~1s trigger request).
+ runningNow: [
+ false,
+ {
+ runNow: () => true,
+ runNowDone: () => false,
+ },
+ ],
+ // A digest run is actively processing (from the runs list) — disables "Run now" and drives polling.
+ runInProgress: [
+ false,
+ {
+ setRunInProgress: (_, { inProgress }) => inProgress,
+ },
+ ],
+ // Keep polling for a grace window after a manual run: the workflow creates its run row
+ // asynchronously, so the RUNNING row usually isn't there on the refresh right after triggering.
+ pollUntil: [
+ 0,
+ {
+ runNow: () => Date.now() + OBSERVE_POLL_GRACE_MS,
+ },
+ ],
}),
selectors({
@@ -143,76 +189,115 @@ export const scannerDigestLogic = kea<scannerDigestLogicType>([
(visionActions: VisionActionApi[]): VisionActionApi | null =>
visionActions.find((a) => a.is_scanner_digest) ?? null,
],
+ shouldPoll: [
+ (s) => [s.runInProgress, s.pollUntil],
+ (runInProgress: boolean, pollUntil: number): boolean => shouldPollObservations(runInProgress, pollUntil),
+ ],
}),
- listeners(({ actions, props, values }) => ({
- loadActionsSuccess: () => {
- if (values.digest) {
- actions.loadLatestRun()
- } else {
- // No digest → nothing to fetch; clear the initial loading state so the opt-in card shows.
- actions.loadLatestRunSuccess(null)
- }
- },
-
- loadLatestRun: async (_, breakpoint) => {
- const teamId = teamLogic.values.currentTeamId
- const digest = values.digest
- if (!teamId || !digest) {
- actions.loadLatestRunFailure()
- return
- }
- try {
- const page = await visionActionsRunsList(String(teamId), digest.id, { limit: RUN_LOOKBACK })
- breakpoint()
- const completed = (page.results ?? []).find((r) => r.status === VisionActionRunStatusEnumApi.Completed)
- if (!completed) {
+ listeners(({ actions, props, values, cache }) => {
+ // Reschedule after every settle so polling stops once no run is in flight and the grace window
+ // has elapsed. Rescheduled on failure too, so a transient hiccup can't kill the cycle.
+ const reschedulePoll = (): void =>
+ scheduleObservationPoll(cache.disposables, values.shouldPoll, () => actions.loadLatestRun())
+ return {
+ loadActionsSuccess: () => {
+ if (values.digest) {
+ actions.loadLatestRun()
+ } else {
+ // No digest → nothing to fetch; clear the initial loading state so the opt-in card shows.
actions.loadLatestRunSuccess(null)
+ }
+ },
+
+ loadLatestRun: async (_, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
+ const digest = values.digest
+ if (!teamId || !digest) {
+ actions.loadLatestRunFailure()
return
}
- // The run list is deliberately light (no report body); fetch the full run for the markdown.
- const run = await visionActionsRunsRetrieve(String(teamId), digest.id, completed.id)
- breakpoint()
- actions.loadLatestRunSuccess(run)
- } catch {
- // Silent: the card falls back to the "first digest is on its way" state.
- actions.loadLatestRunFailure()
- }
- },
+ try {
+ const page = await visionActionsRunsList(String(teamId), digest.id, { limit: RUN_LOOKBACK })
+ breakpoint()
+ const results = page.results ?? []
+ // Surface an in-flight run so the card can show "Running…" and disable Run now.
+ actions.setRunInProgress(results.some((r) => r.status === VisionActionRunStatusEnumApi.Running))
+ const completed = results.find((r) => r.status === VisionActionRunStatusEnumApi.Completed)
+ if (!completed) {
+ actions.loadLatestRunSuccess(null)
+ return
+ }
+ // The run list is deliberately light (no report body); fetch the full run for the markdown.
+ const run = await visionActionsRunsRetrieve(String(teamId), digest.id, completed.id)
+ breakpoint()
+ actions.loadLatestRunSuccess(run)
+ } catch {
+ // Silent: the card falls back to the "first digest is on its way" state.
+ actions.loadLatestRunFailure()
+ }
+ },
- createDigest: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- actions.createDigestFailure()
- return
- }
- try {
- const created = await visionActionsCreate(String(teamId), {
- // Mirrors the backend provisioning defaults (digest.py) for scanners created before
- // digests existed, or after the digest was deleted.
- name: `Daily digest: ${props.scannerName}`.slice(0, 255),
- scanner: props.scannerId,
- is_scanner_digest: true,
- trigger_config: {
- rrule: SCANNER_DIGEST_RRULE,
- timezone: teamLogic.values.currentTeam?.timezone || 'UTC',
- },
- delivery_config: [],
- })
- actions.createDigestSuccess()
- lemonToast.success('Daily digest turned on')
- // Insert the created digest optimistically instead of refetching the list — a refetch
- // would blank the card (visionActionsLoading true, digest still absent) and flash it.
- actions.addAction(created)
- // A brand-new digest has no runs yet, so resolve the run state locally rather than
- // fetching; this keeps the card from flashing through its latestRunLoading gap.
- actions.loadLatestRunSuccess(null)
- } catch (error: any) {
- actions.createDigestFailure()
- lemonToast.error(`Couldn't turn on the daily digest${error?.detail ? `: ${error.detail}` : ''}`)
- }
- },
- })),
+ createDigest: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.createDigestFailure()
+ return
+ }
+ try {
+ const created = await visionActionsCreate(String(teamId), {
+ // Mirrors the backend provisioning defaults (digest.py) for scanners created before
+ // digests existed, or after the digest was deleted.
+ name: `Daily digest: ${props.scannerName}`.slice(0, 255),
+ scanner: props.scannerId,
+ is_scanner_digest: true,
+ trigger_config: {
+ rrule: SCANNER_DIGEST_RRULE,
+ timezone: teamLogic.values.currentTeam?.timezone || 'UTC',
+ },
+ delivery_config: [],
+ })
+ actions.createDigestSuccess()
+ lemonToast.success('Daily digest turned on')
+ // Insert the created digest optimistically instead of refetching the list — a refetch
+ // would blank the card (visionActionsLoading true, digest still absent) and flash it.
+ actions.addAction(created)
+ // A brand-new digest has no runs yet, so resolve the run state locally rather than
+ // fetching; this keeps the card from flashing through its latestRunLoading gap.
+ actions.loadLatestRunSuccess(null)
+ } catch (error: any) {
+ actions.createDigestFailure()
+ lemonToast.error(`Couldn't turn on the daily digest${error?.detail ? `: ${error.detail}` : ''}`)
+ }
+ },
+
+ runNow: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ const digest = values.digest
+ if (!teamId || !digest) {
+ actions.runNowDone()
+ return
+ }
+ try {
+ const { already_running } = await visionActionsRunCreate(String(teamId), digest.id)
+ lemonToast.success(
+ already_running
+ ? 'A digest is already being generated — it will appear here shortly.'
+ : "Generating the digest now. It'll appear here in a minute or two."
+ )
+ // Refresh + poll so the card picks up the running run and then the finished summary.
+ actions.loadLatestRun()
+ } catch (error: any) {
+ lemonToast.error(`Couldn't run the digest${error?.detail ? `: ${error.detail}` : ''}`)
+ } finally {
+ actions.runNowDone()
+ }
+ },
+
+ loadLatestRunSuccess: reschedulePoll,
+ loadLatestRunFailure: reschedulePoll,
+ }
+ }),
afterMount(({ actions, values }) => {
// visionActionsLogic loads on its own mount; if it already settled (tab was visited first),
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts b/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts
index 076f3e798e7a..15b0948e5b11 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.test.ts
@@ -67,4 +67,32 @@ describe('visionActionRunsLogic', () => {
runsLoading: false,
})
})
+
+ it('runNow posts to the run endpoint and refreshes the runs list', async () => {
+ let posted = false
+ useMocks({
+ post: {
+ '/api/projects/:team/vision/actions/:action/run/': ({ request }: { request: Request }) => {
+ // The button hits this action's run endpoint, not create/observe.
+ expect(request.url).toContain('/vision/actions/a1/run/')
+ posted = true
+ return [202, { workflow_id: 'wf-1', already_running: false }]
+ },
+ },
+ })
+ await expectLogic(logic, () => logic.actions.runNow()).toFinishAllListeners()
+ // Posted, button loading cleared, and runs reloaded so the new running row can appear.
+ expect(posted).toBe(true)
+ expect(logic.values.runningNow).toBe(false)
+ })
+
+ it('runInProgress reflects a running run so Run now can be disabled against spam clicks', async () => {
+ // The button disables while a run is actively processing — a repeat run coalesces server-side,
+ // but the disable is what makes that obvious in the UI.
+ await expectLogic(logic).toFinishAllListeners()
+ expect(logic.values.runInProgress).toBe(false) // seeded runs are completed/skipped
+
+ logic.actions.loadRunsSuccess([run('r-live', { status: 'running' })], 1)
+ expect(logic.values.runInProgress).toBe(true)
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.ts b/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.ts
index 6e6cf3db510b..5ac16d6e9cb0 100644
--- a/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/visionActionRunsLogic.ts
@@ -1,10 +1,12 @@
-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { visionActionsRetrieve, visionActionsRunsList } from '../generated/api'
+import { visionActionsRetrieve, visionActionsRunCreate, visionActionsRunsList } from '../generated/api'
+import { VisionActionRunStatusEnumApi } from '../generated/api.schemas'
import type { VisionActionApi, VisionActionRunListApi } from '../generated/api.schemas'
+import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'
import { visionActionSceneLogic } from './visionActionSceneLogic'
export interface VisionActionRunsLogicProps {
@@ -15,9 +17,13 @@ export interface VisionActionRunsLogicProps {
export interface visionActionRunsLogicValues {
action: VisionActionApi | null
actionLoading: boolean
+ pollUntil: number
+ runInProgress: boolean
+ runningNow: boolean
runs: VisionActionRunListApi[]
runsCount: number
runsLoading: boolean
+ shouldPoll: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -44,11 +50,21 @@ export interface visionActionRunsLogicActions {
count: number
runs: VisionActionRunListApi[]
}
+ runNow: () => {
+ value: true
+ }
+ runNowDone: () => {
+ value: true
+ }
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface visionActionRunsLogicMeta {
key: string
+ __keaTypeGenInternalSelectorTypes: {
+ runInProgress: (runs: VisionActionRunListApi[]) => boolean
+ shouldPoll: (runInProgress: boolean, pollUntil: number) => boolean
+ }
}
export type visionActionRunsLogicType = MakeLogicType<
@@ -70,6 +86,8 @@ export const visionActionRunsLogic = kea<visionActionRunsLogicType>([
loadAction: true,
loadActionSuccess: (action: VisionActionApi) => ({ action }),
loadActionFailure: true,
+ runNow: true,
+ runNowDone: true,
}),
reducers({
@@ -108,40 +126,101 @@ export const visionActionRunsLogic = kea<visionActionRunsLogicType>([
loadActionFailure: () => false,
},
],
+ // Loading state for the "Run now" button on the run-history page.
+ runningNow: [
+ false,
+ {
+ runNow: () => true,
+ runNowDone: () => false,
+ },
+ ],
+ // Keep polling for a grace window after a manual run: the workflow creates its run row
+ // asynchronously, so the new RUNNING row usually isn't there on the refresh right after the
+ // trigger returns. Poll until it lands (and then until it finishes).
+ pollUntil: [
+ 0,
+ {
+ runNow: () => Date.now() + OBSERVE_POLL_GRACE_MS,
+ },
+ ],
}),
- listeners(({ actions, props }) => ({
- loadRuns: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- actions.loadRunsFailure()
- return
- }
- try {
- const response = await visionActionsRunsList(String(teamId), props.actionId, { limit: 100 })
- actions.loadRunsSuccess(response.results ?? [], response.count ?? response.results?.length ?? 0)
- } catch (error: any) {
- lemonToast.error(`Failed to load runs${error.detail ? `: ${error.detail}` : ''}`)
- actions.loadRunsFailure()
- }
- },
-
- // Loads the action metadata for the page title + breadcrumb. Runs render independently of this.
- loadAction: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- actions.loadActionFailure()
- return
- }
- try {
- const action = await visionActionsRetrieve(String(teamId), props.actionId)
- actions.loadActionSuccess(action)
- visionActionSceneLogic.actions.setActionContext(action.name, action.scanner ?? null)
- } catch {
- actions.loadActionFailure()
- }
- },
- })),
+ selectors({
+ // A summary/alert run is actively processing — used to keep "Run now" disabled (a second run
+ // coalesces server-side anyway, but disabling makes that obvious) and to drive polling.
+ runInProgress: [
+ (s) => [s.runs],
+ (runs: VisionActionRunListApi[]): boolean =>
+ runs.some((r) => r.status === VisionActionRunStatusEnumApi.Running),
+ ],
+ shouldPoll: [
+ (s) => [s.runInProgress, s.pollUntil],
+ (runInProgress: boolean, pollUntil: number): boolean => shouldPollObservations(runInProgress, pollUntil),
+ ],
+ }),
+
+ listeners(({ actions, props, values, cache }) => {
+ // Reschedule after every settle so polling stops once no run is in flight and the grace
+ // window has elapsed. Rescheduled on failure too, so a transient hiccup can't kill the cycle.
+ const reschedulePoll = (): void =>
+ scheduleObservationPoll(cache.disposables, values.shouldPoll, () => actions.loadRuns())
+ return {
+ loadRuns: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.loadRunsFailure()
+ return
+ }
+ try {
+ const response = await visionActionsRunsList(String(teamId), props.actionId, { limit: 100 })
+ actions.loadRunsSuccess(response.results ?? [], response.count ?? response.results?.length ?? 0)
+ } catch (error: any) {
+ lemonToast.error(`Failed to load runs${error.detail ? `: ${error.detail}` : ''}`)
+ actions.loadRunsFailure()
+ }
+ },
+
+ // Loads the action metadata for the page title + breadcrumb. Runs render independently of this.
+ loadAction: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.loadActionFailure()
+ return
+ }
+ try {
+ const action = await visionActionsRetrieve(String(teamId), props.actionId)
+ actions.loadActionSuccess(action)
+ visionActionSceneLogic.actions.setActionContext(action.name, action.scanner ?? null)
+ } catch {
+ actions.loadActionFailure()
+ }
+ },
+
+ runNow: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.runNowDone()
+ return
+ }
+ try {
+ const { already_running } = await visionActionsRunCreate(String(teamId), props.actionId)
+ lemonToast.success(
+ already_running ? 'A run is already in progress.' : 'Running now — the new run appears below.'
+ )
+ // Refresh so the new (running) run shows up; the poll keeps refreshing until it lands
+ // (the workflow creates the row asynchronously) and then until it finishes.
+ actions.loadRuns()
+ } catch (error: any) {
+ lemonToast.error(`Couldn't run this summary${error?.detail ? `: ${error.detail}` : ''}`)
+ } finally {
+ actions.runNowDone()
+ }
+ },
+
+ loadRunsSuccess: reschedulePoll,
+ loadRunsFailure: reschedulePoll,
+ }
+ }),
afterMount(({ actions }) => {
actions.loadRuns()
diff --git a/products/replay_vision/mcp/tools.yaml b/products/replay_vision/mcp/tools.yaml
index 2a1f4ea9f7b8..dcd445e01fa1 100644
--- a/products/replay_vision/mcp/tools.yaml
+++ b/products/replay_vision/mcp/tools.yaml
@@ -53,6 +53,9 @@ tools:
`synthesis_config`, `alert_config`, cadence, and delivery targets. Use `vision-actions-runs-list` +
`vision-actions-runs-retrieve` to read the reports it has actually produced.
feature_flag: replay-vision
+ vision-actions-run-create:
+ operation: vision_actions_run_create
+ enabled: false
vision-actions-runs-list:
operation: vision_actions_runs_list
enabled: true
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 8c042f281e2a..dd369629de74 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -60252,6 +60252,16 @@ export namespace Schemas {
reference: RoleExternalReference | null;
}
+ /**
+ * Async-accepted response for POST /vision/actions/{id}/run/.
+ */
+ export interface RunActionResponse {
+ /** Temporal workflow id for the run; the resulting run appears under the action's run history. */
+ workflow_id: string;
+ /** True when a run for this action was already in progress (scheduled or manual), so this request coalesced onto it rather than starting a second run. */
+ already_running: boolean;
+ }
+
export interface RunFailureLogs {
/** Failed CI jobs of this run with their thinned failure logs, grouped by job. */
jobs: CIJobFailureLog[];