:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(replay-vision): per scanner usage tab for granular report (#73907)
Hayne Ryu922a62f8f9a4
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex d3d3d6cc7823..519887da3641 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6891,9 +6891,9 @@ snapshots:scenes-app-quickstart-product-card--playground--light:hash: v1.k794b7964.b85349f783d2e37dc3d8f34c47a0cf0279472dd5f4b57a98972274fc6a08fac5.KzPnkFBWU41BKwOOklmvlpw3U_7UfSmDr-9HBibnCrcscenes-app-replay-vision--scanners-list--dark:- hash: v1.k794b7964.d34dcdf0513228fba74671c5ae8a086341a25da4072215f3017fbfecb30d709e.X5uu0XrowQzhQYiyylzfo6X3ovcKYa2Qz0JNsoO0ivc+ hash: v1.k794b7964.c224db762849cf8b332d37e72b254a859d40cd113b36b78f6f031e1f17efcf73.9d-GzGqGR4iCPVCCEOySYcYbGOR2NMRhr9JR9eOndBAscenes-app-replay-vision--scanners-list--light:- hash: v1.k794b7964.1922cbe5bcba96f64f4de8bfbaf270693c3acf561ab279f48b1fd95e2653eaa9.azCzWZ0LusXCVTJ6XQlTYpHdBzf7vXjYoOsEWR3Jd2s+ hash: v1.k794b7964.75b0fb01ded84eec9ed41f4503f5bd4bee361050b080f5d98793cb13e2dd7ac3.22HYMtg-KTJxgcNp2yxQLnlleJ7fdtvDnSRMyaZNGjAscenes-app-saved-insights--empty-state--dark:hash: v1.k794b7964.43545664c9133c8afd354be6a6ed8f808c35b381101325d9605114632fcdc0c9.l8w9uEOEmrH6Xl1kNd9ueRtg_51cJUSjWLdjWDM0Fkoscenes-app-saved-insights--empty-state--light:diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.pyindex 5a6cd4864ba5..032997cd5b24 100644--- a/products/replay_vision/backend/api/scanners.py+++ b/products/replay_vision/backend/api/scanners.py@@ -72,6 +72,7 @@ from products.replay_vision.backend.queries import (refresh_scanner_estimate,)from products.replay_vision.backend.quota import (+ ScannerSpend,compute_quota_snapshot,credits_used_by_scanner,current_period_bounds,@@ -303,6 +304,9 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"(1 credit = $0.01). Matches the window of the org-wide quota meter."),)+ observations_this_month = serializers.SerializerMethodField(+ help_text="Succeeded observations this scanner produced in the current billing period.",+ )last_swept_at = serializers.DateTimeField(read_only=True,help_text="Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery.",@@ -350,6 +354,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"credits_per_observation","estimated_monthly_credits","credits_this_month",+ "observations_this_month","last_swept_at","created_at","created_by",@@ -364,6 +369,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Mode"credits_per_observation","estimated_monthly_credits","credits_this_month",+ "observations_this_month","last_swept_at","created_at","created_by",@@ -382,8 +388,7 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modereturn Nonereturn scanner.estimated_monthly_observations * observation_credits_for_model(scanner.model)- @extend_schema_field(serializers.IntegerField())- def get_credits_this_month(self, scanner: ReplayScanner) -> int:+ def _scanner_spend(self, scanner: ReplayScanner) -> ScannerSpend:# The context dict is shared across the list's children, so the page's totals are computed once.totals = self.context.get("_scanner_credits_used")if totals is None:@@ -392,7 +397,15 @@ class ReplayScannerSerializer(UserAccessControlSerializerMixin, serializers.Modescanner_ids = [s.id for s in instance] if instance is not None else [scanner.id]totals = credits_used_by_scanner(self.context["get_team"]().organization_id, scanner_ids)self.context["_scanner_credits_used"] = totals- return totals.get(scanner.id, 0)+ return totals.get(scanner.id, ScannerSpend(0, 0))++ @extend_schema_field(serializers.IntegerField())+ def get_credits_this_month(self, scanner: ReplayScanner) -> int:+ return self._scanner_spend(scanner).credits++ @extend_schema_field(serializers.IntegerField())+ def get_observations_this_month(self, scanner: ReplayScanner) -> int:+ return self._scanner_spend(scanner).observationsdef validate(self, attrs: dict[str, Any]) -> dict[str, Any]:# Surface the (team_id, name) uniqueness as a 400 instead of letting the DB raise 500.diff --git a/products/replay_vision/backend/quota.py b/products/replay_vision/backend/quota.pyindex f16b8a7847c6..9494c5cc45fe 100644--- a/products/replay_vision/backend/quota.py+++ b/products/replay_vision/backend/quota.py@@ -97,8 +97,14 @@ def current_period_bounds(organization_id: UUID) -> BillingPeriod:return _current_period_bounds(organization, datetime.now(UTC))-def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dict[UUID, int]:- """Credits each scanner's succeeded observations consumed in the current billing period.+@dataclass(frozen=True)+class ScannerSpend:+ credits: int+ observations: int+++def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dict[UUID, ScannerSpend]:+ """Credits and observation counts for each scanner's succeeded observations in the current billing period.Priced at current rates from each observation's frozen snapshot model. Receipts freeze pricesat success time, so these totals can drift from the billed ledger after a mid-period price@@ -117,9 +123,13 @@ def credits_used_by_scanner(organization_id: UUID, scanner_ids: list[UUID]) -> dcreated_at__lt=period_end,).values_list("scanner_id", "scanner_snapshot__model"))- totals: dict[UUID, int] = {}+ totals: dict[UUID, ScannerSpend] = {}for (scanner_id, model), count in pairs.items():- totals[scanner_id] = totals.get(scanner_id, 0) + observation_credits_for_model(model or "") * count+ prev = totals.get(scanner_id, ScannerSpend(0, 0))+ totals[scanner_id] = ScannerSpend(+ credits=prev.credits + observation_credits_for_model(model or "") * count,+ observations=prev.observations + count,+ )return totalsdiff --git a/products/replay_vision/backend/temporal/activities/emit_observation_event.py b/products/replay_vision/backend/temporal/activities/emit_observation_event.pyindex 9bee3b2e8094..fc2970a807ed 100644--- a/products/replay_vision/backend/temporal/activities/emit_observation_event.py+++ b/products/replay_vision/backend/temporal/activities/emit_observation_event.py@@ -9,6 +9,7 @@ from posthog.api.capture import capture_internalfrom posthog.models.team import Teamfrom posthog.sync import database_sync_to_async+from products.replay_vision.backend.billing import observation_credits_for_modelfrom products.replay_vision.backend.models.replay_observation import ObservationTrigger, ReplayObservationfrom products.replay_vision.backend.temporal.constants import replay_vision_distinct_idfrom products.replay_vision.backend.temporal.decorators import track_activity@@ -63,6 +64,9 @@ def _emit_event(inputs: EmitObservationEventInputs) -> None:"triggered_by_user_id": observation.triggered_by_user_id,"model_used": snapshot.model,"provider_used": snapshot.provider,+ # Priced at emit time and frozen into the event, so spend charts can drift from+ # quota.py's repriced-at-current-rates totals after a price change.+ "credits": observation_credits_for_model(snapshot.model),"emits_signals": snapshot.emits_signals,# Flatten scanner output so HogQL can query individual fields without a JSON extract.**inputs.model_output.to_event_properties(),diff --git a/products/replay_vision/backend/tests/test_temporal.py b/products/replay_vision/backend/tests/test_temporal.pyindex 673c1ddbd44f..3b0a6bc238d2 100644--- a/products/replay_vision/backend/tests/test_temporal.py+++ b/products/replay_vision/backend/tests/test_temporal.py@@ -57,7 +57,10 @@ from products.replay_vision.backend.temporal.activities.count_in_flight_appliesfrom products.replay_vision.backend.temporal.activities.create_observation import create_observation_activityfrom products.replay_vision.backend.temporal.activities.embed_observation import embed_observation_activityfrom products.replay_vision.backend.temporal.activities.emit_classifier_tags import emit_classifier_tags_activity-from products.replay_vision.backend.temporal.activities.emit_observation_event import emit_observation_event_activity+from products.replay_vision.backend.temporal.activities.emit_observation_event import (+ _emit_event,+ emit_observation_event_activity,+)from products.replay_vision.backend.temporal.activities.emit_observation_signal import (SIGNAL_WEIGHT,emit_observation_signal_activity,@@ -104,6 +107,7 @@ from products.replay_vision.backend.temporal.types import (CreateObservationOutput,EmbedObservationInputs,EmitClassifierTagsInputs,+ EmitObservationEventInputs,EmitObservationSignalInputs,EnsureSessionAssetInputs,EnsureSessionAssetOutput,@@ -727,6 +731,26 @@ class TestObservationStateActivities:assert ReplayObservationUsage.objects.filter(observation_id=observation.id).count() == 0[email protected]_db(transaction=True)+class TestEmitObservationEventActivity:+ def test_event_prices_credits_from_the_frozen_snapshot(self) -> None:+ # The spend chart sums this property; dropping or mispricing it silently flatlines the chart.+ scanner = _make_scanner()+ observation = _make_observation(scanner)+ inputs = EmitObservationEventInputs(+ observation_id=observation.id,+ model_output=MonitorOutput(verdict="yes", reasoning="ok", confidence=0.9),+ )++ with patch(+ "products.replay_vision.backend.temporal.activities.emit_observation_event.capture_internal"+ ) as capture:+ _emit_event(inputs)++ properties = capture.call_args.kwargs["properties"]+ assert properties["credits"] == observation_credits_for_model(observation.scanner_snapshot["model"])++def _counter_value(metric_name: str, **labels: str) -> float:return REGISTRY.get_sample_value(metric_name, labels) or 0.0diff --git a/products/replay_vision/frontend/generated/api.schemas.ts b/products/replay_vision/frontend/generated/api.schemas.tsindex e6ef3d269586..ca59427a2475 100644--- a/products/replay_vision/frontend/generated/api.schemas.ts+++ b/products/replay_vision/frontend/generated/api.schemas.ts@@ -825,6 +825,8 @@ export interface ReplayScannerApi {readonly estimated_monthly_credits: number | null/** Credits this scanner's succeeded observations consumed in the current billing period (1 credit = $0.01). Matches the window of the org-wide quota meter. */readonly credits_this_month: number+ /** Succeeded observations this scanner produced in the current billing period. */+ readonly observations_this_month: number/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: stringreadonly created_at: string@@ -917,6 +919,8 @@ export interface PatchedReplayScannerApi {readonly estimated_monthly_credits?: number | null/** Credits this scanner's succeeded observations consumed in the current billing period (1 credit = $0.01). Matches the window of the org-wide quota meter. */readonly credits_this_month?: number+ /** Succeeded observations this scanner produced in the current billing period. */+ readonly observations_this_month?: number/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: stringreadonly created_at?: stringdiff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsxindex 6c9e9bd6cd9b..55fc162847ee 100644--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx@@ -4,7 +4,16 @@ import { useState } from 'react'import * as xRayPng from '@posthog/brand/hoggies/png/x-ray'import { IconPencil, IconPlus, IconRefresh, IconSearch, IconTrash } from '@posthog/icons'-import { LemonButton, LemonInput, LemonSwitch, LemonTable, Link, Spinner, SpinnerOverlay } from '@posthog/lemon-ui'+import {+ LemonButton,+ LemonInput,+ LemonSwitch,+ LemonTable,+ LemonTabs,+ Link,+ Spinner,+ SpinnerOverlay,+} from '@posthog/lemon-ui'import { pngHoggie } from 'lib/brand/hoggies'import { NotFound } from 'lib/components/NotFound'@@ -31,6 +40,7 @@ import { ScannerTypeBadge } from '../components/ScannerTypeBadge'import { getReplayVisionDeleteDisabledReason, getReplayVisionEditDisabledReason } from '../utils/accessControl'import { formatCredits } from '../utils/credits'import { VisionMetrics } from './components/VisionMetrics'+import { VisionUsageTab } from './components/VisionUsageTab'import { type ScannersSorting, SCANNERS_PAGE_SIZE, replayScannersLogic } from './replayScannersLogic'import { ENABLED_OPTIONS, EnabledFilter, SCANNER_TYPE_OPTIONS, ScannerType, ReplayScanner } from './types'@@ -122,6 +132,7 @@ export function ReplayScannersScene(): JSX.Element {const { loadScanners, deleteScanner, toggleScannerEnabled, setScannersFilters, clearFilters } =useActions(replayScannersLogic)const { push } = useActions(router)+ const { searchParams } = useValues(router)const { featureFlags, receivedFeatureFlags } = useValues(featureFlagLogic)const { featureFlagsTimedOut } = useValues(appLogic)@@ -189,7 +200,7 @@ export function ReplayScannersScene(): JSX.Element {sorter: true,},{- title: 'Spend this month',+ title: 'Spend this period',key: 'credits_this_month',render: (_, scanner) => (<span className="text-sm tabular-nums">{formatCredits(scanner.credits_this_month)}</span>@@ -280,94 +291,109 @@ export function ReplayScannersScene(): JSX.Element {action={() => push(urls.replayVisionTemplates())}/>- {(scannerStats?.total ?? 0) > 0 ? (- <VisionMetrics />- ) : scannerStatsLoading ? (- <div className="flex items-center justify-center h-72 bg-bg-light rounded">- <Spinner className="text-2xl" />- </div>- ) : null}+ <LemonTabs+ activeKey={searchParams.tab === 'usage' ? 'usage' : 'scanners'}+ onChange={(tab) => push(urls.replayVision(), tab === 'usage' ? { tab } : {})}+ tabs={[+ { key: 'scanners', label: 'Scanners', content: <></> },+ { key: 'usage', label: 'Usage', content: <></> },+ ]}+ />- <div className="flex flex-col gap-3">- <div className="flex items-center gap-2">- <h3 className="font-semibold text-base m-0">Scanners</h3>- <div className="ml-auto flex items-center gap-2">- <LemonInput- type="search"- placeholder="Search scanners..."- value={search}- onChange={(v) => setScannersFilters({ search: v })}- prefix={<IconSearch />}- className="max-w-sm"- />- <FilterPill<EnabledFilter>- label="Status"- options={ENABLED_OPTIONS}- value={enabledFilter}- onChange={(v) => setScannersFilters({ enabledFilter: v })}- />- <FilterPill<ScannerType>- label="Type"- options={TYPE_OPTIONS}- value={scannerTypeFilter}- onChange={(v) => setScannersFilters({ scannerTypeFilter: v })}- />- <FilterPill<string>- label="Created by"- options={createdByOptions}- value={createdByFilter}- onChange={(v) => setScannersFilters({ createdByFilter: v })}- />- {hasActiveFilters && (- <LemonButton type="tertiary" size="small" onClick={() => clearFilters()}>- Clear filters- </LemonButton>- )}- <LemonButton- type="secondary"- size="small"- icon={<IconRefresh />}- tooltip="Refresh"- onClick={() => loadScanners()}- loading={scannersLoading}- />- </div>- </div>+ {searchParams.tab === 'usage' ? (+ <VisionUsageTab />+ ) : (+ <>+ {(scannerStats?.total ?? 0) > 0 ? (+ <VisionMetrics />+ ) : scannerStatsLoading ? (+ <div className="flex items-center justify-center h-72 bg-bg-light rounded">+ <Spinner className="text-2xl" />+ </div>+ ) : null}- <LemonTable- columns={columns}- dataSource={scanners}- loading={scannersLoading}- rowKey="id"- pagination={{- controlled: true,- pageSize: SCANNERS_PAGE_SIZE,- currentPage: scannersPage,- entryCount: scannersTotal,- onForward: () => setScannersFilters({ page: scannersPage + 1 }),- onBackward: () => setScannersFilters({ page: scannersPage - 1 }),- }}- sorting={scannersSort}- onSort={(next) => setScannersFilters({ sort: next as ScannersSorting | null })}- noSortingCancellation- useURLForSorting={false}- nouns={['scanner', 'scanners']}- emptyState={- scannersTotal === 0 && !hasActiveFilters ? (- <div className="flex flex-col items-center gap-3 p-8 text-center">- <div className="text-muted">No scanners yet.</div>- <CreateScannerButton- acceptedLabel="Create your first scanner"- dataAttr="vision-scanner-create-empty"- size="medium"+ <div className="flex flex-col gap-3">+ <div className="flex items-center gap-2">+ <h3 className="font-semibold text-base m-0">Scanners</h3>+ <div className="ml-auto flex items-center gap-2">+ <LemonInput+ type="search"+ placeholder="Search scanners..."+ value={search}+ onChange={(v) => setScannersFilters({ search: v })}+ prefix={<IconSearch />}+ className="max-w-sm"+ />+ <FilterPill<EnabledFilter>+ label="Status"+ options={ENABLED_OPTIONS}+ value={enabledFilter}+ onChange={(v) => setScannersFilters({ enabledFilter: v })}+ />+ <FilterPill<ScannerType>+ label="Type"+ options={TYPE_OPTIONS}+ value={scannerTypeFilter}+ onChange={(v) => setScannersFilters({ scannerTypeFilter: v })}+ />+ <FilterPill<string>+ label="Created by"+ options={createdByOptions}+ value={createdByFilter}+ onChange={(v) => setScannersFilters({ createdByFilter: v })}+ />+ {hasActiveFilters && (+ <LemonButton type="tertiary" size="small" onClick={() => clearFilters()}>+ Clear filters+ </LemonButton>+ )}+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconRefresh />}+ tooltip="Refresh"+ onClick={() => loadScanners()}+ loading={scannersLoading}/></div>- ) : (- <span className="text-muted">No scanners match your filters.</span>- )- }- />- </div>+ </div>++ <LemonTable+ columns={columns}+ dataSource={scanners}+ loading={scannersLoading}+ rowKey="id"+ pagination={{+ controlled: true,+ pageSize: SCANNERS_PAGE_SIZE,+ currentPage: scannersPage,+ entryCount: scannersTotal,+ onForward: () => setScannersFilters({ page: scannersPage + 1 }),+ onBackward: () => setScannersFilters({ page: scannersPage - 1 }),+ }}+ sorting={scannersSort}+ onSort={(next) => setScannersFilters({ sort: next as ScannersSorting | null })}+ noSortingCancellation+ useURLForSorting={false}+ nouns={['scanner', 'scanners']}+ emptyState={+ scannersTotal === 0 && !hasActiveFilters ? (+ <div className="flex flex-col items-center gap-3 p-8 text-center">+ <div className="text-muted">No scanners yet.</div>+ <CreateScannerButton+ acceptedLabel="Create your first scanner"+ dataAttr="vision-scanner-create-empty"+ size="medium"+ />+ </div>+ ) : (+ <span className="text-muted">No scanners match your filters.</span>+ )+ }+ />+ </div>+ </>+ )}</SceneContent>)}diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsxindex 30aaf72d9cd7..5c21a2d9368d 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQualityTab.tsx@@ -405,7 +405,7 @@ function ConfigRecommendationPanel({ scannerId }: { scannerId: string }): JSX.El: quota?.exhausted && quota.credit_limit !== null? `Monthly Replay Vision budget of ${formatCredits(quota.credit_limit)} reached. Resets ${dayjs(quota.period_end).format('MMM D')}.`: quota && quota.remaining !== null && plannedTestCredits > quota.remaining- ? `Only ${formatCredits(quota.remaining)} of budget left this month. Lower the test session count.`+ ? `Only ${formatCredits(quota.remaining)} of budget left this period. Lower the test session count.`: undefined)}tooltip="Re-runs the scanner with the suggested prompt against your rated sessions, so you can see what would change before applying. Each tested session is charged like a normal observation. Pick how many below."@@ -463,7 +463,7 @@ function ConfigRecommendationPanel({ scannerId }: { scannerId: string }): JSX.El{Math.min(evaluationSessionCap, ratedCount) === 1 ? '' : 's'}, charging{' '}{formatCredits(plannedTestCredits)}{quota && quota.remaining !== null && quota.credit_limit !== null- ? ` (${formatCredits(quota.remaining)} of ${formatCredits(quota.credit_limit)} left this month)`+ ? ` (${formatCredits(quota.remaining)} of ${formatCredits(quota.credit_limit)} left this period)`: ''}.</span>diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsxindex f21cbd2ec869..736574ec2a00 100644--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx@@ -57,7 +57,7 @@ export function ScannerQuotaForecast({ scannerId }: Props): JSX.Element | null {const breakdown = (<div className="text-xs space-y-0.5"><div>- Spent this month: <strong>{formatCredits(used)}</strong>+ Spent this period: <strong>{formatCredits(used)}</strong></div><div>Projected from this scanner: <strong>~{formatCredits(projectedCredits ?? 0)}/month</strong>diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsxindex 02889fe12d13..b47f35e63866 100644--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx@@ -1,9 +1,10 @@import { useActions, useValues } from 'kea'import { useMemo } from 'react'-import { Spinner, Tooltip } from '@posthog/lemon-ui'+import { Link, Spinner, Tooltip } from '@posthog/lemon-ui'import { DateFilter } from 'lib/components/DateFilter/DateFilter'+import { urls } from 'scenes/urls'import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'import { BaseMathType, ChartDisplayType, InsightLogicProps } from '~/types'@@ -60,7 +61,7 @@ export function VisionMetrics(): JSX.Element {)return (- <div className="flex flex-col lg:flex-row gap-4 h-80">+ <div className="flex flex-col lg:flex-row gap-4 h-96"><div className="flex-1 bg-bg-light rounded p-4 flex flex-col InsightCard h-full"><div className="flex items-start justify-between gap-2 mb-1"><h3 className="text-base font-semibold m-0">Observations over time</h3>@@ -104,7 +105,7 @@ export function VisionMetrics(): JSX.Element {</div><div className="flex-1 bg-bg-light border rounded p-4 flex flex-col"><div className="flex items-baseline justify-between gap-3 mb-2">- <div className="text-muted text-xs font-medium uppercase">Spend this month</div>+ <div className="text-muted text-xs font-medium uppercase">Spend this period</div>{hasCap && (<span className={`text-xs tabular-nums ${styles.text}`}>{percentLabel}%{' '}@@ -135,7 +136,7 @@ export function VisionMetrics(): JSX.Element {title={<div className="text-xs space-y-0.5"><div>- Spent this month:{' '}+ Spent this period:{' '}<strong>{formatCredits(quota.credits_used)}</strong></div><div>@@ -177,6 +178,11 @@ export function VisionMetrics(): JSX.Element {spend.</div>)}+ <div className="mt-2">+ <Link to={`${urls.replayVision()}?tab=usage`} className="text-xs">+ View usage by scanner+ </Link>+ </div></>) : quotaLoading ? (<div className="flex items-center py-2">diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsxnew file mode 100644index 000000000000..74da2b30c558--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/components/VisionUsageTab.tsx@@ -0,0 +1,208 @@+import { useActions, useValues } from 'kea'+import { useMemo } from 'react'++import { LemonSegmentedButton, LemonTable, LemonTag, Link } from '@posthog/lemon-ui'++import { LemonProgress } from 'lib/lemon-ui/LemonProgress'+import { LemonTableColumns } from 'lib/lemon-ui/LemonTable'+import { urls } from 'scenes/urls'++import { InsightVizNode, NodeKind, ProductKey } from '~/queries/schema/schema-general'+import { ChartDisplayType, InsightLogicProps, PropertyMathType } from '~/types'++import { visionQuotaLogic } from '../../logics/visionQuotaLogic'+import { formatCredits } from '../../utils/credits'+import { exhaustionForecast, hasCreditLimit, projectQuota } from '../../utils/quotaProjection'+import { ReplayScanner, modelName } from '../types'+import { SpendChartInterval, visionUsageLogic } from '../visionUsageLogic'+import { VisionInsightChart } from './VisionInsightChart'++const RECORDING_OBSERVED_EVENT = '$recording_observed'++const SPEND_CHART_INTERVAL_OPTIONS: { value: SpendChartInterval; label: string }[] = [+ { value: 'day', label: 'Daily' },+ { value: 'week', label: 'Weekly' },+ { value: 'month', label: 'Monthly' },+ { value: 'year', label: 'Yearly' },+]++// Daily covers the current billing period (set at query time); the rest widen the window to fit the bucket size.+const SPEND_CHART_DATE_FROM: Record<Exclude<SpendChartInterval, 'day'>, string> = {+ week: '-90d',+ month: '-365d',+ year: 'all',+}++export function VisionUsageTab(): JSX.Element {+ const { usageScanners, usageScannersLoading, spendChartInterval } = useValues(visionUsageLogic)+ const { setSpendChartInterval } = useActions(visionUsageLogic)+ const { quota } = useValues(visionQuotaLogic)++ const projection = projectQuota(quota)+ const hasCap = hasCreditLimit(quota)+ const forecastDate = quota+ ? exhaustionForecast(quota.credits_used, quota.credit_limit, quota.period_start, quota.period_end)+ : null++ const spenders = usageScanners.filter((s: ReplayScanner) => s.credits_this_month > 0)+ const zeroSpendCount = usageScanners.length - spenders.length+ const totalCredits = spenders.reduce((sum: number, s: ReplayScanner) => sum + s.credits_this_month, 0)+ const maxCredits = spenders.length > 0 ? spenders[0].credits_this_month : 0++ // Memoized so a re-render (e.g. quota arriving) can't churn the query and abort an in-flight load.+ // `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.+ const spendChartQuery = useMemo<InsightVizNode>(+ () => ({+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ {+ kind: NodeKind.EventsNode,+ event: RECORDING_OBSERVED_EVENT,+ math: PropertyMathType.Sum,+ math_property: 'credits',+ },+ ],+ trendsFilter: {+ display: ChartDisplayType.ActionsLineGraph,+ // The credits event property is 1 credit = $0.01; chart in dollars to match the table.+ formulaNodes: [{ formula: 'A / 100', custom_name: 'Spend' }],+ aggregationAxisPrefix: '$',+ },+ dateRange: {+ date_from:+ spendChartInterval === 'day'+ ? (quota?.period_start ?? '-30d')+ : SPEND_CHART_DATE_FROM[spendChartInterval],+ date_to: null,+ },+ interval: spendChartInterval,+ tags: { productKey: ProductKey.REPLAY_VISION },+ },+ }),+ [quota?.period_start, spendChartInterval]+ )+ const spendChartInsightProps = useMemo<InsightLogicProps>(+ () => ({+ dashboardItemId: 'new-replay-vision-usage-spend-chart',+ dataNodeCollectionId: 'replay-vision-usage',+ }),+ []+ )++ const columns: LemonTableColumns<ReplayScanner> = [+ {+ title: 'Scanner',+ key: 'name',+ width: '25%',+ render: (_, scanner) => (+ <div className="flex items-center gap-2">+ <Link to={urls.replayVision(scanner.id)} className="font-semibold text-primary">+ {scanner.name || '(untitled)'}+ </Link>+ {!scanner.enabled && <LemonTag type="muted">Disabled</LemonTag>}+ </div>+ ),+ },+ {+ title: 'Observations',+ key: 'observations_this_month',+ tooltip: 'Succeeded observations this billing period.',+ render: (_, scanner) => (+ <span className="text-sm tabular-nums">{scanner.observations_this_month.toLocaleString()}</span>+ ),+ },+ {+ title: 'Price per observation',+ key: 'credits_per_observation',+ render: (_, scanner) => (+ <span className="text-sm whitespace-nowrap">+ <span className="tabular-nums">+ {scanner.credits_per_observation} credit{scanner.credits_per_observation === 1 ? '' : 's'}+ </span>+ <span className="text-muted"> · {modelName(scanner.model)}</span>+ </span>+ ),+ },+ {+ title: 'Sampling',+ key: 'sampling_rate',+ tooltip: 'The main cost lever: lower sampling scans fewer of the matching sessions.',+ render: (_, scanner) => (+ <span className="text-sm tabular-nums">+ {(scanner.sampling_rate * 100).toFixed(scanner.sampling_rate < 0.1 ? 2 : 1)}%+ </span>+ ),+ },+ {+ title: 'Share of spend',+ key: 'credits_this_month',+ width: '30%',+ render: (_, scanner) => {+ const sharePct = totalCredits > 0 ? Math.round((scanner.credits_this_month / totalCredits) * 100) : 0+ const barPct = maxCredits > 0 ? Math.round((scanner.credits_this_month / maxCredits) * 100) : 0+ return (+ <div className="flex items-center gap-2 pr-6">+ <LemonProgress percent={barPct} className="flex-1" />+ <span className="text-sm tabular-nums whitespace-nowrap w-32 text-right">+ {formatCredits(scanner.credits_this_month)}{' '}+ <span className="text-muted">({sharePct}%)</span>+ </span>+ </div>+ )+ },+ },+ ]++ return (+ <div className="flex flex-col gap-4">+ <div className="bg-bg-light rounded p-4 flex flex-col InsightCard h-80">+ <div className="flex items-center justify-between gap-2 mb-1">+ <h3 className="text-base font-semibold m-0">Spend over time</h3>+ <div className="flex items-center gap-3">+ {quota && (+ <span className="text-xs text-muted tabular-nums">+ {formatCredits(quota.credits_used)}+ {hasCap ? ` of ${formatCredits(quota.credit_limit ?? 0)}` : ''} this period+ {projection.resetsOn ? `, resets ${projection.resetsOn}` : ''}+ </span>+ )}+ <LemonSegmentedButton+ size="small"+ value={spendChartInterval}+ onChange={(value) => setSpendChartInterval(value)}+ options={SPEND_CHART_INTERVAL_OPTIONS}+ />+ </div>+ </div>+ <p className="text-muted text-xs mb-3">Across all scanners</p>+ <VisionInsightChart+ query={spendChartQuery}+ insightProps={spendChartInsightProps}+ className="flex-1 flex flex-col min-h-0"+ />+ </div>+ {forecastDate && (+ <div className="text-xs text-warning">+ At the current pace, you'll reach your spend limit around {forecastDate}. Scanning pauses at the+ limit until the period resets.+ </div>+ )}+ <LemonTable+ columns={columns}+ dataSource={spenders}+ loading={usageScannersLoading}+ rowKey={(scanner) => scanner.id}+ emptyState="No spend this period yet. Costs appear here once scanners produce observations."+ footer={+ zeroSpendCount > 0 ? (+ <div className="px-3 py-2 text-xs text-muted">+ {zeroSpendCount} scanner{zeroSpendCount === 1 ? '' : 's'} with no spend this period+ </div>+ ) : undefined+ }+ />+ </div>+ )+}diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.tsindex 5c4a50edf8cc..9acfaeb098e3 100644--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts@@ -144,6 +144,7 @@ export function newScanner(templateKey?: string | null): ReplayScanner {// create-time gating falls back to the resource-level default instead (see getReplayVisionEditDisabledReason).user_access_level: null,credits_this_month: 0,+ observations_this_month: 0,} as constconst template = findScannerTemplate(templateKey ?? undefined)diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.tsindex 5a7175370722..a8a82fc92311 100644--- a/products/replay_vision/frontend/replay_scanners/types.ts+++ b/products/replay_vision/frontend/replay_scanners/types.ts@@ -174,6 +174,14 @@ export function modelLabel(model: string | null | undefined): string {return MODEL_OPTIONS.find((opt) => opt.value === model)?.label ?? model}+/** Plain model name without the price suffix, for surfaces that show the price separately. */+export function modelName(model: string | null | undefined): string {+ if (!model) {+ return '—'+ }+ return MODEL_NAMES[model as ScannerModelEnumApi] ?? model+}+export function scannerTypeLabel(scannerType: ScannerType | null | undefined): string {if (!scannerType) {return '—'diff --git a/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.tsnew file mode 100644index 000000000000..e63989ae059d--- /dev/null+++ b/products/replay_vision/frontend/replay_scanners/visionUsageLogic.ts@@ -0,0 +1,65 @@+import { MakeLogicType, actions, afterMount, kea, path, reducers } from 'kea'+import { loaders } from 'kea-loaders'++import { teamLogic } from 'scenes/teamLogic'++import { IntervalType } from '~/types'++import { visionScannersList } from '../generated/api'+import type { ReplayScanner } from './types'++export type SpendChartInterval = Extract<IntervalType, 'day' | 'week' | 'month' | 'year'>++interface visionUsageLogicValues {+ usageScanners: ReplayScanner[]+ usageScannersLoading: boolean+ spendChartInterval: SpendChartInterval+}++interface visionUsageLogicActions {+ loadUsageScanners: () => void+ loadUsageScannersSuccess: (usageScanners: ReplayScanner[]) => { usageScanners: ReplayScanner[] }+ loadUsageScannersFailure: (error: string) => { error: string }+ setSpendChartInterval: (interval: SpendChartInterval) => { interval: SpendChartInterval }+}++export type visionUsageLogicType = MakeLogicType<visionUsageLogicValues, visionUsageLogicActions>++// Loads the whole team's scanners ordered by spend for the Usage tab and the overview's+// usage bridge. Separate from replayScannersLogic so the list tab's filters and+// pagination never leak into usage math.+export const visionUsageLogic = kea<visionUsageLogicType>([+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'visionUsageLogic']),+ actions({+ setSpendChartInterval: (interval: SpendChartInterval) => ({ interval }),+ }),+ reducers({+ spendChartInterval: [+ 'day' as SpendChartInterval,+ {+ setSpendChartInterval: (_, { interval }) => interval,+ },+ ],+ }),+ loaders({+ usageScanners: [+ [] as ReplayScanner[],+ {+ loadUsageScanners: async (): Promise<ReplayScanner[]> => {+ const teamId = teamLogic.values.currentTeamId+ if (!teamId) {+ return []+ }+ const response = await visionScannersList(String(teamId), {+ order_by: '-credits_this_month',+ limit: 100,+ })+ return (response.results ?? []) as unknown as ReplayScanner[]+ },+ },+ ],+ }),+ afterMount(({ actions }) => {+ actions.loadUsageScanners()+ }),+])diff --git a/products/replay_vision/frontend/utils/quotaProjection.test.ts b/products/replay_vision/frontend/utils/quotaProjection.test.tsindex e55439689d61..81078f817fa7 100644--- a/products/replay_vision/frontend/utils/quotaProjection.test.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.test.ts@@ -1,4 +1,4 @@-import { projectQuota, quotaUx, splitProjectedPct } from './quotaProjection'+import { exhaustionForecast, projectQuota, quotaUx, splitProjectedPct } from './quotaProjection'import { makeQuota } from './quotaTestUtils'describe('projectQuota', () => {@@ -115,3 +115,30 @@ describe('quotaUx', () => {expect(quotaUx(makeQuota({ credits_used: 1_000, remaining: 9_000 }))).toEqual({})})})++describe('exhaustionForecast', () => {+ // Frozen 10 days into a July 1-31 period.+ beforeEach(() => {+ jest.useFakeTimers().setSystemTime(new Date('2026-07-11T00:00:00Z'))+ })+ afterEach(() => {+ jest.useRealTimers()+ })++ const PERIOD_START = '2026-07-01T00:00:00Z'+ const PERIOD_END = '2026-07-31T00:00:00Z'++ it.each([+ ['uncapped', 5_000, null],+ ['no spend yet', 0, 10_000],+ ['already at the limit', 10_000, 10_000],+ ['burn too slow to hit the limit this period', 1_000, 10_000],+ ])('returns null when %s', (_name, creditsUsed, creditLimit) => {+ expect(exhaustionForecast(creditsUsed, creditLimit, PERIOD_START, PERIOD_END)).toBeNull()+ })++ it('extrapolates the burn rate to the exhaustion date', () => {+ // 5,000 of 10,000 spent in 10 days: the other half runs out 10 days from now.+ expect(exhaustionForecast(5_000, 10_000, PERIOD_START, PERIOD_END)).toBe('Jul 21')+ })+})diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.tsindex 89cbe08fb67c..078943ca832e 100644--- a/products/replay_vision/frontend/utils/quotaProjection.ts+++ b/products/replay_vision/frontend/utils/quotaProjection.ts@@ -145,3 +145,26 @@ export function quotaBannerState(}return { kind: null }}++/** "You'll hit your limit around Jul 24": null when uncapped, unused, exhausted, or safely within budget. */+export function exhaustionForecast(+ creditsUsed: number,+ creditLimit: number | null,+ periodStart: string,+ periodEnd: string+): string | null {+ if (creditLimit === null || creditsUsed <= 0 || creditsUsed >= creditLimit) {+ return null+ }+ const elapsedMs = Date.now() - dayjs(periodStart).valueOf()+ if (elapsedMs <= 0) {+ return null+ }+ const burnPerMs = creditsUsed / elapsedMs+ const msToLimit = (creditLimit - creditsUsed) / burnPerMs+ const exhaustAt = dayjs(Date.now() + msToLimit)+ if (exhaustAt.isAfter(dayjs(periodEnd))) {+ return null+ }+ return exhaustAt.format('MMM D')+}diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex d0effc64aa73..80bb7c79fb78 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -42735,6 +42735,8 @@ export namespace Schemas {readonly estimated_monthly_credits: number | null;/** Credits this scanner's succeeded observations consumed in the current billing period (1 credit = $0.01). Matches the window of the org-wide quota meter. */readonly credits_this_month: number;+ /** Succeeded observations this scanner produced in the current billing period. */+ readonly observations_this_month: number;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at: string;readonly created_at: string;@@ -51474,6 +51476,8 @@ export namespace Schemas {readonly estimated_monthly_credits?: number | null;/** Credits this scanner's succeeded observations consumed in the current billing period (1 credit = $0.01). Matches the window of the org-wide quota meter. */readonly credits_this_month?: number;+ /** Succeeded observations this scanner produced in the current billing period. */+ readonly observations_this_month?: number;/** Watermark for the scanner's last scheduled fire. Mirrors Temporal schedule state for recovery. */readonly last_swept_at?: string;readonly created_at?: string;