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.

fix(replay-vision): frontend review hardening and cleanups (#67862)

Tue Haulundcf5ab897b19b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index f40f33d2c394..6af2962ee415 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6477,9 +6477,9 @@ snapshots:
scenes-app-project-homepage--project-homepage--light:
hash: v1.k794b7964.853928313ecadc1d9daf77ddf3779f4dc42c14853b28ed9bb91dffeb5a751bbf.knbN_bMGgzgR-EoNShaqPQYhnEiWBS7_pLFWcxnka7c
scenes-app-replay-vision--scanners-list--dark:
- hash: v1.k794b7964.18d0f4374bc33987c44b9031922083edb437962bb0319bd85b0f7cde37a11785.oRgKtdkiYWoeNHhBM4RxGUrhNkKHUh_nRKoMzqvzElQ
+ hash: v1.k794b7964.0e18ee716502a431a1b52f43413ecca3b2b40bb96172279d0e9e557f87ac6c61.Qq-IoYFbMhHW5FkdNyVTkhx5vf_g_4fowvmyQtcO8p4
scenes-app-replay-vision--scanners-list--light:
- hash: v1.k794b7964.b4caab62832b3dca68fab26706b6b5d5400d9c3bfec541208abafaf7149d1fff.OjknJo2mzTQoY9nTQ4kHd3khj92vcfwH9k2AmK-ZYd4
+ hash: v1.k794b7964.4ed251f572c8b0ac15ef5b55ed2c7d5a761d3392c909ce9a0216b981e334533b.IBCp1Avvb7JrPFIgzIwNz-NEHgR6cqfD6i0u5ljSlyw
scenes-app-revenue-analytics--revenue-analytics-dashboard--dark:
hash: v1.k794b7964.cdf9e00b28b52b4abf4d161b3593a7b9c7616df14c78ca1022f1b452ec98a628.oC6MqWeOLr6BAEuVc3MgKwPcv6ThL0vJfwRXWrfqH5g
scenes-app-revenue-analytics--revenue-analytics-dashboard--light:
diff --git a/products/replay_vision/frontend/components/LabeledRow.tsx b/products/replay_vision/frontend/components/LabeledRow.tsx
new file mode 100644
index 000000000000..f145b15746e4
--- /dev/null
+++ b/products/replay_vision/frontend/components/LabeledRow.tsx
@@ -0,0 +1,9 @@
+/** A label-above-content row used across the readonly config and observation detail cards. */
+export function LabeledRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
+ return (
+ <div>
+ <div className="text-xs text-muted mb-0.5">{label}</div>
+ <div className="text-sm">{children}</div>
+ </div>
+ )
+}
diff --git a/products/replay_vision/frontend/components/ObservationCard.tsx b/products/replay_vision/frontend/components/ObservationCard.tsx
index 72d34f025a78..bd65105a4761 100644
--- a/products/replay_vision/frontend/components/ObservationCard.tsx
+++ b/products/replay_vision/frontend/components/ObservationCard.tsx
@@ -4,8 +4,11 @@ import { LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
import { colonDelimitedDuration } from 'lib/utils/durations'
import { urls } from 'scenes/urls'
-import type { ReplayObservationApi, ScannerSnapshotApi } from '../generated/api.schemas'
+import type { ReplayObservationApi } from '../generated/api.schemas'
import {
+ type ClassifierScannerConfig,
+ type ScorerScannerConfig,
+ configFromSnapshot,
failureKindDescription,
ineligibleKindDescription,
parseFailureReason,
@@ -66,8 +69,7 @@ export function readResult(observation: ReplayObservationApi): Record<string, un
return output && typeof output === 'object' ? (output as Record<string, unknown>) : null
}
-// `uuid` is legacy: timestamp citations only carry `timestamp_ms`, but observations stored under the
-// old event-uuid citations still have it, so it's optional and otherwise ignored.
+// `uuid` is legacy — only old event-uuid citations carry it; timestamp citations use `timestamp_ms` alone.
type Segment = { kind: 'text'; value: string } | { kind: 'chip'; timestamp_ms: number; uuid?: string }
function isSegment(value: unknown): value is Segment {
@@ -125,11 +127,6 @@ export function CitedText({
)
}
-export function readConfig(snapshot: ScannerSnapshotApi | null): Record<string, unknown> {
- const config = snapshot?.scanner_config
- return config && typeof config === 'object' ? (config as Record<string, unknown>) : {}
-}
-
export function ObservationPrimaryOutput({
observation,
compact = false,
@@ -151,8 +148,8 @@ export function ObservationPrimaryOutput({
return null
}
const scannerType = snapshot.scanner_type
- const config = readConfig(snapshot)
- const prompt = showPrompt && typeof config.prompt === 'string' ? config.prompt : null
+ const config = configFromSnapshot(snapshot)
+ const prompt = showPrompt ? (config?.prompt ?? null) : null
const summaryClass = expandSummary ? 'text-sm whitespace-pre-wrap' : compact ? 'text-sm truncate' : 'text-sm'
const bodyClass = compact ? 'text-sm truncate' : 'text-sm'
const promptClass = 'text-xs text-muted'
@@ -198,15 +195,16 @@ export function ObservationPrimaryOutput({
if (scannerType === 'classifier') {
const fixedTags = Array.isArray(result.tags) ? (result.tags as string[]) : []
const freeformTags = Array.isArray(result.tags_freeform) ? (result.tags_freeform as string[]) : []
- const configuredTags = Array.isArray(config.tags) ? (config.tags as string[]) : []
+ const classifierConfig = config as ClassifierScannerConfig | null
+ const configuredTags = Array.isArray(classifierConfig?.tags) ? classifierConfig.tags : []
const chosen = new Set(fixedTags)
const empty = fixedTags.length === 0 && freeformTags.length === 0
const renderVocab = (): JSX.Element[] =>
- configuredTags.map((tag) => {
+ configuredTags.map((tag, index) => {
const isChosen = chosen.has(tag)
return (
<LemonTag
- key={`fixed-${tag}`}
+ key={`fixed-${index}-${tag}`}
size="medium"
type={isChosen ? 'option' : 'default'}
className={isChosen ? undefined : 'opacity-50 line-through'}
@@ -216,8 +214,8 @@ export function ObservationPrimaryOutput({
)
})
const renderFreeform = (): JSX.Element[] =>
- freeformTags.map((tag) => (
- <LemonTag key={`freeform-${tag}`} size="medium" type="default" icon={<IconSparkles />}>
+ freeformTags.map((tag, index) => (
+ <LemonTag key={`freeform-${index}-${tag}`} size="medium" type="default" icon={<IconSparkles />}>
{tag}
</LemonTag>
))
@@ -229,8 +227,8 @@ export function ObservationPrimaryOutput({
<span className="text-muted text-sm">No tags</span>
) : (
<>
- {fixedTags.map((tag) => (
- <LemonTag key={`fixed-${tag}`} size="medium" type="option">
+ {fixedTags.map((tag, index) => (
+ <LemonTag key={`fixed-${index}-${tag}`} size="medium" type="option">
{tag}
</LemonTag>
))}
@@ -264,10 +262,9 @@ export function ObservationPrimaryOutput({
if (scannerType === 'scorer') {
const score = typeof result.score === 'number' ? result.score : null
const resultLabel = typeof result.label === 'string' ? result.label : null
- const scale =
- config.scale && typeof config.scale === 'object' ? (config.scale as Record<string, unknown>) : null
- const scaleMax = scale && typeof scale.max === 'number' ? scale.max : null
- const scaleLabel = scale && typeof scale.label === 'string' ? scale.label : null
+ const scale = (config as ScorerScannerConfig | null)?.scale ?? null
+ const scaleMax = typeof scale?.max === 'number' ? scale.max : null
+ const scaleLabel = typeof scale?.label === 'string' ? scale.label : null
// Prefer the per-observation label (specific); fall back to the configured scale label (axis name).
const displayLabel = resultLabel ?? scaleLabel
return (
@@ -374,10 +371,6 @@ export function IneligibleDetail({ errorReason }: { errorReason: string }): JSX.
)
}
-function ObservationProgress({ observation }: { observation: ReplayObservationApi }): JSX.Element {
- return <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} compact />
-}
-
export function ObservationDockCard({
observation,
onSeek,
@@ -415,7 +408,7 @@ export function ObservationDockCard({
)}
{(observation.status === 'pending' || observation.status === 'running') && (
- <ObservationProgress observation={observation} />
+ <ObservationProgressBar observationId={observation.id} sessionId={observation.session_id} compact />
)}
</div>
)
diff --git a/products/replay_vision/frontend/components/ObservationProgressBar.tsx b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
index c7f0c9431d55..874b7dd1da29 100644
--- a/products/replay_vision/frontend/components/ObservationProgressBar.tsx
+++ b/products/replay_vision/frontend/components/ObservationProgressBar.tsx
@@ -1,9 +1,10 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { useRef } from 'react'
-import { IconCheckCircle, IconCircleDashed } from '@posthog/icons'
+import { IconCheckCircle, IconCircleDashed, IconWarning } from '@posthog/icons'
import { Spinner } from '@posthog/lemon-ui'
+import { useOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { usePeriodicRerender } from 'lib/hooks/usePeriodicRerender'
import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
@@ -22,8 +23,7 @@ const PHASE_LABELS: Record<Phase, string> = {
finalizing: 'Finalizing',
}
-// Rough per-phase time constants (seconds) driving an asymptotic fill for phases without real sub-progress, so the
-// bar keeps moving. At elapsed = tau the fill is ~63%; at 2*tau ~86%; never reaches 100% until the phase advances.
+// Per-phase time constants (seconds) for an asymptotic fill (~63% at tau, ~86% at 2*tau) so the bar keeps moving.
const PHASE_TAU_S: Record<Phase, number> = {
queued: 4,
fetching: 4,
@@ -70,9 +70,13 @@ export function ObservationProgressBar({
sessionId: string
compact?: boolean
}): JSX.Element {
- const { progress } = useValues(observationProgressLogic({ observationId, sessionId }))
+ const { progress, streamError } = useValues(observationProgressLogic({ observationId, sessionId }))
+ const { startStream } = useActions(observationProgressLogic({ observationId, sessionId }))
usePeriodicRerender(1000)
+ // The bar only renders for in-flight observations, so its mount is the signal to open the stream.
+ useOnMountEffect(() => startStream())
+
const currentStep = Math.min(progress?.step ?? 0, PHASE_ORDER.length - 1)
const activePhase = PHASE_ORDER[currentStep]
@@ -90,6 +94,16 @@ export function ObservationProgressBar({
? Math.min((frame.frame / frame.estimatedTotalFrames) * 100, 100)
: asymptoticFillPercent(activeElapsed, PHASE_TAU_S[activePhase])
+ if (streamError) {
+ // The stream died but the observation may still be running — status polling keeps the page truthful.
+ return (
+ <div className="flex items-center gap-2 text-muted text-sm">
+ <IconWarning className="text-warning text-base shrink-0" />
+ <span>Live progress unavailable: {streamError}</span>
+ </div>
+ )
+ }
+
if (compact) {
const detail =
frame && frame.estimatedTotalFrames > 0 ? ` (${frame.frame} / ${frame.estimatedTotalFrames} frames)` : ''
diff --git a/products/replay_vision/frontend/logics/bulkScanLogic.test.ts b/products/replay_vision/frontend/logics/bulkScanLogic.test.ts
new file mode 100644
index 000000000000..5682c353f7a2
--- /dev/null
+++ b/products/replay_vision/frontend/logics/bulkScanLogic.test.ts
@@ -0,0 +1,85 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { bulkScanLogic } from './bulkScanLogic'
+
+describe('bulkScanLogic', () => {
+ let logic: ReturnType<typeof bulkScanLogic.build>
+ let observeSpy: jest.Mock
+ let successToast: jest.SpyInstance
+ let errorToast: jest.SpyInstance
+
+ const sessionIds = (n: number): string[] => Array.from({ length: n }, (_, i) => `session-${i + 1}`)
+
+ beforeEach(() => {
+ observeSpy = jest.fn(() => [202, { workflow_id: 'wf-test' }])
+ useMocks({
+ get: {
+ '/api/projects/:team/vision/scanners/': {
+ results: [{ id: 'scanner-1', name: 'Rage detector' }],
+ count: 1,
+ next: null,
+ },
+ },
+ post: {
+ '/api/projects/:team/vision/scanners/:id/observe/': observeSpy,
+ },
+ })
+ initKeaTests()
+ successToast = jest.spyOn(lemonToast, 'success').mockImplementation(() => 'toast-id')
+ errorToast = jest.spyOn(lemonToast, 'error').mockImplementation(() => 'toast-id')
+ logic = bulkScanLogic()
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ jest.restoreAllMocks()
+ })
+
+ it('scans every selected recording and toasts the started count with the scanner name', async () => {
+ await expectLogic(logic, () => logic.actions.scanRecordings('scanner-1', sessionIds(3)))
+ .toDispatchActions(['scanRecordings', 'scanRecordingsSuccess'])
+ .toMatchValues({ scanning: false })
+ expect(observeSpy).toHaveBeenCalledTimes(3)
+ expect(successToast.mock.calls[0][0]).toContain('Started scanning 3 recordings with “Rage detector”')
+ expect(errorToast).not.toHaveBeenCalled()
+ })
+
+ it('stops after the batch that hits a 402 and reports the skipped remainder', async () => {
+ observeSpy.mockImplementation(() =>
+ observeSpy.mock.calls.length === 10
+ ? [402, { detail: 'Monthly quota reached.' }]
+ : [202, { workflow_id: 'wf-test' }]
+ )
+ await expectLogic(logic, () => logic.actions.scanRecordings('scanner-1', sessionIds(25)))
+ .toDispatchActions(['scanRecordingsSuccess'])
+ .toMatchValues({ scanning: false })
+ // Only the first batch of 10 fires; the remaining 15 are skipped, not attempted.
+ expect(observeSpy).toHaveBeenCalledTimes(10)
+ expect(successToast.mock.calls[0][0]).toContain('Started scanning 9 recordings')
+ expect(errorToast.mock.calls[0][0]).toBe('Monthly quota reached. Skipped 15 remaining recordings.')
+ })
+
+ it('continues through all batches on non-quota failures and surfaces the first error detail', async () => {
+ observeSpy.mockImplementation(() => [500, { detail: 'boom' }])
+ await expectLogic(logic, () => logic.actions.scanRecordings('scanner-1', sessionIds(12)))
+ .toDispatchActions(['scanRecordingsSuccess'])
+ .toMatchValues({ scanning: false })
+ expect(observeSpy).toHaveBeenCalledTimes(12)
+ expect(successToast).not.toHaveBeenCalled()
+ expect(errorToast.mock.calls[0][0]).toBe('Failed to start scanning 12 recordings: boom')
+ })
+
+ it('rejects an empty selection without any requests', async () => {
+ await expectLogic(logic, () => logic.actions.scanRecordings('scanner-1', []))
+ .toDispatchActions(['scanRecordingsFailure'])
+ .toMatchValues({ scanning: false })
+ expect(observeSpy).not.toHaveBeenCalled()
+ expect(errorToast.mock.calls[0][0]).toBe('Select at least one recording to scan')
+ })
+})
diff --git a/products/replay_vision/frontend/logics/bulkScanLogic.ts b/products/replay_vision/frontend/logics/bulkScanLogic.ts
index 238487b3ef43..4ea1688e30e2 100644
--- a/products/replay_vision/frontend/logics/bulkScanLogic.ts
+++ b/products/replay_vision/frontend/logics/bulkScanLogic.ts
@@ -1,20 +1,24 @@
-import { actions, afterMount, connect, kea, listeners, path, reducers } from 'kea'
-import { loaders } from 'kea-loaders'
+import { actions, connect, kea, listeners, path, reducers } from 'kea'
import { router } from 'kea-router'
+import { ApiError } from 'lib/api-error'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
-import { visionScannersList, visionScannersObserveCreate } from '../generated/api'
-import type { ReplayScannerApi } from '../generated/api.schemas'
+import { visionScannersObserveCreate } from '../generated/api'
import type { bulkScanLogicType } from './bulkScanLogicType'
+import { refreshVisionQuota } from './visionQuotaLogic'
+import { visionScannersListLogic } from './visionScannersListLogic'
+
+// Caps simultaneous workflow-start requests; the batches run sequentially.
+const BULK_SCAN_CONCURRENCY = 10
export const bulkScanLogic = kea<bulkScanLogicType>([
path(['products', 'replay_vision', 'frontend', 'logics', 'bulkScanLogic']),
connect(() => ({
- actions: [teamLogic, ['loadCurrentTeamSuccess']],
+ values: [visionScannersListLogic, ['scanners', 'scannersLoading']],
})),
actions({
@@ -23,26 +27,6 @@ export const bulkScanLogic = kea<bulkScanLogicType>([
scanRecordingsFailure: true,
}),
- loaders({
- scanners: [
- [] as ReplayScannerApi[],
- {
- loadScanners: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return []
- }
- try {
- const response = await visionScannersList(String(teamId))
- return response.results ?? []
- } catch {
- return []
- }
- },
- },
- ],
- }),
-
reducers({
scanning: [
false,
@@ -66,16 +50,36 @@ export const bulkScanLogic = kea<bulkScanLogicType>([
actions.scanRecordingsFailure()
return
}
- // The backend keys the workflow on (scanner, session) and silently no-ops duplicates,
- // so re-running the same pair is safe and needs no client-side dedup.
- const results = await Promise.allSettled(
- sessionIds.map((session_id) => visionScannersObserveCreate(String(teamId), scannerId, { session_id }))
- )
- const failed = results.filter((r) => r.status === 'rejected').length
- const started = results.length - failed
+ // The backend keys the workflow on (scanner, session) and no-ops duplicates, so no client-side dedup.
+ let started = 0
+ let failed = 0
+ let firstError: ApiError | null = null
+ let quotaError: ApiError | null = null
+ // Batched so selecting hundreds of recordings doesn't fire hundreds of simultaneous workflow starts.
+ for (let i = 0; i < sessionIds.length && !quotaError; i += BULK_SCAN_CONCURRENCY) {
+ const batch = sessionIds.slice(i, i + BULK_SCAN_CONCURRENCY)
+ const results = await Promise.allSettled(
+ batch.map((session_id) => visionScannersObserveCreate(String(teamId), scannerId, { session_id }))
+ )
+ for (const result of results) {
+ if (result.status === 'fulfilled') {
+ started += 1
+ continue
+ }
+ failed += 1
+ if (result.reason instanceof ApiError) {
+ firstError = firstError ?? result.reason
+ if (result.reason.status === 402) {
+ quotaError = result.reason // Quota is org-wide — the rest of the batch would 402 too.
+ }
+ }
+ }
+ }
+ const skipped = sessionIds.length - started - failed
const scannerName = values.scanners.find((s) => s.id === scannerId)?.name ?? 'scanner'
if (started > 0) {
+ refreshVisionQuota()
lemonToast.success(
`Started scanning ${started} recording${started === 1 ? '' : 's'} with “${scannerName}”`,
{
@@ -87,19 +91,17 @@ export const bulkScanLogic = kea<bulkScanLogicType>([
}
)
}
- if (failed > 0) {
- lemonToast.error(`Failed to start scanning ${failed} recording${failed === 1 ? '' : 's'}`)
+ if (quotaError) {
+ const detail = quotaError.detail ?? 'Monthly Replay Vision quota reached.'
+ lemonToast.error(skipped > 0 ? `${detail} Skipped ${skipped} remaining recordings.` : detail)
+ } else if (failed > 0) {
+ lemonToast.error(
+ `Failed to start scanning ${failed} recording${failed === 1 ? '' : 's'}${
+ firstError?.detail ? `: ${firstError.detail}` : ''
+ }`
+ )
}
actions.scanRecordingsSuccess()
},
- // The logic is global/propless, so reload scanners when the active team changes
- // to avoid POSTing the previous team's scanner IDs to the new team's endpoint.
- loadCurrentTeamSuccess: () => {
- actions.loadScanners()
- },
})),
-
- afterMount(({ actions }) => {
- actions.loadScanners()
- }),
])
diff --git a/products/replay_vision/frontend/logics/observationPolling.ts b/products/replay_vision/frontend/logics/observationPolling.ts
index 3883916402fe..7b1c8085f3a0 100644
--- a/products/replay_vision/frontend/logics/observationPolling.ts
+++ b/products/replay_vision/frontend/logics/observationPolling.ts
@@ -24,3 +24,10 @@ export function scheduleObservationPoll(
disposables.dispose(POLL_KEY)
}
}
+
+// Observe only starts the workflow — poll through this grace window so the new card appears before its row lands.
+export const OBSERVE_POLL_GRACE_MS = 30_000
+
+export function shouldPollObservations(hasInFlight: boolean, pollUntil: number): boolean {
+ return hasInFlight || Date.now() < pollUntil
+}
diff --git a/products/replay_vision/frontend/logics/observationsDockLogic.ts b/products/replay_vision/frontend/logics/observationsDockLogic.ts
index 98fd5863cc38..3862abd710b4 100644
--- a/products/replay_vision/frontend/logics/observationsDockLogic.ts
+++ b/products/replay_vision/frontend/logics/observationsDockLogic.ts
@@ -1,16 +1,14 @@
-import { actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { teamLogic } from 'scenes/teamLogic'
-import { visionScannersList, visionScannersObserveCreate, visionObservationsList } from '../generated/api'
+import { visionScannersObserveCreate, visionObservationsList } from '../generated/api'
import type { ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'
-import { scheduleObservationPoll } from './observationPolling'
+import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from './observationPolling'
import type { observationsDockLogicType } from './observationsDockLogicType'
-
-// The observe endpoint only starts the workflow; its row is created a moment later. Keep polling
-// for this window after an observe so the new card appears even before anything reports in flight.
-const OBSERVE_POLL_GRACE_MS = 30000
+import { refreshVisionQuota } from './visionQuotaLogic'
+import { visionScannersListLogic } from './visionScannersListLogic'
export interface ObservationsDockLogicProps {
sessionId: string
@@ -21,13 +19,15 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
props({} as ObservationsDockLogicProps),
key((props) => props.sessionId),
+ connect(() => ({
+ // The scanner list is team-wide — shared so per-recording dock instances don't each refetch it.
+ values: [visionScannersListLogic, ['scanners']],
+ })),
+
actions({
loadObservations: true,
loadObservationsSuccess: (observations: ReplayObservationApi[]) => ({ observations }),
loadObservationsFailure: true,
- loadScanners: true,
- loadScannersSuccess: (scanners: ReplayScannerApi[]) => ({ scanners }),
- loadScannersFailure: true,
observe: (scannerId: string) => ({ scannerId }),
observeSuccess: true,
observeFailure: true,
@@ -51,12 +51,6 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
loadObservationsFailure: () => false,
},
],
- scanners: [
- [] as ReplayScannerApi[],
- {
- loadScannersSuccess: (_, { scanners }) => scanners,
- },
- ],
observing: [
false,
{
@@ -108,71 +102,63 @@ export const observationsDockLogic = kea<observationsDockLogicType>([
],
}),
- listeners(({ actions, props, values, cache }) => ({
- loadObservations: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- const response = await visionObservationsList(String(teamId), { session_id: props.sessionId })
- actions.loadObservationsSuccess(response.results ?? [])
- } catch {
- actions.loadObservationsFailure()
- }
- },
-
- loadObservationsSuccess: () => {
- // Poll while work is in flight, and through the grace window after an observe.
+ listeners(({ actions, props, values, cache }) => {
+ const reschedulePoll = (): void => {
scheduleObservationPoll(
cache.disposables,
- values.hasObservationsInFlight || Date.now() < values.pollUntil,
+ shouldPollObservations(values.hasObservationsInFlight, values.pollUntil),
actions.loadObservations
)
- },
+ }
+ return {
+ loadObservations: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.loadObservationsFailure() // Clear the loading flag; a bare return spins forever.
+ return
+ }
+ try {
+ const response = await visionObservationsList(String(teamId), { session_id: props.sessionId })
+ actions.loadObservationsSuccess(response.results ?? [])
+ } catch {
+ actions.loadObservationsFailure()
+ }
+ },
- loadScanners: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- const response = await visionScannersList(String(teamId))
- actions.loadScannersSuccess(response.results ?? [])
- } catch {
- actions.loadScannersFailure()
- }
- },
+ // Poll while in flight and through the observe grace window; rescheduled on failure so one hiccup can't kill it.
+ loadObservationsSuccess: reschedulePoll,
+ loadObservationsFailure: reschedulePoll,
- observe: async ({ scannerId }) => {
- actions.setScannerPickerOpen(false)
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- actions.observeFailure()
- return
- }
- // Backend keys the workflow id on (scanner, session); re-triggering the same pair silently no-ops.
- if (values.observations.some((o) => o.scanner_id === scannerId)) {
- lemonToast.info('This scanner has already been run on this recording.')
- actions.observeFailure()
- actions.setDockOpen(true)
- return
- }
- try {
- await visionScannersObserveCreate(String(teamId), scannerId, { session_id: props.sessionId })
- lemonToast.success('Observation started')
- actions.observeSuccess()
- actions.setDockOpen(true)
- actions.loadObservations()
- } catch (error: any) {
- lemonToast.error(`Failed to start observation${error.detail ? `: ${error.detail}` : ''}`)
- actions.observeFailure()
- }
- },
- })),
+ observe: async ({ scannerId }) => {
+ actions.setScannerPickerOpen(false)
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ actions.observeFailure()
+ return
+ }
+ // Backend keys the workflow id on (scanner, session); re-triggering the same pair silently no-ops.
+ if (values.observations.some((o) => o.scanner_id === scannerId)) {
+ lemonToast.info('This scanner has already been run on this recording.')
+ actions.observeFailure()
+ actions.setDockOpen(true)
+ return
+ }
+ try {
+ await visionScannersObserveCreate(String(teamId), scannerId, { session_id: props.sessionId })
+ lemonToast.success('Observation started')
+ actions.observeSuccess()
+ actions.setDockOpen(true)
+ actions.loadObservations()
+ refreshVisionQuota()
+ } catch (error: any) {
+ lemonToast.error(`Failed to start observation${error.detail ? `: ${error.detail}` : ''}`)
+ actions.observeFailure()
+ }
+ },
+ }
+ }),
afterMount(({ actions }) => {
actions.loadObservations()
- actions.loadScanners()
}),
])
diff --git a/products/replay_vision/frontend/logics/visionQuotaLogic.ts b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
index bad08b4a668b..cd42e3f76ee7 100644
--- a/products/replay_vision/frontend/logics/visionQuotaLogic.ts
+++ b/products/replay_vision/frontend/logics/visionQuotaLogic.ts
@@ -17,7 +17,7 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
adjustProjectedMonthly: (delta: number) => ({ delta }),
}),
- loaders({
+ loaders(({ values }) => ({
quota: [
null as VisionQuotaApi | null,
{
@@ -26,17 +26,18 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
await breakpoint(50)
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
- return null
+ return values.quota
}
try {
return await environmentVisionQuotaRetrieve(String(teamId))
} catch {
- return null
+ // Keep the last-known snapshot — nulling it would silently drop the exhausted-quota guards.
+ return values.quota
}
},
},
],
- }),
+ })),
reducers({
quota: {
@@ -54,3 +55,8 @@ export const visionQuotaLogic = kea<visionQuotaLogicType>([
actions.loadQuota()
}),
])
+
+/** Refresh after any quota-affecting mutation — observes consume quota immediately (in-flight rows count). */
+export function refreshVisionQuota(): void {
+ visionQuotaLogic.findMounted()?.actions.loadQuota()
+}
diff --git a/products/replay_vision/frontend/logics/visionScannersListLogic.ts b/products/replay_vision/frontend/logics/visionScannersListLogic.ts
new file mode 100644
index 000000000000..fba68d0b1057
--- /dev/null
+++ b/products/replay_vision/frontend/logics/visionScannersListLogic.ts
@@ -0,0 +1,71 @@
+import { actions, afterMount, connect, isBreakpoint, kea, listeners, path } from 'kea'
+import { loaders } from 'kea-loaders'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { visionScannersList } from '../generated/api'
+import type { ReplayScannerApi } from '../generated/api.schemas'
+import type { visionScannersListLogicType } from './visionScannersListLogicType'
+
+const PAGE_LIMIT = 100
+
+/** The team's full scanner list for pickers — shared and propless so each surface doesn't refetch its own copy. */
+export const visionScannersListLogic = kea<visionScannersListLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'logics', 'visionScannersListLogic']),
+
+ connect(() => ({
+ actions: [teamLogic, ['loadCurrentTeamSuccess']],
+ })),
+
+ actions({
+ // Declared here so the action stays zero-arg despite the loader's `breakpoint` parameter.
+ loadScanners: true,
+ }),
+
+ loaders(({ values }) => ({
+ scanners: [
+ [] as ReplayScannerApi[],
+ {
+ loadScanners: async (_, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return []
+ }
+ try {
+ // Follow pagination so pickers never silently truncate past the server page size.
+ const all: ReplayScannerApi[] = []
+ let offset = 0
+ for (;;) {
+ const response = await visionScannersList(String(teamId), {
+ limit: PAGE_LIMIT,
+ offset,
+ })
+ // Cancel superseded loops (e.g. team switch) so a stale multi-page fetch can't win.
+ breakpoint()
+ const results = response.results ?? []
+ all.push(...results)
+ if (!response.next || results.length === 0) {
+ return all
+ }
+ offset += results.length
+ }
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
+ return values.scanners
+ }
+ },
+ },
+ ],
+ })),
+
+ listeners(({ actions }) => ({
+ // Propless/global — reload on team switch so a stale list can't offer another team's scanner ids.
+ loadCurrentTeamSuccess: () => actions.loadScanners(),
+ })),
+
+ afterMount(({ actions }) => {
+ actions.loadScanners()
+ }),
+])
diff --git a/products/replay_vision/frontend/observations/ReplayObservation.tsx b/products/replay_vision/frontend/observations/ReplayObservation.tsx
index c2cc35834d1c..ba3d8fa50c5e 100644
--- a/products/replay_vision/frontend/observations/ReplayObservation.tsx
+++ b/products/replay_vision/frontend/observations/ReplayObservation.tsx
@@ -19,6 +19,7 @@ import { TZLabel } from 'lib/components/TZLabel'
import { dayjs } from 'lib/dayjs'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
+import { humanFriendlyDuration, humanFriendlyMilliseconds } from 'lib/utils/durations'
import { SceneExport } from 'scenes/sceneTypes'
import { SessionRecordingPlayer } from 'scenes/session-recordings/player/SessionRecordingPlayer'
import {
@@ -33,18 +34,23 @@ import { ProductKey } from '~/queries/schema/schema-general'
import { BooleanTag } from '../components/BooleanTag'
import { CardHeader } from '../components/CardHeader'
+import { LabeledRow } from '../components/LabeledRow'
import {
CitedText,
ObservationConfidence,
ObservationPrimaryOutput,
ObservationStatusTag,
- readConfig,
readResult,
} from '../components/ObservationCard'
import { ObservationProgressBar } from '../components/ObservationProgressBar'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { ScannerTypeBadge } from '../components/ScannerTypeBadge'
import {
+ type ClassifierScannerConfig,
+ type MonitorScannerConfig,
+ type ScorerScannerConfig,
+ type SummarizerScannerConfig,
+ configFromSnapshot,
failureKindDescription,
ineligibleKindDescription,
modelLabel,
@@ -68,15 +74,6 @@ const SUCCEEDED_OUTPUT_LABEL: Record<ScannerType, string> = {
scorer: 'Score',
}
-function LabeledRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
- return (
- <div className="flex flex-col gap-1">
- <div className="text-xs text-muted">{label}</div>
- {children}
- </div>
- )
-}
-
function AutoSeekToTime({
playerKey,
sessionRecordingId,
@@ -109,6 +106,11 @@ export function ReplayObservationSceneComponent(): JSX.Element {
const [recordingExpanded, setRecordingExpanded] = useState(true)
const [pendingSeek, setPendingSeek] = useState<{ ms: number; trigger: number } | null>(null)
+ // A citation seek belongs to one observation — never replay it on a sibling after prev/next navigation.
+ useEffect(() => {
+ setPendingSeek(null)
+ }, [observationId])
+
const observationLogic = replayObservationLogic({ id: observationId })
useAttachedLogic(observationLogic, replayObservationSceneLogic)
@@ -141,24 +143,20 @@ export function ReplayObservationSceneComponent(): JSX.Element {
const scannerType = snapshot?.scanner_type
const scannerName = snapshot?.name || 'Scanner'
const triggerLabel = observation.triggered_by === 'on_demand' ? 'On demand' : 'Schedule'
- const snapshotConfig = readConfig(snapshot ?? null)
- const prompt = typeof snapshotConfig.prompt === 'string' ? snapshotConfig.prompt : null
- const summarizerLength =
- scannerType === 'summarizer' && typeof snapshotConfig.length === 'string' ? snapshotConfig.length : null
- const classifierVocab =
- scannerType === 'classifier' && Array.isArray(snapshotConfig.tags)
- ? (snapshotConfig.tags as unknown[]).filter((t): t is string => typeof t === 'string')
- : null
- const classifierMultiLabel = scannerType === 'classifier' ? snapshotConfig.multi_label === true : null
- const monitorAllowInconclusive = scannerType === 'monitor' ? snapshotConfig.allow_inconclusive === true : null
- const classifierAllowFreeform = scannerType === 'classifier' ? snapshotConfig.allow_freeform_tags === true : null
- const scorerScale =
- scannerType === 'scorer' && snapshotConfig.scale && typeof snapshotConfig.scale === 'object'
- ? (snapshotConfig.scale as { min?: unknown; max?: unknown; label?: unknown })
- : null
- const scorerMin = scorerScale && typeof scorerScale.min === 'number' ? scorerScale.min : null
- const scorerMax = scorerScale && typeof scorerScale.max === 'number' ? scorerScale.max : null
- const scorerLabel = scorerScale && typeof scorerScale.label === 'string' ? scorerScale.label : null
+ const snapshotConfig = configFromSnapshot(snapshot)
+ const prompt = snapshotConfig?.prompt ?? null
+ const summarizerConfig = scannerType === 'summarizer' ? (snapshotConfig as SummarizerScannerConfig | null) : null
+ const classifierConfig = scannerType === 'classifier' ? (snapshotConfig as ClassifierScannerConfig | null) : null
+ const monitorConfig = scannerType === 'monitor' ? (snapshotConfig as MonitorScannerConfig | null) : null
+ const scorerConfig = scannerType === 'scorer' ? (snapshotConfig as ScorerScannerConfig | null) : null
+ const summarizerLength = summarizerConfig?.length ?? null
+ const classifierVocab = Array.isArray(classifierConfig?.tags) ? classifierConfig.tags : null
+ const classifierMultiLabel = classifierConfig ? classifierConfig.multi_label === true : null
+ const monitorAllowInconclusive = monitorConfig ? monitorConfig.allow_inconclusive === true : null
+ const classifierAllowFreeform = classifierConfig ? classifierConfig.allow_freeform_tags === true : null
+ const scorerMin = typeof scorerConfig?.scale?.min === 'number' ? scorerConfig.scale.min : null
+ const scorerMax = typeof scorerConfig?.scale?.max === 'number' ? scorerConfig.scale.max : null
+ const scorerLabel = typeof scorerConfig?.scale?.label === 'string' ? scorerConfig.scale.label : null
const ineligibleParsed =
observation.status === 'ineligible' && observation.error_reason
? parseIneligibleReason(observation.error_reason)
@@ -175,11 +173,9 @@ export function ReplayObservationSceneComponent(): JSX.Element {
: null
const durationLabel =
durationMs !== null && Number.isFinite(durationMs) && durationMs >= 0
- ? durationMs < 1000
- ? `${durationMs} ms`
- : durationMs < 60_000
- ? `${(durationMs / 1000).toFixed(1)} s`
- : `${Math.floor(durationMs / 60_000)}m ${Math.floor((durationMs % 60_000) / 1000)}s`
+ ? durationMs < 60_000
+ ? (humanFriendlyMilliseconds(durationMs) ?? null)
+ : humanFriendlyDuration(durationMs / 1000)
: null
const seekEmbeddedPlayer = (ms: number): void => {
@@ -189,6 +185,14 @@ export function ReplayObservationSceneComponent(): JSX.Element {
setPendingSeek({ ms, trigger: Date.now() })
}
+ const toggleRecordingExpanded = (): void => {
+ // Collapsing discards the seek intent, or re-expanding would remount the seeker and replay it.
+ if (recordingExpanded) {
+ setPendingSeek(null)
+ }
+ setRecordingExpanded(!recordingExpanded)
+ }
+
return (
<SceneContent>
<SceneTitleSection
@@ -236,18 +240,15 @@ export function ReplayObservationSceneComponent(): JSX.Element {
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconInfo />} title="Observation details" />
<div className="flex flex-col gap-3 text-sm">
- <div>
- <div className="text-xs text-muted mb-0.5">Status</div>
+ <LabeledRow label="Status">
<ObservationStatusTag status={observation.status} />
- </div>
+ </LabeledRow>
{result && typeof result.confidence === 'number' && (
- <div>
- <div className="text-xs text-muted mb-0.5">Confidence</div>
+ <LabeledRow label="Confidence">
<ObservationConfidence result={result} />
- </div>
+ </LabeledRow>
)}
- <div>
- <div className="text-xs text-muted mb-0.5">Triggered by</div>
+ <LabeledRow label="Triggered by">
{observation.triggered_by === 'on_demand' && observation.triggered_by_user ? (
<ProfilePicture
user={{
@@ -261,18 +262,16 @@ export function ReplayObservationSceneComponent(): JSX.Element {
) : (
<span>{triggerLabel}</span>
)}
- </div>
- <div>
- <div className="text-xs text-muted mb-0.5">Session</div>
+ </LabeledRow>
+ <LabeledRow label="Session">
<Link
to={urls.sessionProfile(observation.session_id)}
data-attr="vision-observation-session-link"
>
{observation.session_id}
</Link>
- </div>
- <div>
- <div className="text-xs text-muted mb-0.5">Recording subject</div>
+ </LabeledRow>
+ <LabeledRow label="Recording subject">
{observation.distinct_id ? (
<Link to={urls.personByDistinctId(observation.distinct_id)}>
{observation.recording_subject_email ?? observation.distinct_id}
@@ -282,34 +281,30 @@ export function ReplayObservationSceneComponent(): JSX.Element {
) : (
<span className="text-muted">—</span>
)}
- </div>
+ </LabeledRow>
</div>
</LemonCard>
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconClock />} title="Lifecycle" />
<div className="flex flex-col gap-3 text-sm">
- <div>
- <div className="text-xs text-muted mb-0.5">Created at</div>
+ <LabeledRow label="Created at">
<TZLabel time={observation.created_at} />
- </div>
+ </LabeledRow>
{observation.started_at && (
- <div>
- <div className="text-xs text-muted mb-0.5">Started at</div>
+ <LabeledRow label="Started at">
<TZLabel time={observation.started_at} />
- </div>
+ </LabeledRow>
)}
{observation.completed_at && (
- <div>
- <div className="text-xs text-muted mb-0.5">Completed at</div>
+ <LabeledRow label="Completed at">
<TZLabel time={observation.completed_at} />
- </div>
+ </LabeledRow>
)}
{durationLabel && (
- <div>
- <div className="text-xs text-muted mb-0.5">Duration</div>
+ <LabeledRow label="Duration">
<span>{durationLabel}</span>
- </div>
+ </LabeledRow>
)}
</div>
</LemonCard>
@@ -318,20 +313,17 @@ export function ReplayObservationSceneComponent(): JSX.Element {
<CardHeader icon={<IconGear />} title="Configuration" />
<div className="flex flex-col gap-3 text-sm">
{snapshot?.model && (
- <div>
- <div className="text-xs text-muted mb-0.5">Model</div>
+ <LabeledRow label="Model">
<span>{modelLabel(snapshot.model)}</span>
- </div>
+ </LabeledRow>
)}
{summarizerLength && (
- <div>
- <div className="text-xs text-muted mb-0.5">Summary length</div>
+ <LabeledRow label="Summary length">
<span className="capitalize">{summarizerLength}</span>
- </div>
+ </LabeledRow>
)}
{classifierVocab && classifierVocab.length > 0 && (
- <div>
- <div className="text-xs text-muted mb-0.5">Vocabulary</div>
+ <LabeledRow label="Vocabulary">
<div className="flex flex-wrap gap-1">
{classifierVocab.map((tag) => (
<LemonTag key={tag} type="default" size="small">
@@ -339,49 +331,42 @@ export function ReplayObservationSceneComponent(): JSX.Element {
</LemonTag>
))}
</div>
- </div>
+ </LabeledRow>
)}
{monitorAllowInconclusive !== null && (
- <div>
- <div className="text-xs text-muted mb-0.5">Allow inconclusive verdicts</div>
+ <LabeledRow label="Allow inconclusive verdicts">
<BooleanTag value={monitorAllowInconclusive} />
- </div>
+ </LabeledRow>
)}
{classifierMultiLabel !== null && (
- <div>
- <div className="text-xs text-muted mb-0.5">Multi-label</div>
+ <LabeledRow label="Multi-label">
<BooleanTag value={classifierMultiLabel} />
- </div>
+ </LabeledRow>
)}
{classifierAllowFreeform !== null && (
- <div>
- <div className="text-xs text-muted mb-0.5">Freeform tags</div>
+ <LabeledRow label="Freeform tags">
<BooleanTag value={classifierAllowFreeform} />
- </div>
+ </LabeledRow>
)}
{scorerMin !== null && (
- <div>
- <div className="text-xs text-muted mb-0.5">Scale minimum</div>
+ <LabeledRow label="Scale minimum">
<span>{scorerMin}</span>
- </div>
+ </LabeledRow>
)}
{scorerMax !== null && (
- <div>
- <div className="text-xs text-muted mb-0.5">Scale maximum</div>
+ <LabeledRow label="Scale maximum">
<span>{scorerMax}</span>
- </div>
+ </LabeledRow>
)}
{scorerLabel && (
- <div>
- <div className="text-xs text-muted mb-0.5">Score label</div>
+ <LabeledRow label="Score label">
<span>{scorerLabel}</span>
- </div>
+ </LabeledRow>
)}
{snapshot?.emits_signals && (
- <div>
- <div className="text-xs text-muted mb-0.5">Signals</div>
+ <LabeledRow label="Signals">
<span>Emitted ({observation.scanner_result?.signals_count ?? 0})</span>
- </div>
+ </LabeledRow>
)}
</div>
</LemonCard>
@@ -498,14 +483,15 @@ export function ReplayObservationSceneComponent(): JSX.Element {
<LemonCard className="overflow-hidden p-0" hoverEffect={false}>
<div
className="flex items-center gap-2 bg-surface-primary p-3 cursor-pointer hover:bg-surface-secondary"
- onClick={() => setRecordingExpanded(!recordingExpanded)}
+ onClick={toggleRecordingExpanded}
>
<LemonButton
icon={recordingExpanded ? <IconCollapse /> : <IconExpand />}
size="small"
+ tooltip={recordingExpanded ? 'Collapse recording' : 'Expand recording'}
onClick={(e) => {
e.stopPropagation()
- setRecordingExpanded(!recordingExpanded)
+ toggleRecordingExpanded()
}}
data-attr="vision-observation-recording-toggle"
/>
diff --git a/products/replay_vision/frontend/observations/observationProgressLogic.ts b/products/replay_vision/frontend/observations/observationProgressLogic.ts
index c12e2e770b5d..6ec0442736e5 100644
--- a/products/replay_vision/frontend/observations/observationProgressLogic.ts
+++ b/products/replay_vision/frontend/observations/observationProgressLogic.ts
@@ -1,4 +1,4 @@
-import { actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'
+import { actions, kea, key, listeners, path, props, reducers } from 'kea'
import { teamLogic } from 'scenes/teamLogic'
@@ -19,7 +19,8 @@ export interface ObservationProgress {
phase: string
step: number
total_steps: number
- rasterizer: ObservationRasterizerProgress | null
+ // Optional: the backend's fallback tick omits the key entirely.
+ rasterizer?: ObservationRasterizerProgress | null
}
export interface ObservationProgressLogicProps {
@@ -103,6 +104,8 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
key((props) => props.observationId),
actions({
+ // Idempotent — callers that know the observation is in flight open the stream; settled rows never do.
+ startStream: true,
setProgress: (progress: ObservationProgress) => ({ progress }),
streamCompleted: true,
setStreamError: (error: string) => ({ error }),
@@ -123,28 +126,32 @@ export const observationProgressLogic = kea<observationProgressLogicType>([
],
}),
- listeners(({ props }) => ({
+ listeners(({ props, actions, cache }) => ({
+ startStream: () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (cache.streamStarted || !teamId) {
+ return
+ }
+ cache.streamStarted = true
+ // Disposable so the fetch is aborted on unmount and paused while the tab is hidden.
+ cache.disposables.add(() => {
+ const controller = new AbortController()
+ void consumeProgressStream(teamId, props.observationId, controller.signal, actions).catch(() => {
+ // Network/abort errors are non-fatal — the bar falls back to its time-based animation.
+ })
+ return () => controller.abort()
+ }, 'progressStream')
+ },
streamCompleted: () => {
- // Refresh the dock list so the finished card swaps its progress bar for the result immediately,
- // instead of lingering until the next poll. No-op where the dock isn't mounted (e.g. details page).
+ // The observation settled — dispose the stream so tab hide/show cycles don't resurrect it.
+ cache.disposables.dispose('progressStream')
+ // Refresh the dock list so the finished card swaps to the result immediately; no-op if the dock isn't mounted.
if (props.sessionId) {
observationsDockLogic.findMounted({ sessionId: props.sessionId })?.actions.loadObservations()
}
},
+ setStreamError: () => {
+ cache.disposables.dispose('progressStream')
+ },
})),
-
- afterMount(({ props, actions, cache }) => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- // Disposable so the fetch is aborted on unmount and paused while the tab is hidden.
- cache.disposables.add(() => {
- const controller = new AbortController()
- void consumeProgressStream(teamId, props.observationId, controller.signal, actions).catch(() => {
- // Network/abort errors are non-fatal — the bar falls back to its time-based animation.
- })
- return () => controller.abort()
- }, 'progressStream')
- }),
])
diff --git a/products/replay_vision/frontend/observations/replayObservationLogic.ts b/products/replay_vision/frontend/observations/replayObservationLogic.ts
index f19628595948..2254ad8753d1 100644
--- a/products/replay_vision/frontend/observations/replayObservationLogic.ts
+++ b/products/replay_vision/frontend/observations/replayObservationLogic.ts
@@ -47,39 +47,44 @@ export const replayObservationLogic = kea<replayObservationLogicType>([
],
}),
- listeners(({ actions, props, cache }) => ({
- loadObservation: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- const response = await visionObservationsRetrieve(String(teamId), props.id)
- actions.loadObservationSuccess(response)
- // Link the breadcrumb to the parent scanner so "back" returns to the scanner, not the vision home.
- replayObservationSceneLogic().actions.setScannerContext(
- response.scanner_id,
- response.scanner_snapshot?.name ?? null
- )
- } catch (error: any) {
- lemonToast.error(`Failed to load observation${error.detail ? `: ${error.detail}` : ''}`)
- actions.loadObservationFailure()
- }
- },
-
- loadObservationSuccess: ({ observation }) => {
- // SSE flips us to the result instantly when our listener catches `streamCompleted`, but the
- // stream is a shared keyed logic — if the dock started and finished it before this page opened,
- // the past event isn't replayed here. Poll while in flight as a fallback so we still land the result.
- const inFlight = observation.status === 'pending' || observation.status === 'running'
+ listeners(({ actions, props, values, cache }) => {
+ // Poll while in flight as the SSE fallback, on failure too; reducers run first, so `observation` is current.
+ const reschedulePoll = (): void => {
+ const inFlight = values.observation?.status === 'pending' || values.observation?.status === 'running'
scheduleObservationPoll(cache.disposables, inFlight, actions.loadObservation)
- },
+ }
+ return {
+ loadObservation: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return
+ }
+ try {
+ const response = await visionObservationsRetrieve(String(teamId), props.id)
+ actions.loadObservationSuccess(response)
+ // Link the breadcrumb to the parent scanner so "back" returns to the scanner, not the vision home.
+ replayObservationSceneLogic().actions.setScannerContext(
+ response.scanner_id,
+ response.scanner_snapshot?.name ?? null
+ )
+ } catch (error: any) {
+ // Only toast the initial load — background poll retries would otherwise spam one toast per tick.
+ if (!values.observation) {
+ lemonToast.error(`Failed to load observation${error.detail ? `: ${error.detail}` : ''}`)
+ }
+ actions.loadObservationFailure()
+ }
+ },
- // When the stream reports the observation has settled, reload once to render the final result.
- streamCompleted: () => {
- actions.loadObservation()
- },
- })),
+ loadObservationSuccess: reschedulePoll,
+ loadObservationFailure: reschedulePoll,
+
+ // When the stream reports the observation has settled, reload once to render the final result.
+ streamCompleted: () => {
+ actions.loadObservation()
+ },
+ }
+ }),
afterMount(({ actions }) => {
actions.loadObservation()
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
index 195de52a99aa..171cd4cd2972 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScanner.tsx
@@ -4,7 +4,6 @@ import { LemonBanner, LemonButton } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { FEATURE_FLAGS } from 'lib/constants'
-import { dayjs } from 'lib/dayjs'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useAttachedLogic } from 'lib/logic/scenes/useAttachedLogic'
@@ -18,7 +17,7 @@ import { AccessControlLevel, AccessControlResourceType } from '~/types'
import { ReplayVisionFeedbackButton } from '../components/ReplayVisionFeedbackButton'
import { visionQuotaLogic } from '../logics/visionQuotaLogic'
-import { QUOTA_WARN_THRESHOLD } from '../utils/quotaProjection'
+import { quotaBannerState } from '../utils/quotaProjection'
import { ObservationSearchMaxChat } from './components/ObservationSearchMaxChat'
import { ScannerConfigReadonly } from './components/ScannerConfigReadonly'
import { ScannerObservationsTable } from './components/ScannerObservationsTable'
@@ -126,27 +125,17 @@ export function ReplayScannerSceneComponent(): JSX.Element {
// 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)
- if (!quota || quota.monthly_quota <= 0) {
+ const state = quotaBannerState(quota)
+ if (!state.kind) {
return null
}
- const resetsOn = dayjs(quota.period_end).format('MMMM D')
- if (quota.exhausted) {
- return (
- <LemonBanner type="warning">
- Monthly observation quota reached ({quota.usage_this_month.toLocaleString()} /{' '}
- {quota.monthly_quota.toLocaleString()}). New observations are paused until {resetsOn}.
- </LemonBanner>
- )
- }
- if (quota.usage_this_month / quota.monthly_quota >= QUOTA_WARN_THRESHOLD) {
- 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. Resets {resetsOn}.
- </LemonBanner>
- )
- }
- return null
+ return (
+ <LemonBanner type="warning">
+ {state.kind === 'exhausted'
+ ? `Monthly observation quota reached (${state.quota.usage_this_month.toLocaleString()} / ${state.quota.monthly_quota.toLocaleString()}). New observations are paused until ${state.resetsOn}.`
+ : `${state.quota.usage_this_month.toLocaleString()} of ${state.quota.monthly_quota.toLocaleString()} monthly observations used. New observations will pause once you hit the cap. Resets ${state.resetsOn}.`}
+ </LemonBanner>
+ )
}
export default ReplayScannerSceneComponent
diff --git a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
index 99fc448e5c23..81159e66d56e 100644
--- a/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
+++ b/products/replay_vision/frontend/replay_scanners/ReplayScannersScene.tsx
@@ -44,6 +44,7 @@ export function ReplayScannersScene(): JSX.Element {
scannersTotal,
scannersSort,
togglingIds,
+ deletingIds,
search,
enabledFilter,
scannerTypeFilter,
@@ -83,7 +84,7 @@ export function ReplayScannersScene(): JSX.Element {
<LemonSwitch
checked={scanner.enabled}
onChange={() => toggleScannerEnabled(scanner.id)}
- disabled={togglingIds.includes(scanner.id)}
+ disabledReason={togglingIds.includes(scanner.id) ? 'Updating…' : undefined}
size="small"
data-attr="vision-scanner-toggle-enabled"
data-ph-capture-attribute-scanner-type={scanner.scanner_type}
@@ -103,15 +104,6 @@ export function ReplayScannersScene(): JSX.Element {
render: (_, scanner) => <ScannerTypeBadge scannerType={scanner.scanner_type} />,
sorter: true,
},
- {
- title: 'Description',
- key: 'description',
- render: (_, scanner) => (
- <div className="text-sm text-muted truncate max-w-md">
- {scanner.description || <span className="italic">No description</span>}
- </div>
- ),
- },
{
title: 'Sampling',
key: 'sampling_rate',
@@ -146,7 +138,7 @@ export function ReplayScannersScene(): JSX.Element {
size="small"
type="secondary"
icon={<IconPencil />}
- onClick={() => push(urls.replayVision(scanner.id))}
+ to={urls.replayVision(scanner.id)}
tooltip="Edit"
data-attr="vision-scanner-edit-row"
data-ph-capture-attribute-scanner-type={scanner.scanner_type}
@@ -161,6 +153,8 @@ export function ReplayScannersScene(): JSX.Element {
type="secondary"
status="danger"
icon={<IconTrash />}
+ loading={deletingIds.includes(scanner.id)}
+ disabledReason={deletingIds.includes(scanner.id) ? 'Deleting…' : undefined}
onClick={() =>
LemonDialog.open({
title: `Delete "${scanner.name || 'Untitled scanner'}"?`,
diff --git a/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx b/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx
index 00965d28cab6..6508fad8f90f 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ObservationSearchMaxChat.tsx
@@ -33,13 +33,12 @@ export function ObservationSearchMaxChat({ scannerId }: { scannerId: string }):
active: scannerId !== 'new',
context: { scanner_id: scannerId },
contextDescription: scanner
- ? { text: scanner.name || 'Replay Vision scanner', icon: iconForType('session_replay') }
+ ? { text: scanner.name || 'Replay vision scanner', icon: iconForType('session_replay') }
: undefined,
initialMaxPrompt: example,
})
- // Summarizer scanners already surface their own "Chat about these summaries" entry point; keep the search
- // tool registered for Max, but don't render a second, near-identical card on that page.
+ // Summarizer pages already surface a near-identical chat entry point — keep the Max tool, skip the card.
if (!openMax || scanner?.scanner_type === 'summarizer') {
return null
}
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
index 72f41f54c030..fa7b303c9242 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerConfigReadonly.tsx
@@ -19,6 +19,7 @@ import { AccessControlLevel, AccessControlResourceType, FilterLogicalOperator }
import { BooleanTag } from '../../components/BooleanTag'
import { CardHeader } from '../../components/CardHeader'
+import { LabeledRow } from '../../components/LabeledRow'
import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
import { replayScannerLogic } from '../replayScannerLogic'
import { MODEL_OPTIONS, ReplayScanner, ScannerType } from '../types'
@@ -31,15 +32,6 @@ const SUMMARY_LENGTHS = [
const SCANNER_TYPES: ScannerType[] = ['monitor', 'classifier', 'scorer', 'summarizer']
-function Row({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {
- return (
- <div>
- <div className="text-xs text-muted mb-0.5">{label}</div>
- <div className="text-sm">{children}</div>
- </div>
- )
-}
-
function Multiline({ value }: { value: string | null | undefined }): JSX.Element {
return <div className="whitespace-pre-wrap text-sm">{value || <span className="text-muted">—</span>}</div>
}
@@ -74,7 +66,7 @@ function OptionTags({
function BehaviorCardContent({ scanner }: { scanner: ReplayScanner }): JSX.Element {
return (
<>
- <Row label="Prompt">
+ <LabeledRow label="Prompt">
{scanner.scanner_config.prompt ? (
<div className="whitespace-pre-wrap text-sm bg-surface-secondary border rounded p-2">
{scanner.scanner_config.prompt}
@@ -82,20 +74,20 @@ function BehaviorCardContent({ scanner }: { scanner: ReplayScanner }): JSX.Eleme
) : (
<span className="text-muted">—</span>
)}
- </Row>
+ </LabeledRow>
{scanner.scanner_type === 'summarizer' && (
- <Row label="Summary length">
+ <LabeledRow label="Summary length">
<OptionTags options={SUMMARY_LENGTHS} selected={scanner.scanner_config.length} />
- </Row>
+ </LabeledRow>
)}
{scanner.scanner_type === 'monitor' && (
- <Row label="Allow inconclusive verdicts">
+ <LabeledRow label="Allow inconclusive verdicts">
<BooleanTag value={!!scanner.scanner_config.allow_inconclusive} />
- </Row>
+ </LabeledRow>
)}
{scanner.scanner_type === 'classifier' && (
<>
- <Row label="Tag vocabulary">
+ <LabeledRow label="Tag vocabulary">
{scanner.scanner_config.tags.length ? (
<div className="flex flex-wrap gap-1">
{scanner.scanner_config.tags.map((tag) => (
@@ -107,24 +99,24 @@ function BehaviorCardContent({ scanner }: { scanner: ReplayScanner }): JSX.Eleme
) : (
<span className="text-muted">—</span>
)}
- </Row>
- <Row label="Multiple tags per session">
+ </LabeledRow>
+ <LabeledRow label="Multiple tags per session">
<BooleanTag value={!!scanner.scanner_config.multi_label} />
- </Row>
- <Row label="Freeform tags">
+ </LabeledRow>
+ <LabeledRow label="Freeform tags">
<BooleanTag value={!!scanner.scanner_config.allow_freeform_tags} />
- </Row>
+ </LabeledRow>
</>
)}
{scanner.scanner_type === 'scorer' && (
- <Row label="Scale">
+ <LabeledRow label="Scale">
{scanner.scanner_config.scale.min} – {scanner.scanner_config.scale.max}
{scanner.scanner_config.scale.label ? ` (${scanner.scanner_config.scale.label})` : ''}
- </Row>
+ </LabeledRow>
)}
- <Row label="Emit signals">
+ <LabeledRow label="Emit signals">
<BooleanTag value={scanner.emits_signals} />
- </Row>
+ </LabeledRow>
</>
)
}
@@ -145,7 +137,7 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconInfo />} title="Overview" />
<div className="flex flex-col gap-3">
- <Row label="Type">
+ <LabeledRow label="Type">
<div className="flex flex-wrap gap-1">
{SCANNER_TYPES.map((scannerType) => (
<ScannerTypeBadge
@@ -155,14 +147,14 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
/>
))}
</div>
- </Row>
- <Row label="Description">
+ </LabeledRow>
+ <LabeledRow label="Description">
<Multiline value={scanner.description} />
- </Row>
- <Row label="Model">
+ </LabeledRow>
+ <LabeledRow label="Model">
<OptionTags options={MODEL_OPTIONS} selected={scanner.model} />
- </Row>
- <Row label="Status">
+ </LabeledRow>
+ <LabeledRow label="Status">
<div className="flex items-center gap-2">
<AccessControlAction
resourceType={AccessControlResourceType.SessionRecording}
@@ -181,7 +173,7 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
{scanner.enabled ? 'Runs automatically on a schedule' : 'Runs on-demand only'}
</span>
</div>
- </Row>
+ </LabeledRow>
</div>
</LemonCard>
@@ -197,8 +189,8 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconBolt />} title="Triggers" />
<div className="flex flex-col gap-3">
- <Row label="Sampling">{samplingPercent}%</Row>
- <Row label="Recording filters">
+ <LabeledRow label="Sampling">{samplingPercent}%</LabeledRow>
+ <LabeledRow label="Recording filters">
{!hasTriggers ? (
<span className="text-muted">No filters</span>
) : (
@@ -229,14 +221,14 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
)}
</div>
)}
- </Row>
+ </LabeledRow>
</div>
</LemonCard>
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconClock />} title="Lifecycle" />
<div className="flex flex-col gap-3">
- <Row label="Created by">
+ <LabeledRow label="Created by">
{scanner.created_by ? (
<ProfilePicture
user={{
@@ -250,27 +242,27 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
) : (
<span className="text-muted">—</span>
)}
- </Row>
- <Row label="Created">
+ </LabeledRow>
+ <LabeledRow label="Created">
<TZLabel time={scanner.created_at} />
- </Row>
- <Row label="Last updated">
+ </LabeledRow>
+ <LabeledRow label="Last updated">
<TZLabel time={scanner.updated_at} />
- </Row>
- <Row label="Last scheduled scan">
+ </LabeledRow>
+ <LabeledRow label="Last scheduled scan">
{scanner.last_swept_at ? (
<TZLabel time={scanner.last_swept_at} />
) : (
<span className="text-muted">Never</span>
)}
- </Row>
+ </LabeledRow>
</div>
</LemonCard>
<LemonCard className="p-4" hoverEffect={false}>
<CardHeader icon={<IconGraph />} title="Usage" />
<div className="flex flex-col gap-3">
- <Row label="Estimated monthly observations">
+ <LabeledRow label="Estimated monthly observations">
{scanner.estimated_monthly_observations != null ? (
<span className="tabular-nums">
{scanner.estimated_monthly_observations.toLocaleString()}
@@ -278,24 +270,24 @@ export function ScannerConfigReadonly({ scanner }: { scanner: ReplayScanner }):
) : (
<span className="text-muted">—</span>
)}
- </Row>
- <Row label="Total observations">
+ </LabeledRow>
+ <LabeledRow label="Total observations">
<span className="tabular-nums">{observationStats.total.toLocaleString()}</span>
- </Row>
- <Row label="Success rate">
+ </LabeledRow>
+ <LabeledRow label="Success rate">
{observationStats.successRate != null ? (
<span className="tabular-nums">{observationStats.successRate}%</span>
) : (
<span className="text-muted">—</span>
)}
- </Row>
- <Row label="Outcomes">
+ </LabeledRow>
+ <LabeledRow label="Outcomes">
<span className="text-sm">
{observationStats.succeeded.toLocaleString()} succeeded ·{' '}
{observationStats.failed.toLocaleString()} failed ·{' '}
{observationStats.ineligible.toLocaleString()} ineligible
</span>
- </Row>
+ </LabeledRow>
</div>
</LemonCard>
</div>
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
index ba68e6846433..108acb203cbf 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerObservationsTable.tsx
@@ -94,7 +94,6 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):
observationStats,
scanner,
triggeringOnDemandObservation,
- refreshing,
} = useValues(logic)
const {
refreshObservations,
@@ -274,7 +273,7 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):
type="secondary"
icon={<IconRefresh />}
onClick={() => refreshObservations()}
- loading={refreshing}
+ loading={observationsLoading}
data-attr="vision-observations-refresh"
>
Refresh
@@ -295,16 +294,14 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):
valueClass={observationStats.failed > 0 ? 'text-danger' : undefined}
/>
<Metric label="Ineligible" value={observationStats.ineligible} />
- {observationStats.inFlight > 0 && (
- <Metric label="In flight" value={observationStats.inFlight} />
- )}
+ <Metric label="In flight" value={observationStats.inFlight} />
</div>
</div>
</div>
<LemonTable
columns={columns}
dataSource={observations}
- loading={refreshing || triggeringOnDemandObservation || observationsLoading}
+ loading={triggeringOnDemandObservation || observationsLoading}
rowKey="id"
pagination={{
controlled: true,
@@ -317,6 +314,8 @@ export function ScannerObservationsTable({ scannerId }: { scannerId: string }):
sorting={observationsSort}
onSort={(next) => setObservationsSort(next)}
useURLForSorting={false}
+ // The URL scheme can't express "no sort", so a third header click would snap back with duplicate fetches.
+ noSortingCancellation
nouns={['observation', 'observations']}
emptyState={
<div className="p-6 text-center text-muted">
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx
index 1c7319a9a7d1..04b495663485 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerRunTab.tsx
@@ -1,8 +1,8 @@
import { BindLogic, useActions, useValues } from 'kea'
-import { useCallback, useEffect, useRef, useState } from 'react'
+import { useEffect, useRef, useState } from 'react'
import { IconEye, IconPlay } from '@posthog/icons'
-import { LemonButton, LemonInput, LemonTable, LemonTag, Link, Spinner } from '@posthog/lemon-ui'
+import { LemonButton, LemonInput, LemonTable, Link } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { TZLabel } from 'lib/components/TZLabel'
@@ -13,18 +13,13 @@ import {
SessionRecordingPlaylistLogicProps,
sessionRecordingsPlaylistLogic,
} from 'scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic'
-import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { AccessControlLevel, AccessControlResourceType, SessionRecordingType } from '~/types'
import { ObservationStatusTag } from '../../components/ObservationCard'
-import { visionScannersObservationsList } from '../../generated/api'
-import type { ReplayObservationApi } from '../../generated/api.schemas'
import { replayScannerLogic } from '../replayScannerLogic'
-
-type RowObservation = { id: string; status: ReplayObservationApi['status'] }
-const IN_PROGRESS_STATUSES = new Set<string>(['pending', 'running'])
+import { IN_PROGRESS_STATUSES, scannerRunTabLogic } from '../scannerRunTabLogic'
/** Manual entry: scan one session by pasting its recording ID. */
function ScanBySessionId({ scannerId }: { scannerId: string }): JSX.Element {
@@ -92,115 +87,14 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {
const { filters, totalFiltersCount, sessionRecordings, sessionRecordingsResponseLoading, hasNext } =
useValues(sessionRecordingsPlaylistLogic)
const { setFilters, resetFilters, maybeLoadSessionRecordings } = useActions(sessionRecordingsPlaylistLogic)
- const { currentTeamId } = useValues(teamLogic)
- const { triggeringOnDemandObservation, onDemandObservationSuccessCount } = useValues(
- replayScannerLogic({ id: scannerId })
- )
- const { triggerOnDemandObservation } = useActions(replayScannerLogic({ id: scannerId }))
-
- // `pendingId` bridges the gap between clicking Scan and its observation showing up in the fetch below — it
- // stays set until the observation lands (so the spinner never flickers back to the button), and is released
- // on trigger failure. `pendingStartCount` lets us tell a queued scan from a failed one.
- const [pendingId, setPendingId] = useState<string | null>(null)
- const pendingStartCount = useRef(0)
+ const { observationBySession, pendingId, refreshingObservations } = useValues(scannerRunTabLogic({ scannerId }))
+ const { setVisibleSessionIds, startScan } = useActions(scannerRunTabLogic({ scannerId }))
- // A scanner observes each session at most once. Look up each visible recording's observation (id + status):
- // in-progress rows show a spinner, settled rows link to the result. Refetch after each scan and poll while
- // anything visible is still running (or queued), so a row swaps spinner → "View observation" on its own.
- const [observationBySession, setObservationBySession] = useState<Map<string, RowObservation>>(new Map())
- // Drives the table's loading bar on foreground refetches (initial load, post-scan). Background polls
- // reload silently so the table stays interactable instead of blanking on each tick.
- const [refreshingObservations, setRefreshingObservations] = useState(false)
+ // Sync the playlist's visible rows into the logic, which owns the observation lookup and polling.
const visibleIdsKey = sessionRecordings.map((recording) => recording.id).join(',')
-
- const refetchObservations = useCallback(
- async (background = false) => {
- const ids = visibleIdsKey ? visibleIdsKey.split(',') : []
- if (!currentTeamId || ids.length === 0) {
- return
- }
- if (!background) {
- setRefreshingObservations(true)
- }
- try {
- const response = await visionScannersObservationsList(String(currentTeamId), scannerId, {
- session_id: visibleIdsKey,
- limit: ids.length,
- })
- setObservationBySession((prev) => {
- const next = new Map(prev)
- for (const observation of response.results ?? []) {
- next.set(observation.session_id, { id: observation.id, status: observation.status })
- }
- return next
- })
- } catch {
- // Best-effort enrichment — on failure we just leave the rows scannable.
- } finally {
- // Only the foreground path touches the flag — a background poll resolving mid-flight must
- // not clear an overlay a concurrent foreground fetch is still showing.
- if (!background) {
- setRefreshingObservations(false)
- }
- }
- },
- [visibleIdsKey, currentTeamId, scannerId]
- )
-
- // Initial load + whenever a scan is triggered (which creates a new pending observation to pick up).
useEffect(() => {
- void refetchObservations()
- }, [refetchObservations, onDemandObservationSuccessCount])
-
- // Release the bridge if the trigger failed (no new observation was queued) — on success we keep it until the
- // observation appears in the fetch, avoiding a one-frame flicker back to the button.
- useEffect(() => {
- if (triggeringOnDemandObservation || !pendingId) {
- return
- }
- const failed = onDemandObservationSuccessCount <= pendingStartCount.current
- if (failed) {
- setPendingId(null)
- }
- }, [triggeringOnDemandObservation, onDemandObservationSuccessCount, pendingId])
-
- // Once the queued observation lands, the bridge is no longer needed (its in-progress status drives the spinner).
- useEffect(() => {
- if (pendingId && observationBySession.has(pendingId)) {
- setPendingId(null)
- }
- }, [observationBySession, pendingId])
-
- const visibleIds = visibleIdsKey ? visibleIdsKey.split(',') : []
- const anyInProgress = visibleIds.some((id) => {
- const observation = observationBySession.get(id)
- return !!observation && IN_PROGRESS_STATUSES.has(observation.status)
- })
-
- // Poll while a visible row is running or a scan is queued, so the spinner settles into the result button.
- const shouldPoll = anyInProgress || pendingId !== null
- useEffect(() => {
- if (!shouldPoll) {
- return
- }
- const interval = setInterval(() => {
- // Skip polling while the browser tab is backgrounded; it resumes on the next tick when visible again.
- if (document.visibilityState === 'visible') {
- // Background reload — keeps the table interactable instead of blanking it each tick.
- void refetchObservations(true)
- }
- }, 4000)
- return () => clearInterval(interval)
- }, [shouldPoll, refetchObservations])
-
- const startScan = (sessionId: string): void => {
- if (triggeringOnDemandObservation || pendingId) {
- return
- }
- pendingStartCount.current = onDemandObservationSuccessCount
- setPendingId(sessionId)
- triggerOnDemandObservation(sessionId, true)
- }
+ setVisibleSessionIds(visibleIdsKey ? visibleIdsKey.split(',') : [])
+ }, [visibleIdsKey, setVisibleSessionIds])
const columns: LemonTableColumns<SessionRecordingType> = [
{
@@ -229,16 +123,12 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {
title: 'Status',
key: 'status',
render: (_, recording) => {
- const observation = observationBySession.get(recording.id)
+ const observation = observationBySession[recording.id]
if (observation) {
return <ObservationStatusTag status={observation.status} />
}
if (pendingId === recording.id) {
- return (
- <LemonTag type="warning">
- <Spinner className="mr-1" /> Scanning
- </LemonTag>
- )
+ return <ObservationStatusTag status="running" />
}
return <span className="text-muted italic">Not scanned</span>
},
@@ -249,7 +139,7 @@ function RecordingsList({ scannerId }: { scannerId: string }): JSX.Element {
// Fixed width so Scan recording / View observation occupy the same width as the cell swaps.
width: 184,
render: (_, recording) => {
- const observation = observationBySession.get(recording.id)
+ const observation = observationBySession[recording.id]
const settled = observation && !IN_PROGRESS_STATUSES.has(observation.status)
// In-flight or queued — the Status pill carries the spinner, so here we just disable the button.
const scanning =
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
index 1ffd5bdd3fd7..532166a03ad8 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTemplatePicker.tsx
@@ -1,19 +1,7 @@
import { useValues } from 'kea'
import { combineUrl, router } from 'kea-router'
-import {
- IconBolt,
- IconBug,
- IconCheckCircle,
- IconMagicWand,
- IconNotebook,
- IconPlus,
- IconSearch,
- IconStar,
- IconTarget,
- IconThumbsDown,
- IconWarning,
-} from '@posthog/icons'
+import { IconCheckCircle, IconNotebook, IconPlus, IconTarget, IconThumbsDown, IconWarning } from '@posthog/icons'
import { urls } from 'scenes/urls'
@@ -21,34 +9,12 @@ import { ScannerTypeBadge } from '../../components/ScannerTypeBadge'
import { replayScannerLogic } from '../replayScannerLogic'
import { ScannerTemplate, ScannerTemplateIcon, defaultScannerTemplates, newScanner } from '../scannerTemplates'
-function getTemplateIcon(icon: ScannerTemplateIcon): JSX.Element {
- const iconClass = 'w-6 h-6 text-primary-3000'
- switch (icon) {
- case 'bolt':
- return <IconBolt className={iconClass} />
- case 'warning':
- return <IconWarning className={iconClass} />
- case 'notebook':
- return <IconNotebook className={iconClass} />
- case 'target':
- return <IconTarget className={iconClass} />
- case 'thumbs-down':
- return <IconThumbsDown className={iconClass} />
- case 'star':
- return <IconStar className={iconClass} />
- case 'search':
- return <IconSearch className={iconClass} />
- case 'magic':
- return <IconMagicWand className={iconClass} />
- case 'bug':
- return <IconBug className={iconClass} />
- case 'check':
- return <IconCheckCircle className={iconClass} />
- default: {
- const exhaustiveCheck: never = icon
- return exhaustiveCheck
- }
- }
+const TEMPLATE_ICONS: Record<ScannerTemplateIcon, JSX.Element> = {
+ warning: <IconWarning />,
+ notebook: <IconNotebook />,
+ target: <IconTarget />,
+ 'thumbs-down': <IconThumbsDown />,
+ check: <IconCheckCircle />,
}
function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JSX.Element {
@@ -71,7 +37,9 @@ function TemplateCard({ template }: { template: ScannerTemplate | 'blank' }): JS
>
<div className="flex flex-col items-center text-center gap-4 h-full">
<div className="bg-primary-3000/10 rounded-lg flex-shrink-0 size-12 flex items-center justify-center">
- {isBlank ? <IconPlus className="w-6 h-6 text-primary-3000" /> : getTemplateIcon(template.icon)}
+ <span className="w-6 h-6 text-primary-3000 [&_svg]:w-6 [&_svg]:h-6">
+ {isBlank ? <IconPlus /> : TEMPLATE_ICONS[template.icon]}
+ </span>
</div>
<div className="flex-1 flex flex-col justify-start">
<div className="flex items-center justify-center gap-2 mb-2">
diff --git a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
index c5985dfd5834..d982aacb83a4 100644
--- a/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
+++ b/products/replay_vision/frontend/replay_scanners/components/ScannerTriggers.tsx
@@ -41,8 +41,7 @@ const SCANNER_FILTER_TYPES: TaxonomicFilterGroupType[] = [
TaxonomicFilterGroupType.SessionProperties,
]
-// Vision only analyzes recordings within these duration bounds (server-enforced; see backend constants.py:
-// MIN_SESSION_DURATION_FOR_VIDEO_SCANNER_S, MIN/MAX_ACTIVE_SECONDS_FOR_VIDEO_SCANNER_S), so the filter clamps to them.
+// Vision only analyzes recordings within these server-enforced duration bounds (see backend constants.py).
const DURATION_BOUNDS: Partial<Record<DurationType, { min?: number; max?: number }>> = {
duration: { min: 15 },
active_seconds: { min: 10, max: 3600 },
@@ -128,12 +127,12 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Eleme
<LemonInput
type="number"
value={samplingPercent}
- onChange={(v) => onChange((Number(v) || 0) / 100)}
+ onChange={(v) => onChange(Math.min(100, Number(v) || 0) / 100)}
min={0.1}
max={100}
step={0.1}
suffix={<span>%</span>}
- status={samplingPercent === 0 ? 'danger' : undefined}
+ status={samplingPercent < 0.1 ? 'danger' : undefined}
/>
</div>
</div>
@@ -148,8 +147,7 @@ export function ScannerTriggers({ scannerId }: { scannerId: string }): JSX.Eleme
const universal = recordingsQueryToUniversalFilters(query)
const applyUniversal = (next: RecordingUniversalFilters): void => {
const converted = convertUniversalFiltersToRecordingsQuery(next)
- // Overlay only the dimensions this editor controls, so query fields it doesn't
- // render (e.g. session_ids, person_uuid set via API/MCP) survive an edit.
+ // Overlay only the dimensions this editor renders so other query fields survive an edit.
onChange({
...query,
kind: converted.kind,
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
index db56199cb80f..8f0eab5ddd42 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.test.ts
@@ -6,13 +6,12 @@ import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
+import { parseCsvParam, parseSortParam } from '../utils/urlParams'
import {
buildObservationListParams,
ObservationStatusValue,
ObservationTriggeredByValue,
ObservationVerdictValue,
- parseCsvParam,
- parseSortParam,
replayScannerLogic,
shouldGuardScannerNavigation,
} from './replayScannerLogic'
@@ -23,16 +22,19 @@ describe('replayScannerLogic', () => {
let logic: ReturnType<typeof replayScannerLogic.build>
let observeSpy: jest.Mock
let suggestSpy: jest.Mock
+ let createSpy: jest.Mock
beforeEach(() => {
observeSpy = jest.fn(() => [202, { workflow_id: 'wf-test' }])
suggestSpy = jest.fn(() => [200, { suggestions: [] }])
+ createSpy = jest.fn(() => [201, { id: 'created-scanner' }])
useMocks({
get: {
'/api/projects/:team/vision/scanners/:id/': () => [404, {}],
'/api/projects/:team/vision/scanners/:id/observations/': { results: [] },
},
post: {
+ '/api/projects/:team/vision/scanners/': createSpy,
'/api/projects/:team/vision/scanners/:id/observe/': observeSpy,
'/api/projects/:team/vision/scanners/suggest_tags/': suggestSpy,
},
@@ -218,6 +220,24 @@ describe('replayScannerLogic', () => {
expect(router.values.location.pathname).toContain('/replay-vision/new/triggers')
expect(logic.values.submitIntent).toBe('save')
})
+
+ it('advance does not mark the draft as saved, so the unsaved-changes guard stays armed', async () => {
+ router.actions.push('/replay-vision/new/configure')
+ logic.actions.setScannerValues({ name: 'Draft scanner', scanner_config: { prompt: 'Q?' } })
+ logic.actions.setSubmitIntent('advance')
+ await expectLogic(logic, () => logic.actions.submitScanner()).toFinishAllListeners()
+ // The draft must not be adopted as the saved baseline — no API write happened.
+ expect(logic.values.originalScanner?.name).toBe('')
+ expect(logic.values.hasUnsavedChanges).toBe(true)
+ })
+
+ it('default-intent submit (Enter) on the new-scanner configure step advances instead of creating', async () => {
+ router.actions.push('/replay-vision/new/configure')
+ logic.actions.setScannerValues({ name: 'Test scanner', scanner_config: { prompt: 'Q?' } })
+ await expectLogic(logic, () => logic.actions.submitScanner()).toFinishAllListeners()
+ expect(createSpy).not.toHaveBeenCalled()
+ expect(router.values.location.pathname).toContain('/replay-vision/new/triggers')
+ })
})
describe('validation errors', () => {
@@ -452,6 +472,14 @@ describe('replayScannerLogic', () => {
it('splits, trims, and drops empty values', () => {
expect(parseCsvParam('a, b ,c,')).toEqual(['a', 'b', 'c'])
})
+
+ it('survives the router coercing a single numeric param to a number', () => {
+ expect(parseCsvParam(2024)).toEqual(['2024'])
+ })
+
+ it('drops values outside the allowlist when one is given', () => {
+ expect(parseCsvParam('banana,yes', ['yes', 'no'])).toEqual(['yes'])
+ })
})
describe('observationsPage / sort URL sync', () => {
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
index a45417153ce0..b7ed2b1fecea 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannerLogic.ts
@@ -1,18 +1,18 @@
-import equal from 'fast-deep-equal'
import { actions, afterMount, isBreakpoint, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { forms } from 'kea-forms'
+import { loaders } from 'kea-loaders'
import { actionToUrl, beforeUnload, router, urlToAction } from 'kea-router'
import { CombinedLocation } from 'kea-router/lib/utils'
import { dayjs } from 'lib/dayjs'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { dateStringToDayJs } from 'lib/utils/dateFilters'
import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import {
visionScannersCreate,
- visionScannersDestroy,
visionScannersEstimateCreate,
visionScannersObservationsList,
visionScannersObservationsStatsRetrieve,
@@ -21,14 +21,16 @@ import {
visionScannersRetrieve,
visionScannersSuggestTagsCreate,
} from '../generated/api'
+import { ObservationStatusEnumApi, ObservationTriggerEnumApi } from '../generated/api.schemas'
import type {
EstimateResponseApi,
ObservationStatsApi,
ReplayObservationApi,
TagSuggestionApi,
} from '../generated/api.schemas'
-import { scheduleObservationPoll } from '../logics/observationPolling'
-import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from '../logics/observationPolling'
+import { refreshVisionQuota } from '../logics/visionQuotaLogic'
+import { type UrlSorting, parseCsvParam, parseSortParam, serializeSortParam } from '../utils/urlParams'
import type { replayScannerLogicType } from './replayScannerLogicType'
import { findScannerTemplate, newScanner } from './scannerTemplates'
import {
@@ -48,9 +50,12 @@ export type ObservationStatusValue = ReplayObservationApi['status']
export type ObservationTriggeredByValue = ReplayObservationApi['triggered_by']
export type ObservationVerdictValue = 'yes' | 'no' | 'inconclusive'
-export const OBSERVATIONS_PAGE_SIZE = 50
+// Derived from the generated runtime enums so a backend enum change can't strand a stale copy here.
+const OBSERVATION_STATUS_VALUES: readonly ObservationStatusValue[] = Object.values(ObservationStatusEnumApi)
+const OBSERVATION_TRIGGERED_BY_VALUES: readonly ObservationTriggeredByValue[] = Object.values(ObservationTriggerEnumApi)
+const OBSERVATION_VERDICT_VALUES: readonly ObservationVerdictValue[] = ['yes', 'no', 'inconclusive']
-const OBSERVE_POLL_GRACE_MS = 30_000
+export const OBSERVATIONS_PAGE_SIZE = 50
function currentTemplateKey(): string | null {
const value = router.values.searchParams.template
@@ -75,54 +80,16 @@ function omitQuery(scanner: ReplayScanner): Omit<ReplayScanner, 'query'> {
return rest
}
-const UNIT_BY_LETTER: Record<string, dayjs.ManipulateType> = {
- h: 'hour',
- d: 'day',
- w: 'week',
- m: 'month',
- y: 'year',
-}
-
-const START_OF_BY_PREFIX: Record<string, dayjs.ManipulateType> = {
- dStart: 'day',
- wStart: 'week',
- mStart: 'month',
- yStart: 'year',
-}
-
-function chartRangeToDayjs(expr: string): dayjs.Dayjs | null {
- const relative = expr.match(/^-(\d+)([hdwmy])(Start|End)?$/)
- if (relative) {
- const [, n, letter, suffix] = relative
- const unit = UNIT_BY_LETTER[letter]
- const date = dayjs().subtract(parseInt(n, 10), unit)
- if (suffix === 'Start') {
- return date.startOf(unit)
- }
- if (suffix === 'End') {
- return date.endOf(unit)
- }
- return date
- }
- if (expr in START_OF_BY_PREFIX) {
- return dayjs().startOf(START_OF_BY_PREFIX[expr])
- }
- if (expr === 'all') {
- return dayjs().subtract(1, 'year')
- }
- const parsed = dayjs(expr)
- return parsed.isValid() ? parsed : null
-}
-
function daysFromChartRange(dateFrom: string | null, dateTo: string | null): number {
if (!dateFrom) {
return 14
}
- const from = chartRangeToDayjs(dateFrom)
+ // 'all' has no anchor; a year is the chart's practical ceiling.
+ const from = dateFrom === 'all' ? dayjs().subtract(1, 'year') : dateStringToDayJs(dateFrom)
if (!from) {
return 14
}
- const to = dateTo ? chartRangeToDayjs(dateTo) || dayjs() : dayjs()
+ const to = (dateTo && dateTo !== 'all' ? dateStringToDayJs(dateTo) : null) ?? dayjs()
return Math.max(1, to.diff(from, 'day'))
}
@@ -137,10 +104,7 @@ interface ObservationListParams {
order_by?: string
}
-export interface ObservationsSorting {
- columnKey: string
- order: 1 | -1
-}
+export type ObservationsSorting = UrlSorting
const STATIC_ORDER_KEYS: Record<string, string> = {
created_at: 'created_at',
@@ -227,10 +191,9 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
loadScannerFailure: true,
setScannerType: (scannerType: ScannerType) => ({ scannerType }),
setSubmitIntent: (intent: 'save' | 'advance') => ({ intent }),
+ // Fired only after an actual API write, unlike submitScannerSuccess (which the advance path emits too).
+ scannerSaved: (scanner: ReplayScanner) => ({ scanner }),
appendClassifierTags: (tags: string[]) => ({ tags }),
- loadTagSuggestions: true,
- loadTagSuggestionsSuccess: (suggestions: TagSuggestionApi[]) => ({ suggestions }),
- loadTagSuggestionsFailure: true,
acceptTagSuggestion: (tag: string) => ({ tag }),
acceptAllTagSuggestions: true,
dismissTagSuggestions: true,
@@ -242,7 +205,6 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
loadObservationStats: true,
loadObservationStatsSuccess: (stats: ObservationStatsApi) => ({ stats }),
loadObservationStatsFailure: true,
- deleteScanner: true,
toggleEnabled: true,
toggleEnabledSuccess: (enabled: boolean) => ({ enabled }),
toggleEnabledFailure: true,
@@ -314,7 +276,11 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
submit: async (scanner: ReplayScanner) => {
- if (values.submitIntent === 'advance') {
+ // Mid-wizard Enter (default 'save' intent) must advance, not create; pathname is project-prefixed, hence endsWith.
+ const onConfigureStep = router.values.location.pathname.endsWith(
+ urls.replayVisionScannerConfigure(props.id)
+ )
+ if (values.submitIntent === 'advance' || (values.isNew && onConfigureStep)) {
actions.setSubmitIntent('save')
router.actions.push(urls.replayVisionScannerTriggers(props.id))
return
@@ -327,10 +293,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
try {
if (props.id === 'new') {
const response = await visionScannersCreate(String(teamId), scannerToApiBody(body))
+ actions.scannerSaved(scanner)
router.actions.replace(urls.replayVision(response.id))
lemonToast.success('Scanner created')
} else {
await visionScannersPartialUpdate(String(teamId), props.id, scannerToPatchedApiBody(body))
+ actions.scannerSaved(scanner)
lemonToast.success('Scanner saved')
router.actions.push(urls.replayVision(props.id))
}
@@ -342,12 +310,42 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
},
})),
+ loaders(({ props, values }) => ({
+ tagSuggestions: [
+ [] as TagSuggestionApi[],
+ {
+ loadTagSuggestions: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ const scanner = values.scanner
+ if (!teamId || !scanner || scanner.scanner_type !== 'classifier') {
+ return []
+ }
+ const config = scanner.scanner_config
+ try {
+ const response = await visionScannersSuggestTagsCreate(String(teamId), {
+ prompt: config.prompt ?? '',
+ tags: config.tags ?? [],
+ multi_label: config.multi_label ?? true,
+ allow_freeform_tags: config.allow_freeform_tags ?? false,
+ scanner_id: props.id !== 'new' ? props.id : undefined,
+ })
+ return response.suggestions ?? []
+ } catch (error: any) {
+ lemonToast.error(`Couldn't generate suggestions${error?.detail ? `: ${error.detail}` : ''}`)
+ return []
+ }
+ },
+ },
+ ],
+ })),
+
reducers({
originalScanner: [
null as ReplayScanner | null,
{
loadScannerSuccess: (_, { scanner }) => scanner,
- submitScannerSuccess: (_, { scanner }: { scanner: ReplayScanner }) => scanner,
+ // Keyed on the real save, not submitScannerSuccess — kea-forms fires that on the no-API advance path too.
+ scannerSaved: (_, { scanner }) => scanner,
toggleEnabledSuccess: (state, { enabled }) => (state ? { ...state, enabled } : state),
},
],
@@ -379,14 +377,6 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
triggerOnDemandObservationSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,
},
],
- refreshing: [
- false,
- {
- refreshObservations: () => true,
- loadObservationsSuccess: () => false,
- loadObservationsFailure: () => false,
- },
- ],
scannerLoading: [
false,
{
@@ -402,25 +392,12 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
loadScannerSuccess: () => 'save' as 'save' | 'advance',
},
],
- tagSuggestions: [
- [] as TagSuggestionApi[],
- {
- loadTagSuggestions: () => [],
- loadTagSuggestionsSuccess: (_, { suggestions }) => suggestions,
- loadTagSuggestionsFailure: () => [],
- // Accepted suggestions leave the panel; the listener adds them to the vocabulary.
- acceptTagSuggestion: (state, { tag }) => state.filter((s) => s.tag !== tag),
- dismissTagSuggestions: () => [],
- },
- ],
- tagSuggestionsLoading: [
- false,
- {
- loadTagSuggestions: () => true,
- loadTagSuggestionsSuccess: () => false,
- loadTagSuggestionsFailure: () => false,
- },
- ],
+ tagSuggestions: {
+ // Accepted suggestions leave the panel; the listener adds them to the vocabulary.
+ acceptTagSuggestion: (state: TagSuggestionApi[], { tag }: { tag: string }) =>
+ state.filter((s) => s.tag !== tag),
+ dismissTagSuggestions: () => [],
+ },
observations: [
[] as ReplayObservationApi[],
{
@@ -458,8 +435,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
observationsLoading: [
false,
{
- // Background polls reload silently so the table stays interactable; only foreground
- // loads (initial paint, manual refresh, filter/sort/pagination) show the overlay.
+ // Background polls reload silently so the table stays interactable; only foreground loads show the overlay.
loadObservations: (state, { background }) => (background ? state : true),
loadObservationsSuccess: () => false,
loadObservationsFailure: () => false,
@@ -675,6 +651,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}),
listeners(({ actions, props, values, cache }) => {
+ const reschedulePoll = (): void => {
+ scheduleObservationPoll(
+ cache.disposables,
+ shouldPollObservations(values.hasObservationsInFlight, values.pollUntil),
+ () => reloadObservationsAndStats(true)
+ )
+ }
const reloadObservationsAndStats = (background = false): void => {
actions.loadObservations(background)
actions.loadObservationStats()
@@ -684,8 +667,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
if (props.id === 'new') {
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.
+ // Strip an unknown template key so the URL matches the from-scratch flow the user actually gets.
const { template: _drop, ...rest } = router.values.searchParams
router.actions.replace(router.values.location.pathname, rest)
actions.loadScannerSuccess(newScanner(null))
@@ -696,6 +678,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
+ actions.loadScannerFailure() // Clear the loading flag — a bare return would spin forever.
return
}
try {
@@ -710,9 +693,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
loadScannerSuccess: ({ scanner }) => {
actions.setScannerValues(scanner)
- actions.requestScannerEstimate()
- // A deep-link to `?sort=result` can't resolve its order_by until the scanner type is known;
- // refire once we have it so the initial paint reflects the URL.
+ // A `?sort=result` deep-link can't resolve order_by until the scanner type is known — refire now.
if (values.observationsSort?.columnKey === 'result' && scanner.scanner_type) {
actions.loadObservations()
actions.loadObservationStats()
@@ -753,28 +734,6 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
- loadTagSuggestions: async () => {
- const teamId = teamLogic.values.currentTeamId
- const scanner = values.scanner
- if (!teamId || !scanner || scanner.scanner_type !== 'classifier') {
- actions.loadTagSuggestionsFailure()
- return
- }
- const config = scanner.scanner_config
- try {
- const response = await visionScannersSuggestTagsCreate(String(teamId), {
- prompt: config.prompt ?? '',
- tags: config.tags ?? [],
- multi_label: config.multi_label ?? true,
- allow_freeform_tags: config.allow_freeform_tags ?? false,
- scanner_id: props.id !== 'new' ? props.id : undefined,
- })
- actions.loadTagSuggestionsSuccess(response.suggestions ?? [])
- } catch (error: any) {
- lemonToast.error(`Couldn't generate suggestions${error?.detail ? `: ${error.detail}` : ''}`)
- actions.loadTagSuggestionsFailure()
- }
- },
acceptTagSuggestion: ({ tag }) => actions.appendClassifierTags([tag]),
acceptAllTagSuggestions: () => {
// Read the suggestions before dismiss clears them.
@@ -782,14 +741,13 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
actions.dismissTagSuggestions()
},
- // kea-forms fires setScannerValue(s) on every field change. Debounce the estimate so slider drags
- // and rapid filter edits don't fire one request per tick.
+ // kea-forms fires setScannerValue(s) per field change — debounced so drags don't fire a request per tick.
setScannerValue: () => actions.requestScannerEstimate(),
setScannerValues: () => actions.requestScannerEstimate(),
- submitScannerSuccess: () => {
+ scannerSaved: () => {
actions.requestScannerEstimate()
// Saving recomputes the persisted estimate, which shifts the org-wide fleet sum.
- visionQuotaLogic.findMounted()?.actions.loadQuota()
+ refreshVisionQuota()
},
requestScannerEstimate: () => {
@@ -834,23 +792,6 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
- deleteScanner: async () => {
- if (props.id === 'new') {
- return
- }
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- await visionScannersDestroy(String(teamId), props.id)
- lemonToast.success('Scanner deleted')
- router.actions.replace(urls.replayVision())
- } catch (error: any) {
- lemonToast.error(`Failed to delete scanner${error.detail ? `: ${error.detail}` : ''}`)
- }
- },
-
toggleEnabled: async () => {
const scanner = values.scanner
if (props.id === 'new' || !scanner) {
@@ -867,7 +808,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
try {
await visionScannersPartialUpdate(String(teamId), props.id, { enabled: next })
actions.toggleEnabledSuccess(next)
- visionQuotaLogic.findMounted()?.actions.loadQuota()
+ refreshVisionQuota()
} catch (error: any) {
actions.setScannerValue('enabled', !next)
const verb = next ? 'enable' : 'disable'
@@ -906,23 +847,38 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}
},
+ triggerOnDemandObservationSuccess: () => refreshVisionQuota(),
+
refreshObservations: () => reloadObservationsAndStats(),
- loadObservations: async () => {
+ loadObservations: async (_, breakpoint) => {
if (props.id === 'new') {
actions.loadObservationsSuccess([], 0)
return
}
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
+ actions.loadObservationsFailure()
return
}
try {
const offset = (values.observationsPage - 1) * OBSERVATIONS_PAGE_SIZE
const params = buildObservationListParams(values, OBSERVATIONS_PAGE_SIZE, offset)
const response = await visionScannersObservationsList(String(teamId), props.id, params)
- actions.loadObservationsSuccess(response.results ?? [], response.count ?? 0)
- } catch {
+ // Drop out-of-order responses — a newer load (filter change, poll, pagination) owns the table.
+ breakpoint()
+ const results = response.results ?? []
+ const count = response.count ?? 0
+ // A shrunken set (narrowed filter, concurrent change) can strand an out-of-range page.
+ if (results.length === 0 && count > 0 && values.observationsPage > 1) {
+ actions.setObservationsPage(Math.ceil(count / OBSERVATIONS_PAGE_SIZE))
+ return
+ }
+ actions.loadObservationsSuccess(results, count)
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
actions.loadObservationsFailure()
}
},
@@ -946,13 +902,14 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
actions.loadObservationStats()
},
- loadObservationStats: async () => {
+ loadObservationStats: async (_, breakpoint) => {
if (props.id === 'new') {
actions.loadObservationStatsFailure()
return
}
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
+ actions.loadObservationStatsFailure()
return
}
try {
@@ -963,27 +920,20 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
...params,
recent_days: recentDays,
})
+ // Drop out-of-order responses; the superseding load reschedules the poll itself.
+ breakpoint()
actions.loadObservationStatsSuccess(response)
- } catch {
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
actions.loadObservationStatsFailure()
}
},
- loadObservationStatsSuccess: () => {
- scheduleObservationPoll(
- cache.disposables,
- values.hasObservationsInFlight || Date.now() < values.pollUntil,
- () => reloadObservationsAndStats(true)
- )
- },
- // Reschedule on failure too — a transient API hiccup shouldn't permanently kill the polling cycle.
- loadObservationStatsFailure: () => {
- scheduleObservationPoll(
- cache.disposables,
- values.hasObservationsInFlight || Date.now() < values.pollUntil,
- () => reloadObservationsAndStats(true)
- )
- },
+ // Rescheduled on failure too — a transient API hiccup shouldn't permanently kill the polling cycle.
+ loadObservationStatsSuccess: reschedulePoll,
+ loadObservationStatsFailure: reschedulePoll,
}
}),
@@ -997,9 +947,7 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
next.page = String(values.observationsPage)
}
const sort = values.observationsSort
- if (sort && !(sort.columnKey === 'created_at' && sort.order === -1)) {
- next.sort = `${sort.order === -1 ? '-' : ''}${sort.columnKey}`
- }
+ next.sort = serializeSortParam(sort, { columnKey: 'created_at', order: -1 })
Object.assign(next, observationFilterParams(values))
return next
}
@@ -1027,25 +975,30 @@ export const replayScannerLogic = kea<replayScannerLogicType>([
}),
urlToAction(({ actions, values, props }) => ({
- // Restore as a single atomic action so the page reducer isn't reset by individual filter setters.
- // Idempotent: we only dispatch when something actually differs from current state.
+ // Restore as one atomic action (individual setters would reset the page); dispatch only on actual change.
[urls.replayVision(props.id)]: (_, searchParams) => {
const pageRaw = Number(searchParams.page ?? 1)
const page = Number.isFinite(pageRaw) ? Math.max(1, pageRaw) : 1
const sort = parseSortParam(searchParams.sort) ?? { columnKey: 'created_at', order: -1 }
- const status = parseCsvParam<ObservationStatusValue>(searchParams.status)
- const triggeredBy = parseCsvParam<ObservationTriggeredByValue>(searchParams.triggered_by)
- const verdict = parseCsvParam<ObservationVerdictValue>(searchParams.verdict)
+ const status = parseCsvParam<ObservationStatusValue>(searchParams.status, OBSERVATION_STATUS_VALUES)
+ const triggeredBy = parseCsvParam<ObservationTriggeredByValue>(
+ searchParams.triggered_by,
+ OBSERVATION_TRIGGERED_BY_VALUES
+ )
+ const verdict = parseCsvParam<ObservationVerdictValue>(searchParams.verdict, OBSERVATION_VERDICT_VALUES)
const tags = parseCsvParam<string>(searchParams.tags)
- const subject = typeof searchParams.recording_subject === 'string' ? searchParams.recording_subject : ''
+ const subjectRaw = searchParams.recording_subject
+ // String() so a numeric-looking subject (`?recording_subject=12345`) survives the router's coercion.
+ const subject =
+ typeof subjectRaw === 'string' ? subjectRaw : typeof subjectRaw === 'number' ? String(subjectRaw) : ''
const sameAsCurrent =
page === values.observationsPage &&
sort.columnKey === values.observationsSort?.columnKey &&
sort.order === values.observationsSort?.order &&
- equal(status, values.observationStatusFilter) &&
- equal(triggeredBy, values.observationTriggeredByFilter) &&
- equal(verdict, values.observationVerdictFilter) &&
- equal(tags, values.observationTagFilter) &&
+ objectsEqual(status, values.observationStatusFilter) &&
+ objectsEqual(triggeredBy, values.observationTriggeredByFilter) &&
+ objectsEqual(verdict, values.observationVerdictFilter) &&
+ objectsEqual(tags, values.observationTagFilter) &&
subject === values.observationSubjectFilter
if (!sameAsCurrent) {
actions.restoreObservationsTableState({ page, sort, status, triggeredBy, verdict, tags, subject })
@@ -1116,25 +1069,3 @@ export function shouldGuardScannerNavigation(params: {
}
return true
}
-
-export function parseSortParam(value: string | undefined): ObservationsSorting | null {
- if (typeof value !== 'string' || value.length === 0) {
- return null
- }
- const descending = value.startsWith('-')
- const columnKey = descending ? value.slice(1) : value
- if (!columnKey) {
- return null
- }
- return { columnKey, order: descending ? -1 : 1 }
-}
-
-export function parseCsvParam<T extends string>(value: string | undefined): T[] {
- if (typeof value !== 'string' || value.length === 0) {
- return []
- }
- return value
- .split(',')
- .map((v) => v.trim())
- .filter((v) => v.length > 0) as T[]
-}
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
index 1e5b574cd80f..a856c8716412 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.test.ts
@@ -379,4 +379,23 @@ describe('replayScannersLogic', () => {
chartDateTo: null,
})
})
+
+ it('clamps back to the last valid page when the requested page is past the shrunken result set', async () => {
+ // e.g. the last scanner on page 2 was just deleted: offset=50 is now empty while count says one page.
+ useMocks({
+ get: {
+ '/api/projects/:team/vision/scanners/': ({ request }: { request: Request }) => {
+ const offset = Number(new URL(request.url).searchParams.get('offset') ?? 0)
+ return offset > 0
+ ? [200, { results: [], count: 50 }]
+ : [200, { results: [makeScanner({ id: 'a' })], count: 50 }]
+ },
+ },
+ })
+
+ await expectLogic(logic, () => logic.actions.setScannersFilters({ page: 2 })).toFinishAllListeners()
+
+ expect(logic.values.filters.page).toBe(1)
+ expect(logic.values.scanners).toHaveLength(1)
+ })
})
diff --git a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
index 030fadfc414a..82fd8d5fc841 100644
--- a/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
+++ b/products/replay_vision/frontend/replay_scanners/replayScannersLogic.ts
@@ -1,9 +1,10 @@
-import equal from 'fast-deep-equal'
-import { actions, afterMount, kea, listeners, path, reducers, selectors } from 'kea'
+import { actions, afterMount, isBreakpoint, kea, listeners, path, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
+import { objectsEqual } from 'lib/utils/objects'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -15,7 +16,8 @@ import {
visionScannersStatsRetrieve,
} from '../generated/api'
import type { ScannerStatsResponseApi, UserBasicApi, VisionScannersListParams } from '../generated/api.schemas'
-import { visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { refreshVisionQuota, visionQuotaLogic } from '../logics/visionQuotaLogic'
+import { csvParam, parseCsvParam, parseSortParam, serializeSortParam } from '../utils/urlParams'
import type { replayScannersLogicType } from './replayScannersLogicType'
import {
ENABLED_OPTIONS,
@@ -70,18 +72,6 @@ export const DEFAULT_FILTERS: ScannersFilters = {
sort: DEFAULT_SORT,
}
-const csv = (values: string[]): string | undefined => (values.length > 0 ? values.join(',') : undefined)
-const splitCsv = (value: unknown): string[] =>
- // The router coerces a single numeric param to a number, so coerce back to a string before splitting.
- value === null || value === undefined || value === ''
- ? []
- : String(value)
- .split(',')
- .map((v) => v.trim())
- .filter(Boolean)
-const fromCsv = <T extends string>(value: unknown, allowed: readonly T[]): T[] =>
- splitCsv(value).filter((v): v is T => (allowed as readonly string[]).includes(v))
-
export function resolveScannerOrderByKey(columnKey: string): ScannerOrderKey | null {
return (SORTABLE_COLUMN_KEYS as readonly string[]).includes(columnKey) ? (columnKey as ScannerOrderKey) : null
}
@@ -126,33 +116,19 @@ export function buildScannerListParams(
return params
}
-function parseSortParam(value: unknown): ScannersSorting | null {
- if (typeof value !== 'string' || value.length === 0) {
- return null
- }
- const descending = value.startsWith('-')
- const key = resolveScannerOrderByKey(descending ? value.slice(1) : value)
- if (!key) {
- return null
- }
- return { columnKey: key, order: descending ? -1 : 1 }
-}
-
export const replayScannersLogic = kea<replayScannersLogicType>([
path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'replayScannersLogic']),
actions({
loadScanners: true,
- loadScannersSuccess: (scanners: ReplayScanner[], total: number) => ({ scanners, total }),
- loadScannersFailure: (error: string) => ({ error }),
+ // Declared here so the actions stay zero-arg despite the loaders' payload/breakpoint parameters.
loadCreators: true,
- loadCreatorsSuccess: (creators: UserBasicApi[]) => ({ creators }),
- loadCreatorsFailure: true,
loadScannerStats: true,
- loadScannerStatsSuccess: (stats: ScannerStatsResponseApi) => ({ stats }),
- loadScannerStatsFailure: true,
+ loadScannersSuccess: (scanners: ReplayScanner[], total: number) => ({ scanners, total }),
+ loadScannersFailure: (error: string) => ({ error }),
deleteScanner: (id: string) => ({ id }),
deleteScannerSuccess: (id: string) => ({ id }),
+ setScannerDeleting: (id: string, deleting: boolean) => ({ id, deleting }),
toggleScannerEnabled: (id: string) => ({ id }),
toggleScannerEnabledDone: (id: string) => ({ id }),
revertScannerEnabled: (id: string) => ({ id }),
@@ -161,6 +137,44 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
clearFilters: true,
}),
+ loaders(({ values }) => ({
+ creators: [
+ [] as UserBasicApi[],
+ {
+ loadCreators: async () => {
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return values.creators
+ }
+ try {
+ const response = await visionScannersCreatorsRetrieve(String(teamId))
+ return response.creators ?? []
+ } catch {
+ return values.creators
+ }
+ },
+ },
+ ],
+ scannerStats: [
+ null as ScannerStatsResponseApi | null,
+ {
+ loadScannerStats: async (_, breakpoint) => {
+ // Debounce so a burst of mutations (rapid toggles, bulk delete) coalesces into one refetch.
+ await breakpoint(50)
+ const teamId = teamLogic.values.currentTeamId
+ if (!teamId) {
+ return values.scannerStats
+ }
+ try {
+ return await visionScannersStatsRetrieve(String(teamId))
+ } catch {
+ return values.scannerStats
+ }
+ },
+ },
+ ],
+ })),
+
reducers({
scanners: [
[] as ReplayScanner[],
@@ -207,16 +221,11 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
revertScannerEnabled: (state, { id }) => state.filter((i) => i !== id),
},
],
- creators: [
- [] as UserBasicApi[],
- {
- loadCreatorsSuccess: (_, { creators }) => creators,
- },
- ],
- scannerStats: [
- null as ScannerStatsResponseApi | null,
+ deletingIds: [
+ [] as string[],
{
- loadScannerStatsSuccess: (_, { stats }) => stats,
+ setScannerDeleting: (state, { id, deleting }) =>
+ deleting ? [...state, id] : state.filter((i) => i !== id),
},
],
scannersLoading: [
@@ -227,14 +236,6 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
loadScannersFailure: () => false,
},
],
- scannerStatsLoading: [
- false,
- {
- loadScannerStats: () => true,
- loadScannerStatsSuccess: () => false,
- loadScannerStatsFailure: () => false,
- },
- ],
chartDateFrom: [
'-30d' as string | null,
{
@@ -250,9 +251,10 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
}),
listeners(({ actions, values }) => ({
- loadScanners: async () => {
+ loadScanners: async (_, breakpoint) => {
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
+ actions.loadScannersFailure('No team in context') // Clear the loading flag; a bare return spins forever.
return
}
try {
@@ -270,22 +272,41 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
offset
)
const response = await visionScannersList(String(teamId), params)
- actions.loadScannersSuccess(scannersFromApi(response.results ?? []), response.count ?? 0)
+ // Drop out-of-order responses — the most recent filter/page change owns the table.
+ breakpoint()
+ const results = response.results ?? []
+ const count = response.count ?? 0
+ // A shrunken set (delete, narrowed filter, concurrent change) can strand an out-of-range page.
+ if (results.length === 0 && count > 0 && filters.page > 1) {
+ actions.setScannersFilters({ page: Math.ceil(count / SCANNERS_PAGE_SIZE) })
+ return
+ }
+ actions.loadScannersSuccess(scannersFromApi(results), count)
} catch (error: any) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
lemonToast.error(`Failed to load scanners${error.detail ? `: ${error.detail}` : ''}`)
actions.loadScannersFailure(String(error))
}
},
- // Any change that affects the result set has to refetch.
- setScannersFilters: () => actions.loadScanners(),
+ // Refetch on any result-set change; debounce live search keystrokes only — URL restores must load immediately.
+ setScannersFilters: async ({ filters, replace }, breakpoint) => {
+ if (filters.search !== undefined && !replace) {
+ await breakpoint(300)
+ }
+ actions.loadScanners()
+ },
clearFilters: () => actions.loadScanners(),
deleteScanner: async ({ id }) => {
const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
+ // The in-flight guard keeps a double-click from double-applying the optimistic quota delta below.
+ if (!teamId || values.deletingIds.includes(id)) {
return
}
+ actions.setScannerDeleting(id, true)
// Deleting an enabled scanner removes its known contribution from the fleet sum — exact, so apply it now.
const scanner = values.scanners.find((s) => s.id === id)
const delta = scanner?.enabled ? -(scanner.estimated_monthly_observations ?? 0) : 0
@@ -297,34 +318,8 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
} catch (error: any) {
visionQuotaLogic.findMounted()?.actions.adjustProjectedMonthly(-delta)
lemonToast.error(`Failed to delete scanner${error.detail ? `: ${error.detail}` : ''}`)
- }
- },
-
- loadCreators: async () => {
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- const response = await visionScannersCreatorsRetrieve(String(teamId))
- actions.loadCreatorsSuccess(response.creators ?? [])
- } catch {
- actions.loadCreatorsFailure()
- }
- },
-
- loadScannerStats: async (_, breakpoint) => {
- // Debounce so a burst of mutations (rapid toggles, bulk delete) coalesces into one refetch.
- await breakpoint(50)
- const teamId = teamLogic.values.currentTeamId
- if (!teamId) {
- return
- }
- try {
- const response = await visionScannersStatsRetrieve(String(teamId))
- actions.loadScannerStatsSuccess(response)
- } catch {
- actions.loadScannerStatsFailure()
+ } finally {
+ actions.setScannerDeleting(id, false)
}
},
@@ -333,11 +328,11 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
actions.loadScanners()
actions.loadCreators()
actions.loadScannerStats()
- visionQuotaLogic.findMounted()?.actions.loadQuota()
+ refreshVisionQuota()
},
toggleScannerEnabledDone: () => {
actions.loadScannerStats()
- visionQuotaLogic.findMounted()?.actions.loadQuota()
+ refreshVisionQuota()
},
toggleScannerEnabled: async ({ id }) => {
@@ -402,19 +397,15 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
trackedActionToUrl(({ values }) => {
const buildUrl = (): [string, Record<string, string | undefined>, undefined, { replace: true }] => {
const { filters } = values
- const sortParam =
- filters.sort &&
- !(filters.sort.columnKey === DEFAULT_SORT.columnKey && filters.sort.order === DEFAULT_SORT.order)
- ? `${filters.sort.order === -1 ? '-' : ''}${filters.sort.columnKey}`
- : undefined
+ const sortParam = serializeSortParam(filters.sort, DEFAULT_SORT)
return [
urls.replayVision(),
{
...router.values.searchParams,
search: filters.search || undefined,
- enabled: csv(filters.enabledFilter),
- type: csv(filters.scannerTypeFilter),
- created_by: csv(filters.createdByFilter),
+ enabled: csvParam(filters.enabledFilter),
+ type: csvParam(filters.scannerTypeFilter),
+ created_by: csvParam(filters.createdByFilter),
page: filters.page > 1 ? String(filters.page) : undefined,
sort: sortParam,
},
@@ -433,13 +424,13 @@ export const replayScannersLogic = kea<replayScannersLogicType>([
const pageRaw = Number(searchParams.page ?? 1)
const parsed: ScannersFilters = {
search: typeof searchParams.search === 'string' ? searchParams.search : '',
- enabledFilter: fromCsv<EnabledFilter>(searchParams.enabled, ALL_ENABLED),
- scannerTypeFilter: fromCsv<ScannerType>(searchParams.type, ALL_SCANNER_TYPES),
- createdByFilter: splitCsv(searchParams.created_by),
+ enabledFilter: parseCsvParam<EnabledFilter>(searchParams.enabled, ALL_ENABLED),
+ scannerTypeFilter: parseCsvParam<ScannerType>(searchParams.type, ALL_SCANNER_TYPES),
+ createdByFilter: parseCsvParam(searchParams.created_by),
page: Number.isFinite(pageRaw) ? Math.max(1, pageRaw) : 1,
- sort: parseSortParam(searchParams.sort) ?? DEFAULT_SORT,
+ sort: parseSortParam(searchParams.sort, resolveScannerOrderByKey) ?? DEFAULT_SORT,
}
- const changed = !equal(parsed, values.filters)
+ const changed = !objectsEqual(parsed, values.filters)
if (changed) {
actions.setScannersFilters(parsed, true)
} else if (!cache.initialLoad) {
diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts
new file mode 100644
index 000000000000..5b2004846631
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.test.ts
@@ -0,0 +1,66 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+
+import { scannerRunTabLogic } from './scannerRunTabLogic'
+
+describe('scannerRunTabLogic', () => {
+ let logic: ReturnType<typeof scannerRunTabLogic.build>
+ let requestedUrls: string[]
+
+ beforeEach(() => {
+ requestedUrls = []
+ useMocks({
+ get: {
+ '/api/projects/:team/vision/scanners/:id/': () => [404, {}],
+ '/api/projects/:team/vision/scanners/:id/observations/': ({ request }: { request: Request }) => {
+ requestedUrls.push(request.url)
+ return [
+ 200,
+ {
+ // Newest-first, mirroring the API's -created_at default ordering.
+ results: [
+ { id: 'obs-retry', session_id: 's1', status: 'running' },
+ { id: 'obs-original', session_id: 's1', status: 'failed' },
+ { id: 'obs-2', session_id: 's2', status: 'succeeded' },
+ ],
+ count: 3,
+ },
+ ]
+ },
+ },
+ })
+ initKeaTests()
+ logic = scannerRunTabLogic({ scannerId: 'scanner-1' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic?.unmount()
+ })
+
+ it('keeps the newest observation per session and does not cap the page to the visible-row count', async () => {
+ await expectLogic(logic, () => logic.actions.setVisibleSessionIds(['s1', 's2'])).toDispatchActions([
+ 'loadObservationsSuccess',
+ ])
+
+ // A retried session shows its fresh running observation, not the stale failed one the API lists after it.
+ expect(logic.values.observationBySession).toEqual({
+ s1: { id: 'obs-retry', status: 'running' },
+ s2: { id: 'obs-2', status: 'succeeded' },
+ })
+ // The connected replayScannerLogic fires its own paged list load; ours is the session_id lookup.
+ const lookupUrl = requestedUrls.find((url) => url.includes('session_id='))
+ expect(lookupUrl).not.toBeUndefined()
+ expect(lookupUrl).not.toContain('limit=')
+ })
+
+ it('releases the pending bridge once the scanned session lands in the lookup', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.setPendingId('s1')
+ logic.actions.setVisibleSessionIds(['s1', 's2'])
+ }).toDispatchActions(['loadObservationsSuccess'])
+ expect(logic.values.pendingId).toBeNull()
+ })
+})
diff --git a/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts
new file mode 100644
index 000000000000..d948d517cd1f
--- /dev/null
+++ b/products/replay_vision/frontend/replay_scanners/scannerRunTabLogic.ts
@@ -0,0 +1,153 @@
+import { actions, connect, isBreakpoint, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+
+import { visionScannersObservationsList } from '../generated/api'
+import type { ReplayObservationApi } from '../generated/api.schemas'
+import { scheduleObservationPoll } from '../logics/observationPolling'
+import { replayScannerLogic } from './replayScannerLogic'
+import type { scannerRunTabLogicType } from './scannerRunTabLogicType'
+
+export interface RowObservation {
+ id: string
+ status: ReplayObservationApi['status']
+}
+
+export const IN_PROGRESS_STATUSES = new Set<string>(['pending', 'running'])
+
+export interface ScannerRunTabLogicProps {
+ scannerId: string
+}
+
+/** Backs the on-demand recordings list: per-session observation lookup, scan bridging, and result polling. */
+export const scannerRunTabLogic = kea<scannerRunTabLogicType>([
+ path(['products', 'replay_vision', 'frontend', 'replay_scanners', 'scannerRunTabLogic']),
+ props({} as ScannerRunTabLogicProps),
+ key((props) => props.scannerId),
+
+ connect((props: ScannerRunTabLogicProps) => ({
+ values: [replayScannerLogic({ id: props.scannerId }), ['triggeringOnDemandObservation']],
+ actions: [
+ replayScannerLogic({ id: props.scannerId }),
+ ['triggerOnDemandObservation', 'triggerOnDemandObservationSuccess', 'triggerOnDemandObservationFailure'],
+ ],
+ })),
+
+ actions({
+ setVisibleSessionIds: (sessionIds: string[]) => ({ sessionIds }),
+ startScan: (sessionId: string) => ({ sessionId }),
+ setPendingId: (sessionId: string) => ({ sessionId }),
+ loadObservations: (background = false) => ({ background }),
+ loadObservationsSuccess: (bySession: Record<string, RowObservation>) => ({ bySession }),
+ loadObservationsFailure: true,
+ }),
+
+ reducers({
+ visibleSessionIds: [
+ [] as string[],
+ {
+ setVisibleSessionIds: (_, { sessionIds }) => sessionIds,
+ },
+ ],
+ observationBySession: [
+ {} as Record<string, RowObservation>,
+ {
+ // Merge over the previous map so rows scrolled out of the fetch keep their last-known state.
+ loadObservationsSuccess: (state, { bySession }) => ({ ...state, ...bySession }),
+ },
+ ],
+ // Bridges click-to-row gap: kept until the observation lands or the trigger fails, so the spinner holds.
+ pendingId: [
+ null as string | null,
+ {
+ setPendingId: (_, { sessionId }) => sessionId,
+ triggerOnDemandObservationFailure: () => null,
+ loadObservationsSuccess: (state, { bySession }) => (state && bySession[state] ? null : state),
+ },
+ ],
+ // Drives the table's loading bar on foreground refetches only; background polls reload silently.
+ refreshingObservations: [
+ false,
+ {
+ loadObservations: (state, { background }) => (background ? state : true),
+ loadObservationsSuccess: () => false,
+ loadObservationsFailure: () => false,
+ },
+ ],
+ }),
+
+ selectors({
+ shouldPoll: [
+ (s) => [s.visibleSessionIds, s.observationBySession, s.pendingId],
+ (
+ visibleSessionIds: string[],
+ observationBySession: Record<string, RowObservation>,
+ pendingId: string | null
+ ): boolean =>
+ pendingId !== null ||
+ visibleSessionIds.some((id) => {
+ const observation = observationBySession[id]
+ return !!observation && IN_PROGRESS_STATUSES.has(observation.status)
+ }),
+ ],
+ }),
+
+ listeners(({ actions, props, values, cache }) => {
+ // Rescheduled on failure too — a transient API hiccup shouldn't permanently kill the polling cycle.
+ const reschedulePoll = (): void =>
+ scheduleObservationPoll(cache.disposables, values.shouldPoll, () => actions.loadObservations(true))
+ return {
+ setVisibleSessionIds: ({ sessionIds }) => {
+ if (sessionIds.length > 0) {
+ actions.loadObservations()
+ }
+ },
+
+ startScan: ({ sessionId }) => {
+ if (values.triggeringOnDemandObservation || values.pendingId) {
+ return
+ }
+ actions.setPendingId(sessionId)
+ actions.triggerOnDemandObservation(sessionId, true)
+ },
+
+ // A successful trigger creates a pending observation server-side — refetch to pick it up.
+ triggerOnDemandObservationSuccess: () => actions.loadObservations(),
+
+ loadObservations: async (_, breakpoint) => {
+ const teamId = teamLogic.values.currentTeamId
+ const sessionIds = values.visibleSessionIds
+ if (!teamId || sessionIds.length === 0) {
+ actions.loadObservationsFailure() // Clear the foreground loading flag; a bare return spins forever.
+ return
+ }
+ try {
+ // No limit coupling to visible rows — retries stack observations and a truncated page hides scans.
+ // Ordering pinned: the newest-wins mapping below depends on it, not on the API default.
+ const response = await visionScannersObservationsList(String(teamId), props.scannerId, {
+ session_id: sessionIds.join(','),
+ order_by: '-created_at',
+ })
+ breakpoint()
+ const bySession: Record<string, RowObservation> = {}
+ for (const observation of response.results ?? []) {
+ // Results are newest-first — the first observation per session is the one the row reflects.
+ if (!(observation.session_id in bySession)) {
+ bySession[observation.session_id] = { id: observation.id, status: observation.status }
+ }
+ }
+ actions.loadObservationsSuccess(bySession)
+ } catch (error) {
+ if (error instanceof Error && isBreakpoint(error)) {
+ throw error
+ }
+ // Best-effort enrichment — on failure the rows just stay scannable, but keep polling alive.
+ actions.loadObservationsFailure()
+ }
+ },
+
+ loadObservationsSuccess: reschedulePoll,
+ loadObservationsFailure: reschedulePoll,
+ }
+ }),
+])
diff --git a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
index 3e733732b1c4..89719cb6ab32 100644
--- a/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
+++ b/products/replay_vision/frontend/replay_scanners/scannerTemplates.ts
@@ -11,17 +11,7 @@ import type {
} from './types'
import { DEFAULT_MODEL, DEFAULT_PROVIDER } from './types'
-export type ScannerTemplateIcon =
- | 'bolt'
- | 'warning'
- | 'notebook'
- | 'target'
- | 'thumbs-down'
- | 'star'
- | 'search'
- | 'magic'
- | 'bug'
- | 'check'
+export type ScannerTemplateIcon = 'warning' | 'notebook' | 'target' | 'thumbs-down' | 'check'
interface BaseTemplate {
key: string
@@ -144,6 +134,7 @@ export function newScanner(templateKey?: string | null): ReplayScanner {
created_at: dayjs().toISOString(),
updated_at: dayjs().toISOString(),
created_by: null,
+ estimated_monthly_observations: null,
} as const
const template = findScannerTemplate(templateKey ?? undefined)
@@ -153,7 +144,8 @@ export function newScanner(templateKey?: string | null): ReplayScanner {
name: template.scanner_name,
description: template.scanner_description,
scanner_type: template.scanner_type,
- scanner_config: template.scanner_config,
+ // Cloned so an in-place form mutation can never corrupt the module-level template.
+ scanner_config: structuredClone(template.scanner_config),
} as ReplayScanner
}
return {
diff --git a/products/replay_vision/frontend/replay_scanners/types.ts b/products/replay_vision/frontend/replay_scanners/types.ts
index abba2fbf872a..461af47308c7 100644
--- a/products/replay_vision/frontend/replay_scanners/types.ts
+++ b/products/replay_vision/frontend/replay_scanners/types.ts
@@ -3,9 +3,14 @@ import { LemonTagType } from '@posthog/lemon-ui'
import { RecordingsQuery } from '~/queries/schema/schema-general'
import { ScannerModelEnumApi } from '../generated/api.schemas'
-import type { PatchedReplayScannerApi, ReplayScannerApi } from '../generated/api.schemas'
+import type {
+ PatchedReplayScannerApi,
+ ReplayScannerApi,
+ ScannerTypeEnumApi,
+ UserBasicApi,
+} from '../generated/api.schemas'
-export type ScannerType = 'monitor' | 'classifier' | 'scorer' | 'summarizer'
+export type ScannerType = ScannerTypeEnumApi
export const SCANNER_TYPE_TAG_TYPE: Record<ScannerType, LemonTagType> = {
monitor: 'primary',
@@ -124,9 +129,7 @@ export function scannerTypeLabel(scannerType: ScannerType | null | undefined): s
return SCANNER_TYPE_OPTIONS.find((opt) => opt.value === scannerType)?.label ?? scannerType
}
-export function createdByLabel(
- user: { id: number; first_name?: string; last_name?: string; email?: string } | null
-): string {
+export function createdByLabel(user: ScannerCreatedBy | null): string {
if (!user) {
return ''
}
@@ -185,24 +188,15 @@ export type ScannerConfig =
| ClassifierScannerConfig
| ScorerScannerConfig
-export interface BaseReplayScanner {
- id: string
- name: string
- description?: string
- enabled: boolean
- sampling_rate: number
- query: RecordingsQuery | null
- provider: string
- model: string
- emits_signals: boolean
- scanner_version: number
- estimated_monthly_observations?: number | null
- last_swept_at: string
- created_at: string
- updated_at: string
- created_by: { id: number; first_name: string; last_name?: string; email?: string } | null
- deleted?: boolean
-}
+// hedgehog_config's nullable index-signature type trips DeepPartial and ProfilePicture; the UI never reads it.
+export type ScannerCreatedBy = Omit<UserBasicApi, 'hedgehog_config'>
+
+// Derived from the generated schema so serializer changes fail typecheck; write-optional fields carry defaults.
+export type BaseReplayScanner = Omit<ReplayScannerApi, 'scanner_type' | 'scanner_config' | 'query' | 'created_by'> &
+ Required<Pick<ReplayScannerApi, 'sampling_rate' | 'enabled' | 'emits_signals' | 'provider'>> & {
+ query: RecordingsQuery | null
+ created_by: ScannerCreatedBy | null
+ }
export interface MonitorScanner extends BaseReplayScanner {
scanner_type: 'monitor'
@@ -226,8 +220,13 @@ export interface ScorerScanner extends BaseReplayScanner {
export type ReplayScanner = MonitorScanner | SummarizerScanner | ClassifierScanner | ScorerScanner
-// The API exposes scanner_config and query as `unknown`. The client narrows them via
-// the scanner_type discriminator, so conversion is contained to this single boundary.
+/** Narrow a snapshot's untyped scanner_config at one boundary; pair with the snapshot's scanner_type to pick the variant. */
+export function configFromSnapshot(snapshot: { scanner_config?: unknown } | null | undefined): ScannerConfig | null {
+ const config = snapshot?.scanner_config
+ return config && typeof config === 'object' ? (config as ScannerConfig) : null
+}
+
+// The API types scanner_config and query as `unknown`; the scanner_type discriminator narrows them here only.
export function scannerFromApi(api: ReplayScannerApi): ReplayScanner {
return api as unknown as ReplayScanner
}
diff --git a/products/replay_vision/frontend/scenes/.gitkeep b/products/replay_vision/frontend/scenes/.gitkeep
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/replay_vision/frontend/tests/.gitkeep b/products/replay_vision/frontend/tests/.gitkeep
deleted file mode 100644
index e69de29bb2d1..000000000000
diff --git a/products/replay_vision/frontend/utils/observation.test.ts b/products/replay_vision/frontend/utils/observation.test.ts
deleted file mode 100644
index 4e1eefaf6437..000000000000
--- a/products/replay_vision/frontend/utils/observation.test.ts
+++ /dev/null
@@ -1,79 +0,0 @@
-import type { ReplayObservationApi } from '../generated/api.schemas'
-import { readFixedTags, readFreeformTags, readModelOutput, readScore, readTags, readVerdict } from './observation'
-
-function makeObservation(modelOutput: Record<string, unknown> | null | undefined): ReplayObservationApi {
- return {
- id: 'o1',
- scanner_result:
- modelOutput === undefined ? undefined : ({ model_output: modelOutput } as Record<string, unknown>),
- } as unknown as ReplayObservationApi
-}
-
-describe('readModelOutput', () => {
- it('returns the model_output object when present', () => {
- expect(readModelOutput(makeObservation({ score: 7 }))).toEqual({ score: 7 })
- })
-
- it('returns null when scanner_result is absent', () => {
- expect(readModelOutput(makeObservation(undefined))).toBeNull()
- })
-
- it.each([null, 'hello', 42, true])('returns null when model_output is %p', (badShape) => {
- expect(readModelOutput(makeObservation(badShape as Record<string, unknown> | null))).toBeNull()
- })
-})
-
-describe('readScore', () => {
- it('returns the numeric score', () => {
- expect(readScore(makeObservation({ score: 7.5 }))).toBe(7.5)
- })
-
- it.each(['7', null, undefined, true, [1, 2]])('returns null for non-numeric score %p', (badScore) => {
- expect(readScore(makeObservation({ score: badScore }))).toBeNull()
- })
-
- it('returns null when model_output is absent', () => {
- expect(readScore(makeObservation(undefined))).toBeNull()
- })
-})
-
-describe('readVerdict', () => {
- it.each(['yes', 'no', 'inconclusive'] as const)('accepts %s', (verdict) => {
- expect(readVerdict(makeObservation({ verdict }))).toBe(verdict)
- })
-
- it.each(['Yes', 'YES', 'maybe', '', 1, null])('rejects non-canonical verdict %p', (bad) => {
- expect(readVerdict(makeObservation({ verdict: bad }))).toBeNull()
- })
-})
-
-describe('readFixedTags / readFreeformTags / readTags', () => {
- it('returns the fixed tag array', () => {
- expect(readFixedTags(makeObservation({ tags: ['bug', 'frustration'] }))).toEqual(['bug', 'frustration'])
- })
-
- it('filters non-string entries from the fixed tag array', () => {
- expect(readFixedTags(makeObservation({ tags: ['bug', 42, null, 'frustration'] }))).toEqual([
- 'bug',
- 'frustration',
- ])
- })
-
- it('returns an empty array when tags is missing or wrong shape', () => {
- expect(readFixedTags(makeObservation({}))).toEqual([])
- expect(readFixedTags(makeObservation({ tags: 'bug' }))).toEqual([])
- expect(readFixedTags(makeObservation(undefined))).toEqual([])
- })
-
- it('reads freeform tags from tags_freeform', () => {
- expect(readFreeformTags(makeObservation({ tags_freeform: ['custom'] }))).toEqual(['custom'])
- })
-
- it('concatenates fixed then freeform in readTags', () => {
- expect(readTags(makeObservation({ tags: ['bug'], tags_freeform: ['custom', 'note'] }))).toEqual([
- 'bug',
- 'custom',
- 'note',
- ])
- })
-})
diff --git a/products/replay_vision/frontend/utils/observation.ts b/products/replay_vision/frontend/utils/observation.ts
deleted file mode 100644
index 8859c4868aec..000000000000
--- a/products/replay_vision/frontend/utils/observation.ts
+++ /dev/null
@@ -1,39 +0,0 @@
-import type { ReplayObservationApi } from '../generated/api.schemas'
-
-export function readModelOutput(obs: ReplayObservationApi): Record<string, unknown> | null {
- const out = obs.scanner_result?.model_output
- return out && typeof out === 'object' ? (out as Record<string, unknown>) : null
-}
-
-export function readScore(obs: ReplayObservationApi): number | null {
- const raw = readModelOutput(obs)?.score
- return typeof raw === 'number' ? raw : null
-}
-
-export type MonitorVerdict = 'yes' | 'no' | 'inconclusive'
-
-export function readVerdict(obs: ReplayObservationApi): MonitorVerdict | null {
- const raw = readModelOutput(obs)?.verdict
- return raw === 'yes' || raw === 'no' || raw === 'inconclusive' ? raw : null
-}
-
-function readStringArray(value: unknown): string[] {
- if (!Array.isArray(value)) {
- return []
- }
- return value.filter((t): t is string => typeof t === 'string')
-}
-
-/** Tags from the scanner's configured vocabulary. */
-export function readFixedTags(obs: ReplayObservationApi): string[] {
- return readStringArray(readModelOutput(obs)?.tags)
-}
-
-/** Tags the model emits outside the vocabulary when `allow_freeform_tags` is on. */
-export function readFreeformTags(obs: ReplayObservationApi): string[] {
- return readStringArray(readModelOutput(obs)?.tags_freeform)
-}
-
-export function readTags(obs: ReplayObservationApi): string[] {
- return [...readFixedTags(obs), ...readFreeformTags(obs)]
-}
diff --git a/products/replay_vision/frontend/utils/quotaProjection.ts b/products/replay_vision/frontend/utils/quotaProjection.ts
index 066b259b6f0b..a3362c660b44 100644
--- a/products/replay_vision/frontend/utils/quotaProjection.ts
+++ b/products/replay_vision/frontend/utils/quotaProjection.ts
@@ -96,17 +96,31 @@ export function splitProjectedPct(
* Assumes block-only overage policy; revisit when `usage_based` lands so we don't disable on metered orgs.
*/
export function quotaUx(quota: VisionQuotaApi | null): { disabledReason?: string; tooltip?: string } {
- if (!quota || quota.monthly_quota <= 0) {
+ const state = quotaBannerState(quota)
+ if (!state.kind) {
return {}
}
+ if (state.kind === 'exhausted') {
+ return { disabledReason: `Monthly observation quota reached. Resets ${state.resetsOn}.` }
+ }
+ return {
+ tooltip: `${state.quota.remaining.toLocaleString()} observations left this month (resets ${state.resetsOn})`,
+ }
+}
+
+/** One shared exhausted/warning classification so the banner, triggers, and tooltips can't drift. */
+export function quotaBannerState(
+ quota: VisionQuotaApi | null
+): { kind: null } | { kind: 'exhausted' | 'warning'; resetsOn: string; quota: VisionQuotaApi } {
+ if (!quota || quota.monthly_quota <= 0) {
+ return { kind: null }
+ }
const resetsOn = dayjs(quota.period_end).format('MMMM D')
if (quota.exhausted) {
- return { disabledReason: `Monthly observation quota reached. Resets ${resetsOn}.` }
+ return { kind: 'exhausted', resetsOn, quota }
}
if (quota.usage_this_month / quota.monthly_quota >= QUOTA_WARN_THRESHOLD) {
- return {
- tooltip: `${quota.remaining.toLocaleString()} observations left this month (resets ${resetsOn})`,
- }
+ return { kind: 'warning', resetsOn, quota }
}
- return {}
+ return { kind: null }
}
diff --git a/products/replay_vision/frontend/utils/urlParams.ts b/products/replay_vision/frontend/utils/urlParams.ts
new file mode 100644
index 000000000000..b2e5c09623d9
--- /dev/null
+++ b/products/replay_vision/frontend/utils/urlParams.ts
@@ -0,0 +1,51 @@
+/** CSV + sort-token URL param helpers shared by the scanners list and the observations table. */
+import type { Sorting } from 'lib/lemon-ui/LemonTable'
+
+/** LemonTable's `Sorting` with the column key narrowed to the caller's sortable-key union. */
+export interface UrlSorting<K extends string = string> extends Sorting {
+ columnKey: K
+}
+
+/** CSV join for URL params; an empty selection omits the param entirely. */
+export const csvParam = (values: string[]): string | undefined => (values.length > 0 ? values.join(',') : undefined)
+
+/** CSV split tolerant of the router coercing a single numeric param to a number; optional allowlist. */
+export function parseCsvParam<T extends string>(value: unknown, validValues?: readonly T[]): T[] {
+ const raw = typeof value === 'string' ? value : typeof value === 'number' ? String(value) : ''
+ if (raw.length === 0) {
+ return []
+ }
+ const parsed = raw
+ .split(',')
+ .map((v) => v.trim())
+ .filter((v) => v.length > 0) as T[]
+ return validValues ? parsed.filter((v) => validValues.includes(v)) : parsed
+}
+
+/** `-`-prefixed sort token, or undefined when the sort matches `defaultSort` (keeps the URL clean). */
+export function serializeSortParam(sort: UrlSorting | null, defaultSort?: UrlSorting): string | undefined {
+ if (!sort || (defaultSort && sort.columnKey === defaultSort.columnKey && sort.order === defaultSort.order)) {
+ return undefined
+ }
+ return `${sort.order === -1 ? '-' : ''}${sort.columnKey}`
+}
+
+/** Parse a `-`-prefixed sort token; an optional `resolveKey` validates and narrows the column key. */
+export function parseSortParam<K extends string>(
+ value: unknown,
+ resolveKey?: (key: string) => K | null
+): UrlSorting<K> | null {
+ if (typeof value !== 'string' || value.length === 0) {
+ return null
+ }
+ const descending = value.startsWith('-')
+ const rawKey = descending ? value.slice(1) : value
+ if (!rawKey) {
+ return null
+ }
+ const columnKey = resolveKey ? resolveKey(rawKey) : (rawKey as K)
+ if (!columnKey) {
+ return null
+ }
+ return { columnKey, order: descending ? -1 : 1 }
+}