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): error handling polish and estimation UI update (#61428)

Hayne Ryu9370a4f39abf
diff --git a/products/replay_vision/backend/api/scanners.py b/products/replay_vision/backend/api/scanners.py
index 946b93acf211..8873fee9b2d8 100644
--- a/products/replay_vision/backend/api/scanners.py
+++ b/products/replay_vision/backend/api/scanners.py
@@ -58,6 +58,37 @@ _QUERY_FIELDS_TO_STRIP = ("date_from", "date_to")
logger = structlog.get_logger(__name__)
+def _scanner_config_error_message(scanner_type: ScannerType, scanner_config: Any) -> str | None:
+ if not isinstance(scanner_config, dict):
+ return "Scanner configuration must be a JSON object."
+ prompt = scanner_config.get("prompt")
+ if not isinstance(prompt, str) or not prompt.strip():
+ return "Prompt is required."
+ if scanner_type == ScannerType.CLASSIFIER:
+ tags = scanner_config.get("tags") or []
+ if len(tags) == 0:
+ return "Tag vocabulary must have at least one tag."
+ if any(not isinstance(t, str) or not t.strip() for t in tags):
+ return "Tags can't be blank."
+ normalized = {t.strip().lower() for t in tags}
+ if len(normalized) != len(tags):
+ return "Tags must be unique."
+ if scanner_type == ScannerType.SCORER:
+ scale = scanner_config.get("scale")
+ if not isinstance(scale, dict):
+ return "Scale is required."
+ min_v, max_v = scale.get("min"), scale.get("max")
+ if not isinstance(min_v, (int, float)) or not isinstance(max_v, (int, float)):
+ return "Scale min and max must be numbers."
+ if min_v >= max_v:
+ return "Scale max must be greater than min."
+ try:
+ validate_scanner_config(scanner_config=scanner_config, scanner_type=scanner_type)
+ except (ValueError, PydanticValidationError):
+ return "Scanner configuration is invalid."
+ return None
+
+
class ReplayScannerSerializer(serializers.ModelSerializer):
name = serializers.CharField(
max_length=255,
@@ -164,10 +195,19 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
duplicates = duplicates.exclude(pk=self.instance.pk)
if duplicates.exists():
raise serializers.ValidationError({"name": "A scanner with this name already exists in this team."})
+ self._reject_scanner_type_change(attrs)
self._validate_scanner_config(attrs)
self._validate_and_strip_query(attrs)
return attrs
+ def _reject_scanner_type_change(self, attrs: dict[str, Any]) -> None:
+ if self.instance is None or "scanner_type" not in attrs:
+ return
+ if attrs["scanner_type"] != self.instance.scanner_type:
+ raise serializers.ValidationError(
+ {"scanner_type": "Scanner type is fixed after creation. Create a new scanner to use a different type."}
+ )
+
def _validate_scanner_config(self, attrs: dict[str, Any]) -> None:
# Skip when neither field is touched on PATCH — the existing combination has already been validated.
if "scanner_config" not in attrs and "scanner_type" not in attrs:
@@ -176,18 +216,17 @@ class ReplayScannerSerializer(serializers.ModelSerializer):
scanner_config = attrs.get("scanner_config", getattr(self.instance, "scanner_config", None))
if scanner_type is None:
return # Upstream `scanner_type` ChoiceField rejects this on create; PATCH with no instance is unreachable.
- try:
- validate_scanner_config(scanner_config=scanner_config, scanner_type=ScannerType(scanner_type))
- except (ValueError, PydanticValidationError) as exc:
- raise serializers.ValidationError({"scanner_config": str(exc)})
+ message = _scanner_config_error_message(ScannerType(scanner_type), scanner_config)
+ if message is not None:
+ raise serializers.ValidationError({"scanner_config": message})
def _validate_and_strip_query(self, attrs: dict[str, Any]) -> None:
if "query" not in attrs:
return
try:
RecordingsQuery.model_validate(attrs["query"])
- except PydanticValidationError as exc:
- raise serializers.ValidationError({"query": str(exc)})
+ except PydanticValidationError:
+ raise serializers.ValidationError({"query": "Recording filter is invalid."})
# Persist exactly what the user sent (validated), minus the date keys the schedule controls.
attrs["query"] = {k: v for k, v in attrs["query"].items() if k not in _QUERY_FIELDS_TO_STRIP}
@@ -364,8 +403,8 @@ class EstimateRequestSerializer(serializers.Serializer):
def validate_query(self, value: dict[str, Any]) -> dict[str, Any]:
try:
RecordingsQuery.model_validate(value)
- except PydanticValidationError as exc:
- raise serializers.ValidationError(str(exc))
+ except PydanticValidationError:
+ raise serializers.ValidationError("Recording filter is invalid.")
return {k: v for k, v in value.items() if k not in _QUERY_FIELDS_TO_STRIP}
@@ -533,8 +572,8 @@ class ReplayScannerViewSet(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
if snapshot.exhausted:
raise QuotaLimitExceeded(
detail=(
- f"Monthly Replay Vision quota of {snapshot.monthly_quota} observations reached; "
- f"resets at {snapshot.period_end.isoformat()}."
+ f"Monthly Replay Vision quota of {snapshot.monthly_quota:,} observations reached. "
+ f"Resets {snapshot.period_end.strftime('%b')} {snapshot.period_end.day}."
)
)
diff --git a/products/replay_vision/backend/tests/test_api.py b/products/replay_vision/backend/tests/test_api.py
index 6cc458dffdfa..57aa4c67887c 100644
--- a/products/replay_vision/backend/tests/test_api.py
+++ b/products/replay_vision/backend/tests/test_api.py
@@ -234,26 +234,104 @@ class TestReplayScannerViewSet(_VisionAPITestCase):
self.assertEqual(resp.status_code, 400, resp.json())
self.assertEqual(resp.json()["attr"], "scanner_config")
- def test_patch_scanner_type_validates_against_existing_config(self) -> None:
- # Existing monitor scanner has {"prompt": "..."}; switching to classifier without tags must 400.
+ @parameterized.expand(
+ [
+ (
+ "classifier_empty_tags",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": []},
+ "Tag vocabulary must have at least one tag.",
+ ),
+ (
+ "classifier_missing_tags",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p"},
+ "Tag vocabulary must have at least one tag.",
+ ),
+ (
+ "classifier_blank_tag",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": ["bug", " "]},
+ "Tags can't be blank.",
+ ),
+ (
+ "classifier_duplicate_tags",
+ ScannerType.CLASSIFIER,
+ {"prompt": "p", "tags": ["Bug", "bug"]},
+ "Tags must be unique.",
+ ),
+ (
+ "monitor_missing_prompt",
+ ScannerType.MONITOR,
+ {},
+ "Prompt is required.",
+ ),
+ (
+ "monitor_explicit_null_prompt",
+ ScannerType.MONITOR,
+ {"prompt": None},
+ "Prompt is required.",
+ ),
+ (
+ "scorer_inverted_scale",
+ ScannerType.SCORER,
+ {"prompt": "p", "scale": {"min": 10, "max": 0}},
+ "Scale max must be greater than min.",
+ ),
+ (
+ "scorer_missing_scale",
+ ScannerType.SCORER,
+ {"prompt": "p"},
+ "Scale is required.",
+ ),
+ (
+ "not_a_dict",
+ ScannerType.MONITOR,
+ "just a string",
+ "Scanner configuration must be a JSON object.",
+ ),
+ ]
+ )
+ def test_validation_returns_specific_message_per_invalid_config(
+ self, label: str, scanner_type: ScannerType, scanner_config: Any, expected_detail: str
+ ) -> None:
+ resp = self.client.post(
+ self.scanners_url,
+ data={
+ "name": f"invalid-{label}",
+ "scanner_type": scanner_type,
+ "scanner_config": scanner_config,
+ "model": ScannerModel.GEMINI_3_FLASH,
+ },
+ format="json",
+ )
+ self.assertEqual(resp.status_code, 400, resp.json())
+ body = resp.json()
+ detail = body.get("detail", "")
+ self.assertNotIn("validation error for", detail)
+ self.assertNotIn("errors.pydantic.dev", detail)
+ self.assertNotIn("input_value=", detail)
+ self.assertEqual(detail, expected_detail)
+
+ def test_patch_rejects_scanner_type_change(self) -> None:
scanner = self._create_scanner()
resp = self.client.patch(
f"{self.scanners_url}{scanner.id}/",
- data={"scanner_type": ScannerType.CLASSIFIER},
+ data={"scanner_type": ScannerType.CLASSIFIER, "scanner_config": {"prompt": "p", "tags": ["x"]}},
format="json",
)
self.assertEqual(resp.status_code, 400, resp.json())
- self.assertEqual(resp.json()["attr"], "scanner_config")
+ self.assertEqual(resp.json()["attr"], "scanner_type")
+ self.assertIn("fixed after creation", resp.json()["detail"])
- def test_patch_can_change_scanner_type_with_matching_config(self) -> None:
+ def test_patch_accepts_same_scanner_type(self) -> None:
scanner = self._create_scanner()
resp = self.client.patch(
f"{self.scanners_url}{scanner.id}/",
- data={"scanner_type": ScannerType.CLASSIFIER, "scanner_config": {"prompt": "p", "tags": ["x"]}},
+ data={"scanner_type": scanner.scanner_type, "scanner_config": {"prompt": "still a monitor"}},
format="json",
)
self.assertEqual(resp.status_code, 200, resp.json())
- self.assertEqual(resp.json()["scanner_type"], ScannerType.CLASSIFIER)
def test_create_accepts_valid_query(self) -> None:
resp = self.client.post(
diff --git a/products/replay_vision/frontend/components/ObservationsDock.tsx b/products/replay_vision/frontend/components/ObservationsDock.tsx
index 2d832fcfd4eb..48b6561fc06d 100644
--- a/products/replay_vision/frontend/components/ObservationsDock.tsx
+++ b/products/replay_vision/frontend/components/ObservationsDock.tsx
@@ -14,13 +14,13 @@ import { urls } from 'scenes/urls'
import type { ReplayScannerApi, VisionQuotaApi } from '../generated/api.schemas'
import { observationsDockLogic } from '../logics/observationsDockLogic'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { QUOTA_WARN_THRESHOLD } from '../utils/quotaProjection'
import { ObservationDockCard } from './ObservationCard'
const COLLAPSED_HEIGHT = 44
const DEFAULT_EXPANDED_HEIGHT = 480
const MIN_EXPANDED_HEIGHT = 120
const MAX_EXPANDED_HEIGHT = 800
-const QUOTA_WARN_THRESHOLD = 0.8
// Assumes block-only overage policy; revisit when `usage_based` lands so we don't disable buttons on metered orgs.
function quotaUx(quota: VisionQuotaApi | null): { disabledReason?: string; tooltip?: string } {
diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.ts
index 7ad82177358a..98fd5863cc38 100644
--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts
+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts
@@ -164,8 +164,8 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
actions.observeSuccess()
actions.setDockOpen(true)
actions.loadObservations()
- } catch (error) {
- lemonToast.error(`Failed to start observation: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to start observation${error.detail ? `: ${error.detail}` : ''}`)
actions.observeFailure()
}
},
diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.ts
index 7284390b9cf4..9564739ba6a4 100644
--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts
+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts
@@ -62,8 +62,8 @@ export const replayObservationLogic = kea<replayObservationLogicType>([
response.scanner_id,
response.scanner_snapshot?.name ?? null
)
- } catch (error) {
- lemonToast.error(`Failed to load observation: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to load observation${error.detail ? `: ${error.detail}` : ''}`)
actions.loadObservationFailure()
}
},
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index db536357c145..d08cbb6dac52 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -1,10 +1,10 @@
import { useActions, useValues } from 'kea'
import { Field, Form } from 'kea-forms'
+import { router } from 'kea-router'
import {
LemonBanner,
LemonButton,
- LemonDivider,
LemonInput,
LemonSelect,
LemonSwitch,
@@ -12,6 +12,7 @@ import {
LemonTabs,
LemonTag,
LemonTextArea,
+ Link,
} from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
@@ -20,13 +21,17 @@ import { More } from 'lib/lemon-ui/LemonButton/More'
import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
import { SceneExport } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { SceneContent } from '~/layout/scenes/components/SceneContent'
+import { SceneDivider } from '~/layout/scenes/components/SceneDivider'
+import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { QUOTA_WARN_THRESHOLD } from '../utils/quotaProjection'
import { ScannerObservationsTable } from './components/ScannerObservationsTable'
import { ScannerTriggers } from './components/ScannerTriggers'
import { ScannerTypeConfigEditor } from './components/ScannerTypeConfigEditor'
@@ -50,7 +55,9 @@ export function ReplayScannerSceneComponent({ tabId }: { tabId: string }): JSX.E
const { scanner, originalScanner, scannerLoading, isScannerSubmitting, hasUnsavedChanges, isNew } =
useValues(scannerLogic)
+ const { searchParams } = useValues(router)
const { setScannerType, submitScanner, resetScanner, deleteScanner } = useActions(scannerLogic)
+ const isTypeSelectable = isNew && !searchParams.template
if (scannerLoading || !scanner) {
return (
@@ -75,75 +82,109 @@ export function ReplayScannerSceneComponent({ tabId }: { tabId: string }): JSX.E
key: 'configuration',
label: 'Configuration',
content: (
- <div className="space-y-6 max-w-3xl pb-8">
- <div>
- <h3 className="text-base font-semibold mb-1">Details</h3>
- <p className="text-sm text-muted m-0">
- What this scanner looks for and how it analyzes recordings.
- </p>
- </div>
-
- <Field name="name" label="Name">
- <LemonInput placeholder="e.g. Confused checkout flow" />
- </Field>
-
- <Field name="description" label="Description (optional)">
- <LemonTextArea placeholder="What this scanner looks for and why." minRows={2} />
- </Field>
-
- {isNew ? (
- <Field name="scanner_type" label="Scanner type">
- <LemonSelect
- value={scanner.scanner_type}
- onChange={(v) => setScannerType(v)}
- options={SCANNER_TYPE_OPTIONS.map((opt) => ({
- value: opt.value,
- label: opt.label,
- labelInMenu: (
- <div className="flex flex-col">
- <span className="font-medium">{opt.label}</span>
- <span className="text-xs text-muted">{opt.description}</span>
- </div>
- ),
- }))}
- />
+ <div className="flex flex-col gap-y-4 max-w-3xl pb-12">
+ <SceneSection
+ title="Details"
+ description="What this scanner looks for and how it analyzes recordings."
+ titleSize="sm"
+ >
+ <Field name="name" label="Name">
+ <LemonInput placeholder="e.g. Confused checkout flow" />
</Field>
- ) : (
- <div className="space-y-1">
- <label className="block text-sm font-medium">Scanner type</label>
- <LemonTag type="option">
- {SCANNER_TYPE_OPTIONS.find((o) => o.value === scanner.scanner_type)?.label ??
- scanner.scanner_type}
- </LemonTag>
- <div className="text-xs text-muted">Scanner type is fixed after creation.</div>
- </div>
- )}
-
- <ScannerTypeConfigEditor scannerId={scannerId} tabId={tabId} />
-
- <Field name="model" label="Model">
- <LemonSelect value={scanner.model} options={MODEL_OPTIONS} />
- </Field>
-
- <Field name="emits_signals">
- {({ value, onChange }) => (
- <div className="flex items-center gap-3">
- <LemonSwitch checked={!!value} onChange={onChange} />
- <div>
- <div className="text-sm font-medium">Emit PostHog Signals</div>
- <div className="text-xs text-muted">Also flags actionable issues as Signals.</div>
+
+ <Field name="description" label="Description (optional)">
+ <LemonTextArea placeholder="What this scanner looks for and why." minRows={2} />
+ </Field>
+
+ {isTypeSelectable ? (
+ <Field name="scanner_type" label="Scanner type">
+ <LemonSelect
+ value={scanner.scanner_type}
+ onChange={(next) => {
+ if (next === scanner.scanner_type) {
+ return
+ }
+ if (scanner.scanner_config?.prompt?.trim()) {
+ LemonDialog.open({
+ title: 'Switch scanner type?',
+ description:
+ 'Your prompt and type-specific settings will reset to defaults for the new type.',
+ primaryButton: {
+ children: 'Switch and reset',
+ onClick: () => setScannerType(next),
+ },
+ secondaryButton: { children: 'Keep current' },
+ })
+ return
+ }
+ setScannerType(next)
+ }}
+ options={SCANNER_TYPE_OPTIONS.map((opt) => ({
+ value: opt.value,
+ label: opt.label,
+ labelInMenu: (
+ <div className="flex flex-col">
+ <span className="font-medium">{opt.label}</span>
+ <span className="text-xs text-muted">{opt.description}</span>
+ </div>
+ ),
+ }))}
+ />
+ </Field>
+ ) : (
+ <div className="space-y-1">
+ <label className="block text-sm font-medium">Scanner type</label>
+ <LemonTag type="option">
+ {SCANNER_TYPE_OPTIONS.find((o) => o.value === scanner.scanner_type)?.label ??
+ scanner.scanner_type}
+ </LemonTag>
+ <div className="text-xs text-muted">
+ {isNew ? (
+ <>
+ Type is set by the template you picked. To use a different type,{' '}
+ <Link to={urls.replayVisionTemplates()}>start from another template</Link>.
+ </>
+ ) : (
+ 'Scanner type is fixed after creation.'
+ )}
</div>
</div>
)}
- </Field>
- <LemonDivider />
+ <ScannerTypeConfigEditor scannerId={scannerId} tabId={tabId} />
+ </SceneSection>
+
+ <SceneDivider />
+
+ <SceneSection title="Advanced" description="Model choice and downstream emission." titleSize="sm">
+ <Field name="model" label="Model">
+ <LemonSelect value={scanner.model} options={MODEL_OPTIONS} />
+ </Field>
+
+ <Field name="emits_signals">
+ {({ value, onChange }) => (
+ <div className="flex items-center gap-3">
+ <LemonSwitch checked={!!value} onChange={onChange} />
+ <div>
+ <div className="text-sm font-medium">Emit PostHog Signals</div>
+ <div className="text-xs text-muted">
+ Also flags actionable issues as Signals.
+ </div>
+ </div>
+ </div>
+ )}
+ </Field>
+ </SceneSection>
- <div>
- <h3 className="text-base font-semibold mb-1">Triggers</h3>
- <p className="text-sm text-muted m-0">Which completed recordings this scanner runs against.</p>
- </div>
- <ScannerTriggers scannerId={scannerId} tabId={tabId} />
+ <SceneDivider />
+
+ <SceneSection
+ title="Triggers"
+ description="Which completed recordings this scanner runs against."
+ titleSize="sm"
+ >
+ <ScannerTriggers scannerId={scannerId} tabId={tabId} />
+ </SceneSection>
</div>
),
},
@@ -221,8 +262,6 @@ export function ReplayScannerSceneComponent({ tabId }: { tabId: string }): JSX.E
)
}
-const QUOTA_WARN_THRESHOLD = 0.8
-
// Assumes block-only overage policy; revisit when `usage_based` ships so we don't scare metered orgs.
function QuotaBanner(): JSX.Element | null {
const { quota } = useValues(visionQuotaLogic)
@@ -242,7 +281,7 @@ function QuotaBanner(): JSX.Element | null {
return (
<LemonBanner type="warning">
{quota.usage_this_month.toLocaleString()} of {quota.monthly_quota.toLocaleString()} monthly observations
- used. New observations will pause once you hit the cap; the quota resets on {resetsOn}.
+ used. New observations will pause once you hit the cap. Resets {resetsOn}.
</LemonBanner>
)
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
index 62ea170a3d5b..047bc663e3b4 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerQuotaForecast.tsx
@@ -1,9 +1,9 @@
import { useValues } from 'kea'
-import { Spinner } from '@posthog/lemon-ui'
-
-import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { Spinner, Tooltip } from '@posthog/lemon-ui'
+import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
+import { type QuotaStatus, projectQuota } from '../../utils/quotaProjection'
import { replayScannerLogic } from '../replayScannerLogic'
interface Props {
@@ -11,24 +11,150 @@ interface Props {
tabId: string
}
+const STATUS_STYLES: Record<QuotaStatus, { bar: string; text: string }> = {
+ safe: { bar: 'bg-primary', text: 'text-muted' },
+ warning: { bar: 'bg-warning', text: 'text-warning' },
+ danger: { bar: 'bg-danger', text: 'text-danger' },
+}
+
export function ScannerQuotaForecast({ scannerId, tabId }: Props): JSX.Element | null {
- const { scanner, scannerEstimate, scannerEstimateLoading } = useValues(replayScannerLogic({ id: scannerId, tabId }))
+ const { scanner, scannerEstimate, scannerEstimateLoading, isNew } = useValues(
+ replayScannerLogic({ id: scannerId, tabId })
+ )
+ const { quota } = useValues(visionQuotaLogic)
if (!scanner) {
return null
}
const samplingRatio = Math.max(0, Math.min(scanner.sampling_rate, 1))
- const samplingPercent = Math.round(samplingRatio * 1000) / 10
- const samplingLabel = samplingPercent.toFixed(samplingPercent < 1 ? 2 : 1)
+ const projected = scannerEstimate?.estimated_observations_per_month ?? null
+ const hasCap = !!quota && quota.monthly_quota > 0
+ const used = quota?.usage_this_month ?? 0
+ const cap = quota?.monthly_quota ?? 0
+
+ // On edit, this scanner's existing contribution is already inside `usage_this_month`, so adding
+ // its projection on top of historical burn would double-count. Skip the addition; the headline
+ // number still reads the new projection so the user can compare it to current burn.
+ const projection = projectQuota(quota, isNew ? projected : null)
+ const {
+ status,
+ capReachDate,
+ projectionConfident,
+ projectedPeriodEndRatio,
+ resetsOn,
+ daysRemaining,
+ combinedDailyRate,
+ } = projection
+
+ const effectiveStatus: QuotaStatus = projected === null ? 'safe' : status
+ const styles = STATUS_STYLES[effectiveStatus]
+ const percentLabel = hasCap ? Math.round(projectedPeriodEndRatio * 100) : 0
+
+ const usedPct = hasCap ? Math.min((used / cap) * 100, 100) : 0
+ const additionalUsagePct =
+ hasCap && projected !== null ? Math.min((combinedDailyRate * daysRemaining * 100) / cap, 100 - usedPct) : 0
+ const projectedPeriodEndUsage = used + (projected !== null ? combinedDailyRate * daysRemaining : 0)
+ const overflowPct = hasCap && projectedPeriodEndUsage > cap ? ((projectedPeriodEndUsage - cap) / cap) * 100 : 0
+
+ const renderBreakdown = (): JSX.Element => (
+ <div className="text-xs space-y-0.5">
+ <div>
+ Used this month: <strong>{used.toLocaleString()}</strong>
+ </div>
+ <div>
+ Projected from this scanner: <strong>~{(projected ?? 0).toLocaleString()}/month</strong>
+ </div>
+ <div>
+ Monthly cap: <strong>{cap.toLocaleString()}</strong>
+ </div>
+ {resetsOn && <div className="text-muted">Resets {resetsOn}</div>}
+ </div>
+ )
+
+ const renderStatusLine = (): JSX.Element | string => {
+ if (effectiveStatus === 'danger') {
+ if (capReachDate && projectionConfident) {
+ return (
+ <span className="text-danger">
+ Cap reached on <strong>{capReachDate.format('MMM D')}</strong> at this rate.
+ </span>
+ )
+ }
+ return <span className="text-danger">Projected to exceed your monthly cap.</span>
+ }
+ if (effectiveStatus === 'warning') {
+ return <span className="text-warning">Approaching cap by {resetsOn ?? 'period end'} at this rate.</span>
+ }
+ if (hasCap) {
+ return <>Should last the month at this rate.</>
+ }
+ return (
+ <>
+ Based on <strong>{scannerEstimate?.matched_sessions_in_window.toLocaleString() ?? 0}</strong> matching
+ recordings in the last {scannerEstimate?.window_days ?? 0} days.
+ </>
+ )
+ }
return (
<div className="border rounded p-3 bg-bg-light space-y-2">
- <div className="flex items-center justify-between">
- <span className="text-sm font-medium">Estimated impact</span>
- <span className="text-sm tabular-nums text-muted">{samplingLabel}% sampling</span>
+ <div className="flex items-baseline justify-between gap-3">
+ <div className="text-xs font-medium uppercase tracking-wide text-muted">Estimated impact</div>
+ {hasCap && projected !== null && (
+ <Tooltip title={renderBreakdown()}>
+ <span className={`text-xs tabular-nums ${styles.text}`}>
+ {percentLabel}%{' '}
+ <span className="text-muted font-normal">by {resetsOn ?? 'period end'}</span>
+ </span>
+ </Tooltip>
+ )}
+ </div>
+
+ <div className="flex items-baseline justify-between gap-3">
+ {projected !== null ? (
+ <div className="text-base font-semibold tabular-nums flex items-baseline gap-2">
+ <span>
+ {projected.toLocaleString()}{' '}
+ <span className="text-sm font-normal text-muted">observations/month</span>
+ </span>
+ {scannerEstimateLoading && (
+ <Tooltip title="Recomputing with the latest filters and sampling rate.">
+ <Spinner className="text-muted text-sm" />
+ </Tooltip>
+ )}
+ </div>
+ ) : (
+ <div className="text-sm text-muted">—</div>
+ )}
+ {hasCap && (
+ <span className="text-xs text-muted tabular-nums">
+ {used.toLocaleString()} / {cap.toLocaleString()}
+ </span>
+ )}
</div>
- <LemonProgress percent={Math.round(samplingRatio * 100)} />
+
+ {hasCap && projected !== null && (
+ <Tooltip title={renderBreakdown()}>
+ <div
+ className="flex h-1.5 rounded overflow-hidden bg-border-light"
+ role="meter"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={percentLabel}
+ aria-label={`Projected ${percentLabel}% of monthly observation quota by ${
+ resetsOn ?? 'period end'
+ }`}
+ >
+ <div className="bg-muted" style={{ width: `${usedPct}%` }} />
+ <div className={styles.bar} style={{ width: `${additionalUsagePct}%` }} />
+ {overflowPct > 0 && (
+ <div className="bg-danger opacity-60" style={{ width: `${Math.min(overflowPct, 100)}%` }} />
+ )}
+ </div>
+ </Tooltip>
+ )}
+
{samplingRatio === 0 ? (
<div className="text-xs text-danger">
Sampling is 0%. This scanner will not produce any observations.
@@ -38,14 +164,9 @@ export function ScannerQuotaForecast({ scannerId, tabId }: Props): JSX.Element |
<Spinner /> Estimating from your filters…
</div>
) : scannerEstimate ? (
- <div className="text-xs text-muted">
- About <strong>{scannerEstimate.estimated_observations_per_month.toLocaleString()}</strong>{' '}
- observations a month at this sampling. Based on{' '}
- <strong>{scannerEstimate.matched_sessions_in_window.toLocaleString()}</strong> matching recordings
- in the last {scannerEstimate.window_days} days.
- </div>
+ <div className="text-xs text-muted">{renderStatusLine()}</div>
) : (
- <div className="text-xs text-muted">Estimate unavailable — try adjusting your filters.</div>
+ <div className="text-xs text-muted">Estimate unavailable. Try adjusting your filters.</div>
)}
</div>
)
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
index 553b3d84e512..942053402770 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTypeConfigEditor.tsx
@@ -53,8 +53,8 @@ export function ScannerTypeConfigEditor({ scannerId, tabId }: { scannerId: strin
<div>
<div className="text-sm font-medium">Allow inconclusive verdicts</div>
<div className="text-xs text-muted">
- Lets the model answer `inconclusive` when the recording doesn't contain enough
- evidence to decide. Otherwise it must commit to `yes` or `no`.
+ Lets the model answer inconclusive when the recording doesn't contain enough
+ evidence to decide. Otherwise it must commit to yes or no.
</div>
</div>
</div>
@@ -131,15 +131,15 @@ export function ScannerTypeConfigEditor({ scannerId, tabId }: { scannerId: strin
<div className="flex items-center gap-3 max-w-md">
<LemonInput
type="number"
- value={scale.min}
- onChange={(v) => onChange({ ...scale, min: Number(v) || 0 })}
+ value={Number.isFinite(scale.min) ? scale.min : undefined}
+ onChange={(v) => onChange({ ...scale, min: v ?? Number.NaN })}
prefix={<span className="text-muted text-xs">min</span>}
/>
<span className="text-muted">to</span>
<LemonInput
type="number"
- value={scale.max}
- onChange={(v) => onChange({ ...scale, max: Number(v) || 0 })}
+ value={Number.isFinite(scale.max) ? scale.max : undefined}
+ onChange={(v) => onChange({ ...scale, max: v ?? Number.NaN })}
prefix={<span className="text-muted text-xs">max</span>}
/>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
index c58043cc4e96..4a35508f81e7 100644
--- a/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/VisionMetrics.tsx
@@ -10,6 +10,7 @@ import { InsightVizNode, NodeKind, ProductKey, TrendsQuery } from '~/queries/sch
import { BaseMathType, ChartDisplayType } from '~/types'
import { visionQuotaLogic } from '../../logics/visionQuotaLogic'
+import { projectQuota } from '../../utils/quotaProjection'
import { replayScannersLogic } from '../replayScannersLogic'
import { SCANNER_TYPE_OPTIONS, SCANNER_TYPE_TAG_TYPE, scannerTypeLabel } from '../types'
@@ -22,7 +23,10 @@ export function VisionMetrics(): JSX.Element {
const { quota } = useValues(visionQuotaLogic)
const ratio = quota && quota.monthly_quota > 0 ? Math.min(quota.usage_this_month / quota.monthly_quota, 1) : 0
- const quotaStroke = quota?.exhausted ? 'var(--danger)' : ratio >= 0.8 ? 'var(--warning)' : 'var(--success)'
+ const projection = projectQuota(quota)
+ const { status, capReachDate, capReachInPeriod, projectionConfident, resetsOn } = projection
+ const quotaStroke =
+ status === 'danger' ? 'var(--danger)' : status === 'warning' ? 'var(--warning)' : 'var(--success)'
// `tags.productKey` is required for ClickHouse query tagging; without it the runner aborts.
const chartSource: TrendsQuery = {
@@ -108,9 +112,21 @@ export function VisionMetrics(): JSX.Element {
/>
<div className="text-muted text-sm mt-1">
{quota.exhausted ? (
- <span className="text-danger">Quota reached</span>
+ <span className="text-danger">Quota reached.</span>
+ ) : capReachInPeriod && projectionConfident && capReachDate ? (
+ <span className="text-danger">
+ {quota.remaining.toLocaleString()} remaining. Cap reached on{' '}
+ <strong>{capReachDate.format('MMM D')}</strong> at this rate.
+ </span>
+ ) : status === 'warning' && projectionConfident ? (
+ <span className="text-warning">
+ {quota.remaining.toLocaleString()} remaining. Approaching cap by{' '}
+ {resetsOn ?? 'period end'} at this rate.
+ </span>
) : (
- `${quota.remaining.toLocaleString()} remaining`
+ `${quota.remaining.toLocaleString()} remaining${
+ resetsOn ? `. Resets ${resetsOn}.` : '.'
+ }`
)}
</div>
</>
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index 8cdfb0c1fb40..345a4ff18e9d 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -118,6 +118,69 @@ describe('replayScannerLogic', () => {
scanner_config: expect.objectContaining({ scale: expect.stringContaining('greater than') }),
},
},
+ {
+ name: 'flags scorer scale when min is not a finite number',
+ setup: () => {
+ logic.actions.setScannerType('scorer')
+ logic.actions.setScannerValues({
+ scanner_config: {
+ prompt: 'rate this',
+ scale: { min: Number.NaN, max: 10 },
+ } as ScorerScanner['scanner_config'],
+ })
+ },
+ expectedErrors: {
+ scanner_config: expect.objectContaining({ scale: expect.stringContaining('numbers') }),
+ },
+ },
+ {
+ name: 'flags classifier with empty tag vocabulary',
+ setup: () => {
+ logic.actions.setScannerType('classifier')
+ logic.actions.setScannerValues({
+ scanner_config: {
+ prompt: 'tag this',
+ tags: [],
+ multi_label: true,
+ } as ClassifierScanner['scanner_config'],
+ })
+ },
+ expectedErrors: {
+ scanner_config: expect.objectContaining({ tags: expect.stringContaining('at least one tag') }),
+ },
+ },
+ {
+ name: 'flags classifier with duplicate tags',
+ setup: () => {
+ logic.actions.setScannerType('classifier')
+ logic.actions.setScannerValues({
+ scanner_config: {
+ prompt: 'tag this',
+ tags: ['Bug', 'bug'],
+ multi_label: true,
+ } as ClassifierScanner['scanner_config'],
+ })
+ },
+ expectedErrors: {
+ scanner_config: expect.objectContaining({ tags: 'Tags must be unique' }),
+ },
+ },
+ {
+ name: 'flags classifier with blank/whitespace tags',
+ setup: () => {
+ logic.actions.setScannerType('classifier')
+ logic.actions.setScannerValues({
+ scanner_config: {
+ prompt: 'tag this',
+ tags: ['bug', ' '],
+ multi_label: true,
+ } as ClassifierScanner['scanner_config'],
+ })
+ },
+ expectedErrors: {
+ scanner_config: expect.objectContaining({ tags: "Tags can't be blank" }),
+ },
+ },
])('$name', async ({ setup, expectedErrors }) => {
setup()
await expectLogic(logic).toMatchValues({
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index 5d529e683850..863bdfd18910 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -224,9 +224,26 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
if (!scanner.scanner_config?.prompt?.trim()) {
configErrors.prompt = 'Prompt is required'
}
+ if (scanner.scanner_type === 'classifier') {
+ const tags = scanner.scanner_config.tags ?? []
+ if (tags.length === 0) {
+ configErrors.tags = 'Add at least one tag to the vocabulary'
+ } else if (tags.some((t) => !t.trim())) {
+ configErrors.tags = "Tags can't be blank"
+ } else if (new Set(tags.map((t) => t.trim().toLowerCase())).size !== tags.length) {
+ configErrors.tags = 'Tags must be unique'
+ }
+ }
if (scanner.scanner_type === 'scorer') {
const { min, max } = scanner.scanner_config.scale
- if (typeof min !== 'number' || typeof max !== 'number' || min >= max) {
+ if (
+ typeof min !== 'number' ||
+ typeof max !== 'number' ||
+ !Number.isFinite(min) ||
+ !Number.isFinite(max)
+ ) {
+ configErrors.scale = 'Scale min and max must be numbers'
+ } else if (min >= max) {
configErrors.scale = 'Scale max must be greater than min'
}
}
@@ -254,8 +271,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
await visionScannersPartialUpdate(String(teamId), props.id, scannerToPatchedApiBody(body))
lemonToast.success('Scanner saved')
}
- } catch (error) {
- lemonToast.error(`Failed to save scanner: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to save scanner${error.detail ? `: ${error.detail}` : ''}`)
throw error
}
},
@@ -517,7 +534,16 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
return {
loadScanner: async () => {
if (props.id === 'new') {
- actions.loadScannerSuccess(newScanner(currentTemplateKey()))
+ const templateKey = currentTemplateKey()
+ if (templateKey && !findScannerTemplate(templateKey)) {
+ // Unknown template (stale link, typo, renamed key). Strip it so the URL matches
+ // what the user actually gets: the from-scratch flow with a selectable type.
+ const { template: _drop, ...rest } = router.values.searchParams
+ router.actions.replace(router.values.location.pathname, rest)
+ actions.loadScannerSuccess(newScanner(null))
+ return
+ }
+ actions.loadScannerSuccess(newScanner(templateKey))
return
}
const teamId = teamLogic.values.currentTeamId
@@ -527,8 +553,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
try {
const response = await visionScannersRetrieve(String(teamId), props.id)
actions.loadScannerSuccess(scannerFromApi(response))
- } catch (error) {
- lemonToast.error(`Failed to load scanner: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to load scanner${error.detail ? `: ${error.detail}` : ''}`)
actions.loadScannerFailure()
router.actions.replace(urls.replayVision())
}
@@ -608,8 +634,8 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
await visionScannersDestroy(String(teamId), props.id)
lemonToast.success('Scanner deleted')
router.actions.replace(urls.replayVision())
- } catch (error) {
- lemonToast.error(`Failed to delete scanner: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to delete scanner${error.detail ? `: ${error.detail}` : ''}`)
}
},
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
index 4960a29746ed..ca8438bde043 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
@@ -281,8 +281,8 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
)
const response = await visionScannersList(String(teamId), params)
actions.loadScannersSuccess(scannersFromApi(response.results ?? []), response.count ?? 0)
- } catch (error) {
- lemonToast.error(`Failed to load scanners: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to load scanners${error.detail ? `: ${error.detail}` : ''}`)
actions.loadScannersFailure(String(error))
}
},
@@ -300,8 +300,8 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
await visionScannersDestroy(String(teamId), id)
actions.deleteScannerSuccess(id)
lemonToast.success('Scanner deleted')
- } catch (error) {
- lemonToast.error(`Failed to delete scanner: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to delete scanner${error.detail ? `: ${error.detail}` : ''}`)
}
},
@@ -331,8 +331,8 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
try {
const response = await visionScannersCreate(String(teamId), scannerToApiBody(duplicate))
actions.duplicateScannerSuccess(scannerFromApi(response))
- } catch (error) {
- lemonToast.error(`Failed to duplicate scanner: ${String(error)}`)
+ } catch (error: any) {
+ lemonToast.error(`Failed to duplicate scanner${error.detail ? `: ${error.detail}` : ''}`)
}
},
@@ -393,8 +393,9 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
try {
await visionScannersPartialUpdate(String(teamId), id, { enabled: scanner.enabled })
actions.toggleScannerEnabledDone(id)
- } catch (error) {
- lemonToast.error(`Failed to ${scanner.enabled ? 'enable' : 'disable'} scanner: ${String(error)}`)
+ } catch (error: any) {
+ const verb = scanner.enabled ? 'enable' : 'disable'
+ lemonToast.error(`Failed to ${verb} scanner${error.detail ? `: ${error.detail}` : ''}`)
actions.revertScannerEnabled(id)
}
},
diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
index b80a8918d297..c601e2274fa7 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
@@ -26,22 +26,22 @@ interface BaseTemplate {
scanner_description: string
}
-export interface MonitorTemplate extends BaseTemplate {
+interface MonitorTemplate extends BaseTemplate {
scanner_type: 'monitor'
scanner_config: MonitorScannerConfig
}
-export interface SummarizerTemplate extends BaseTemplate {
+interface SummarizerTemplate extends BaseTemplate {
scanner_type: 'summarizer'
scanner_config: SummarizerScannerConfig
}
-export interface ClassifierTemplate extends BaseTemplate {
+interface ClassifierTemplate extends BaseTemplate {
scanner_type: 'classifier'
scanner_config: ClassifierScannerConfig
}
-export interface ScorerTemplate extends BaseTemplate {
+interface ScorerTemplate extends BaseTemplate {
scanner_type: 'scorer'
scanner_config: ScorerScannerConfig
}
@@ -58,7 +58,7 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [
scanner_name: 'Dead-end pages',
scanner_description: 'Flag sessions where the user appears stuck with no obvious next action.',
scanner_config: {
- prompt: 'Answer `yes` if the user appears stuck on a page — scrolling without engaging, hovering over elements with no clear CTA, or abandoning the session shortly after arriving. Otherwise answer `no`.',
+ prompt: 'Answer yes if the user appears stuck on a page: scrolling without engaging, hovering over elements with no clear CTA, or abandoning the session shortly after arriving. Otherwise answer no.',
},
},
{
@@ -70,7 +70,7 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [
scanner_name: 'Session summary',
scanner_description: 'A short narrative summary of the session.',
scanner_config: {
- prompt: "Summarize what the user did in this session — which pages they visited, what they tried to accomplish, and any notable moments like errors, confusion, or successful completions. Be concrete and don't speculate.",
+ prompt: "Summarize what the user did in this session: which pages they visited, what they tried to accomplish, and any notable moments like errors, confusion, or successful completions. Be concrete and don't speculate.",
length: 'medium',
},
},
@@ -97,14 +97,14 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [
scanner_name: 'Frustration score',
scanner_description: 'Numeric score for how frustrated the user appeared.',
scanner_config: {
- prompt: 'Score how frustrated the user appeared during this session. 0 means a smooth session with no visible friction. 10 means clear, sustained frustration — rage clicks, repeated failures, abandonment. Use the full range; most sessions land somewhere in the middle.',
+ prompt: 'Score how frustrated the user appeared during this session. 0 means a smooth session with no visible friction. 10 means clear, sustained frustration: rage clicks, repeated failures, abandonment. Use the full range; most sessions land somewhere in the middle.',
scale: { min: 0, max: 10, label: 'frustration' },
},
},
{
key: 'session_outcome',
name: 'Session outcome',
- description: 'Tag each session with what actually happened — task completed, abandoned, errored, etc.',
+ description: 'Tag each session with what actually happened: task completed, abandoned, errored, etc.',
icon: 'check',
scanner_type: 'classifier',
scanner_name: 'Session outcome',
@@ -117,8 +117,6 @@ export const defaultScannerTemplates: readonly ScannerTemplate[] = [
},
] as const
-export type ScannerTemplateKey = (typeof defaultScannerTemplates)[number]['key']
-
export function findScannerTemplate(key: string | undefined): ScannerTemplate | undefined {
if (!key) {
return undefined
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
new file mode 100644
index 000000000000..dbb16eaa22b1
--- /dev/null
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -0,0 +1,76 @@
+import { dayjs } from 'lib/dayjs'
+
+import type { VisionQuotaApi } from '../generated/api.schemas'
+
+export const QUOTA_WARN_THRESHOLD = 0.8
+
+const MIN_DAYS_FOR_PROJECTED_DATE = 3
+
+export type QuotaStatus = 'safe' | 'warning' | 'danger'
+
+export interface QuotaProjection {
+ status: QuotaStatus
+ capReachDate: dayjs.Dayjs | null
+ capReachInPeriod: boolean
+ projectionConfident: boolean
+ projectedPeriodEndRatio: number
+ resetsOn: string | null
+ daysRemaining: number
+ combinedDailyRate: number
+}
+
+const EMPTY: QuotaProjection = {
+ status: 'safe',
+ capReachDate: null,
+ capReachInPeriod: false,
+ projectionConfident: false,
+ projectedPeriodEndRatio: 0,
+ resetsOn: null,
+ daysRemaining: 0,
+ combinedDailyRate: 0,
+}
+
+export function projectQuota(
+ quota: VisionQuotaApi | null,
+ scannerProjectedMonthly: number | null = null
+): QuotaProjection {
+ if (!quota || quota.monthly_quota <= 0) {
+ return EMPTY
+ }
+ const now = dayjs()
+ const used = quota.usage_this_month
+ const cap = quota.monthly_quota
+ const periodStart = quota.period_start ? dayjs(quota.period_start) : null
+ const periodEnd = quota.period_end ? dayjs(quota.period_end) : null
+ const periodLengthDays = periodStart && periodEnd ? Math.max(periodEnd.diff(periodStart, 'day', true), 1) : 30
+ const daysElapsed = periodStart ? Math.max(now.diff(periodStart, 'day', true), 0) : 0
+ const daysRemaining = periodEnd ? Math.max(periodEnd.diff(now, 'day', true), 0) : 0
+ const resetsOn = periodEnd ? periodEnd.format('MMM D') : null
+ const projectionConfident = daysElapsed >= MIN_DAYS_FOR_PROJECTED_DATE
+
+ const historicalDailyBurn = daysElapsed > 0 ? used / daysElapsed : 0
+ const scannerDailyRate = scannerProjectedMonthly !== null ? scannerProjectedMonthly / periodLengthDays : 0
+ const combinedDailyRate = historicalDailyBurn + scannerDailyRate
+
+ const projectedPeriodEndRatio = (used + combinedDailyRate * daysRemaining) / cap
+ const capReachDate = combinedDailyRate > 0 && used < cap ? now.add((cap - used) / combinedDailyRate, 'day') : null
+ const capReachInPeriod = !!(capReachDate && periodEnd && capReachDate.isBefore(periodEnd))
+
+ const status: QuotaStatus =
+ quota.exhausted || capReachInPeriod
+ ? 'danger'
+ : projectedPeriodEndRatio >= QUOTA_WARN_THRESHOLD
+ ? 'warning'
+ : 'safe'
+
+ return {
+ status,
+ capReachDate,
+ capReachInPeriod,
+ projectionConfident,
+ projectedPeriodEndRatio,
+ resetsOn,
+ daysRemaining,
+ combinedDailyRate,
+ }
+}