:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
import {
MakeLogicType,
actions,
afterMount,
beforeUnmount,
connect,
kea,
key,
listeners,
path,
props,
reducers,
selectors,
} from 'kea'
import { ApiError } from 'lib/api-error'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import type { ToastButton } from 'lib/lemon-ui/LemonToast/LemonToast'
import { metricCount } from 'lib/operationalMetrics'
import { playerSettingsLogic } from 'scenes/session-recordings/player/playerSettingsLogic'
import { playerSidebarLogic } from 'scenes/session-recordings/player/sidebar/playerSidebarLogic'
import { teamLogic } from 'scenes/teamLogic'
import { SessionRecordingSidebarTab } from '~/types'
import { visionObservationsList, visionScannersInlineScanCreate, visionScannersObserveCreate } from '../generated/api'
import { BuiltInScanKeyEnumApi } from '../generated/api.schemas'
import type { ReplayScannerApi, ReplayObservationApi } from '../generated/api.schemas'
import { isSummarizerScanner } from '../replay_scanners/types'
import { isSummaryObservation } from '../utils/observation'
import { RecordingTimeline, recordingTimeline } from '../utils/recordingTimeline'
import { OBSERVE_POLL_GRACE_MS, scheduleObservationPoll, shouldPollObservations } from './observationPolling'
import { requestObservationRetry } from './observationRetry'
import { BUILT_IN_SUMMARIZER, resolveSummarizer, summarizeOutcomeMessage } from './summarizeRecording'
import { visionDockPreferenceLogic } from './visionDockPreferenceLogic'
import { refreshVisionQuota } from './visionQuotaLogic'
import { visionScannersListLogic } from './visionScannersListLogic'
export interface ObservationsDockLogicProps {
sessionId: string
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationsDockLogicValues {
preferredSummarizerId: string | null // visionDockPreferenceLogic
scanners: ReplayScannerApi[] // visionScannersListLogic
scannersLoading: boolean // visionScannersListLogic
defaultSummarizer: ReplayScannerApi | null
filteredScanners: ReplayScannerApi[]
focusedObservationId: string | null
followMoments: boolean
hasLoadedObservations: boolean
hasObservationsInFlight: boolean
hoveredMarkMs: number | null
observations: ReplayObservationApi[]
observationsLoading: boolean
observing: boolean
pollUntil: number
retryingObservationIds: string[]
scannerPickerOpen: boolean
scannerSearch: string
summarizePending: boolean
summarizerScanners: ReplayScannerApi[]
summarizing: boolean
summaryInFlight: boolean
timeline: RecordingTimeline
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationsDockLogicActions {
setSidebarOpen: (open: boolean) => {
open: boolean
} // playerSettingsLogic
setWatchPanelTab: (tab: import('scenes/session-recordings/player/playerSettingsLogic').WatchPanelTab) => {
tab: import('scenes/session-recordings/player/playerSettingsLogic').WatchPanelTab
} // playerSettingsLogic
setAutoTab: (tab: SessionRecordingSidebarTab | null) => {
tab: SessionRecordingSidebarTab | null
} // playerSidebarLogic
setTab: (tab: SessionRecordingSidebarTab) => {
tab: SessionRecordingSidebarTab
} // playerSidebarLogic
setPreferredSummarizerId: (scannerId: string | null) => {
scannerId: string | null
} // visionDockPreferenceLogic
focusObservation: (observationId: string) => {
observationId: string
}
loadObservations: () => {
value: true
}
loadObservationsFailure: () => {
value: true
}
loadObservationsSuccess: (observations: ReplayObservationApi[]) => {
observations: ReplayObservationApi[]
}
observe: (
scannerId: string,
forSummary?: boolean
) => {
forSummary: boolean
scannerId: string
}
observeFailure: () => {
value: true
}
observeSuccess: () => {
value: true
}
retryObservation: (observationId: string) => {
observationId: string
}
retryObservationFailure: (observationId: string) => {
observationId: string
}
retryObservationSuccess: (observationId: string) => {
observationId: string
}
setFollowMoments: (follow: boolean) => {
follow: boolean
}
setHoveredMark: (timestampMs: number | null) => {
timestampMs: number | null
}
setScannerPickerOpen: (open: boolean) => {
open: boolean
}
setScannerSearch: (search: string) => {
search: string
}
showObservations: (inWatchLayout: boolean) => {
inWatchLayout: boolean
}
summarize: (inWatchLayout?: boolean) => {
inWatchLayout: boolean
}
summarizeFailure: () => {
value: true
}
summarizeSettled: () => {
value: true
}
summarizeSuccess: () => {
value: true
}
summarizeWith: (
scannerId: string | null,
inWatchLayout?: boolean
) => {
inWatchLayout: boolean
scannerId: string | null
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface observationsDockLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
hasObservationsInFlight: (observations: ReplayObservationApi[]) => boolean
summaryInFlight: (observations: ReplayObservationApi[]) => boolean
summarizePending: (summarizing: boolean, summaryInFlight: boolean) => boolean
timeline: (observations: ReplayObservationApi[]) => RecordingTimeline
summarizerScanners: (scanners: ReplayScannerApi[]) => ReplayScannerApi[]
defaultSummarizer: (
scanners: ReplayScannerApi[],
preferredSummarizerId: string | null
) => ReplayScannerApi | null
filteredScanners: (scanners: ReplayScannerApi[], scannerSearch: string) => ReplayScannerApi[]
}
}
export type observationsDockLogicType = MakeLogicType<
observationsDockLogicValues,
observationsDockLogicActions,
ObservationsDockLogicProps,
observationsDockLogicMeta
>
export const observationsDockLogic = kea<observationsDockLogicType>([
path(['products', 'replay_vision', 'frontend', 'logics', 'observationsDockLogic']),
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', 'scannersLoading'],
visionDockPreferenceLogic,
['preferredSummarizerId'],
],
actions: [
visionDockPreferenceLogic,
['setPreferredSummarizerId'],
playerSidebarLogic,
['setTab', 'setAutoTab'],
playerSettingsLogic,
['setSidebarOpen', 'setWatchPanelTab'],
],
})),
actions({
loadObservations: true,
loadObservationsSuccess: (observations: ReplayObservationApi[]) => ({ observations }),
loadObservationsFailure: true,
observe: (scannerId: string, forSummary: boolean = false) => ({ scannerId, forSummary }),
observeSuccess: true,
observeFailure: true,
retryObservation: (observationId: string) => ({ observationId }),
retryObservationSuccess: (observationId: string) => ({ observationId }),
retryObservationFailure: (observationId: string) => ({ observationId }),
showObservations: (inWatchLayout: boolean) => ({ inWatchLayout }),
focusObservation: (observationId: string) => ({ observationId }),
setFollowMoments: (follow: boolean) => ({ follow }),
setHoveredMark: (timestampMs: number | null) => ({ timestampMs }),
setScannerPickerOpen: (open: boolean) => ({ open }),
setScannerSearch: (search: string) => ({ search }),
summarize: (inWatchLayout: boolean = false) => ({ inWatchLayout }),
summarizeWith: (scannerId: string | null, inWatchLayout: boolean = false) => ({ scannerId, inWatchLayout }),
summarizeSuccess: true,
summarizeFailure: true,
summarizeSettled: true,
}),
reducers({
observations: [
[] as ReplayObservationApi[],
{
loadObservationsSuccess: (_, { observations }) => observations,
},
],
observationsLoading: [
false,
{
loadObservations: () => true,
loadObservationsSuccess: () => false,
loadObservationsFailure: () => false,
},
],
hasLoadedObservations: [
false,
{
loadObservationsSuccess: () => true,
loadObservationsFailure: () => true,
},
],
observing: [
false,
{
observe: () => true,
observeSuccess: () => false,
observeFailure: () => false,
},
],
// True from the click until the summary itself settles, not until the trigger request returns.
// The request only starts a scan that runs for a minute or more, so clearing this on its
// response put the idle label back under a user whose summary had not started arriving yet.
summarizing: [
false,
{
summarize: () => true,
summarizeWith: () => true,
// Nothing started, so there is nothing to wait for. `summarize` hands off to
// `observe` when the team has its own summarizer, and that listener reports its dead
// ends here too. It cannot be `observeFailure`: the sidebar picker runs on this same
// keyed logic, so its failures are not the summary's to settle.
summarizeFailure: () => false,
summarizeSettled: () => false,
},
],
scannerPickerOpen: [
false,
{
setScannerPickerOpen: (_, { open }) => open,
},
],
// Shared so hovering a mark on one surface highlights it on the other.
hoveredMarkMs: [
null as number | null,
{
setHoveredMark: (_, { timestampMs }) => timestampMs,
},
],
focusedObservationId: [
null as string | null,
{
focusObservation: (_, { observationId }) => observationId,
retryObservation: (_, { observationId }) => observationId,
},
],
followMoments: [
true,
{
setFollowMoments: (_, { follow }) => follow,
},
],
scannerSearch: [
'',
{
setScannerSearch: (_, { search }) => search,
// Reset the query each time the picker is opened or closed.
setScannerPickerOpen: () => '',
},
],
retryingObservationIds: [
[] as string[],
{
retryObservation: (state: string[], { observationId }: { observationId: string }) => [
...state,
observationId,
],
retryObservationSuccess: (state: string[], { observationId }: { observationId: string }) =>
state.filter((id) => id !== observationId),
retryObservationFailure: (state: string[], { observationId }: { observationId: string }) =>
state.filter((id) => id !== observationId),
},
],
pollUntil: [
0,
{
observeSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,
summarizeSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,
// The replacement row is inserted by the workflow moments after the retry 202 lands.
retryObservationSuccess: () => Date.now() + OBSERVE_POLL_GRACE_MS,
},
],
}),
selectors({
hasObservationsInFlight: [
(s) => [s.observations],
(observations: ReplayObservationApi[]): boolean =>
observations.some((o) => o.status === 'pending' || o.status === 'running'),
],
// Only a summary counts here: a monitor scanner the sidebar started is in flight too, and the
// summarize button must not claim that run as its own.
summaryInFlight: [
(s) => [s.observations],
(observations: ReplayObservationApi[]): boolean =>
observations.some((o) => isSummaryObservation(o) && (o.status === 'pending' || o.status === 'running')),
],
// What the button shows. `summarizing` covers the window before the row exists; the row covers
// a summary that was already running when this recording was opened.
summarizePending: [
(s) => [s.summarizing, s.summaryInFlight],
(summarizing: boolean, summaryInFlight: boolean): boolean => summarizing || summaryInFlight,
],
timeline: [
(s) => [s.observations],
(observations: ReplayObservationApi[]): RecordingTimeline => recordingTimeline(observations),
],
summarizerScanners: [
(s) => [s.scanners],
(scanners: ReplayScannerApi[]): ReplayScannerApi[] => scanners.filter(isSummarizerScanner),
],
// What the button runs, and names. Null means the built-in prompt.
defaultSummarizer: [
(s) => [s.scanners, s.preferredSummarizerId],
(scanners: ReplayScannerApi[], preferredSummarizerId: string | null): ReplayScannerApi | null =>
resolveSummarizer(scanners, preferredSummarizerId),
],
filteredScanners: [
(s) => [s.scanners, s.scannerSearch],
(scanners: ReplayScannerApi[], scannerSearch: string): ReplayScannerApi[] => {
const query = scannerSearch.trim().toLowerCase()
return query ? scanners.filter((scanner) => scanner.name.toLowerCase().includes(query)) : scanners
},
],
}),
listeners(({ actions, props, values, cache }) => {
const reschedulePoll = (): void => {
scheduleObservationPoll(
cache.disposables,
shouldPollObservations(values.hasObservationsInFlight, values.pollUntil),
actions.loadObservations
)
}
const landOnExistingObservations = (): void => {
if (values.observations.length > 0) {
actions.setWatchPanelTab('observations')
}
if (values.observations.some((o) => isSummaryObservation(o) && o.status === 'succeeded')) {
actions.setAutoTab(SessionRecordingSidebarTab.OBSERVATIONS)
}
}
// The button stays pending for as long as the run it started has something left to report: a
// summary row still running, or the grace period in which the row the scan will create has not
// landed yet. The cache flags hold it pending while the trigger request is still open, before
// either applies. The grace period is only the wait for a missing row, so that row landing ends
// it early; a summary that finishes fast must not keep the button pending beside its result.
const settleSummarizeIfDone = (): void => {
if (cache.summarizeInFlight || cache.observeInFlight === 'summary' || !values.summarizing) {
return
}
const startedRowLanded =
!!cache.summarizeScannerId && values.observations.some((o) => o.scanner_id === cache.summarizeScannerId)
const graceUntil = startedRowLanded ? 0 : values.pollUntil
if (!shouldPollObservations(values.summaryInFlight, graceUntil)) {
actions.summarizeSettled()
}
}
// Show the row that is coming, and re-read the quota the scan spent. Only call this when a scan
// actually started, or the poll window opens for work that will never land.
const afterScanStarted = (): void => {
actions.loadObservations()
refreshVisionQuota()
}
const reportTriggerFailure = (error: unknown, metric: string, message: string): void => {
metricCount(metric)
const detail = error instanceof ApiError && error.detail ? `: ${error.detail}` : ''
lemonToast.error(`${message}${detail}`)
}
// Run a summary, through one of the team's own scanners or the built-in prompt. A named scanner
// is just `observe`, which already owns its double-click guard and its already-run check.
const runSummary = async (scannerId: string | null, inWatchLayout: boolean): Promise<void> => {
actions.showObservations(inWatchLayout)
if (scannerId) {
// Flagged as the summary's run, so only this one settles the button.
actions.observe(scannerId, true)
return
}
// A cache flag for the same reason `observe` uses one: the reducer has already flipped
// `summarizing` by the time this runs. Say so rather than dropping the click, which left
// the user in front of a control that looked live and answered with nothing.
if (cache.summarizeInFlight) {
lemonToast.info('A summary of this recording is already starting.')
return
}
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
actions.summarizeFailure()
return
}
cache.summarizeInFlight = true
try {
const response = await visionScannersInlineScanCreate(String(teamId), {
built_in: BuiltInScanKeyEnumApi.SummarizeRecording,
session_ids: [props.sessionId],
})
// One session in, so one result out. The inline scanner is shared per project, so a
// recording somebody already summarized comes back settled instead of started.
const outcome = response.results?.[0]?.scan_outcome
if (outcome === 'already_scanned') {
// A row settled server-side, but the inline scanner is shared and RBAC-scoped, so
// the row may not be readable here, and the reload can also fail. Confirm the row
// is in hand before naming it, and leave a way to re-read when it stays hidden.
actions.summarizeFailure()
// Both retries re-read the same rows, but they follow different failures: a row the
// reload could not see, and a reload that did not complete. Keep them apart.
const tryAgain = (dataAttr: string): ToastButton => ({
label: 'Try again',
action: () => actions.loadObservations(),
dataAttr,
})
try {
const reloaded = await visionObservationsList(String(teamId), {
session_id: props.sessionId,
})
const results = reloaded.results ?? []
actions.loadObservationsSuccess(results)
if (response.scan_id && results.some((o) => o.scanner_id === response.scan_id)) {
// The row is readable in the tab. A failed or ineligible one still shows its
// retry control there, so the user has a way to run the summary again.
lemonToast.info('This recording already has a result in the Observations tab.')
} else {
lemonToast.warning(
'This recording was already summarized, but the result is not available here.',
{ button: tryAgain('vision-summary-hidden-retry') }
)
}
} catch {
metricCount('replay_vision_frontend_observations_load_failures')
actions.loadObservationsFailure()
lemonToast.warning("Couldn't load this recording's summary.", {
button: tryAgain('vision-summary-reload-retry'),
})
}
return
}
const { level, message } = summarizeOutcomeMessage(outcome)
lemonToast[level](message)
if (outcome === 'started' || outcome === 'already_running') {
// A scan is in flight either way — ours, or one this project already had running
// against the shared inline scanner — so the poll window has a row to wait for.
cache.summarizeScannerId = response.scan_id
actions.summarizeSuccess()
afterScanStarted()
} else {
// Nothing started and nothing to read, so the poll window would watch for a row
// that never arrives.
actions.summarizeFailure()
}
} catch (error) {
reportTriggerFailure(
error,
'replay_vision_frontend_summarize_failures',
'Failed to summarize recording'
)
actions.summarizeFailure()
} finally {
cache.summarizeInFlight = false
}
}
return {
loadObservations: async (_, breakpoint) => {
// Poll, observe, retry, and the SSE hook all call this; without it a slow earlier response
// lands last and resurrects a settled card.
await breakpoint(1)
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 })
breakpoint()
actions.loadObservationsSuccess(response.results ?? [])
} catch {
metricCount('replay_vision_frontend_observations_load_failures')
actions.loadObservationsFailure()
}
},
// Poll while in flight and through the observe grace window; rescheduled on failure so one hiccup can't kill it.
loadObservationsSuccess: ({ observations }) => {
const started = observations.find((o) => o.scanner_id === cache.focusScannerId)
if (started) {
cache.focusScannerId = null
actions.focusObservation(started.id)
}
if (!cache.openingLoadDone) {
cache.openingLoadDone = true
landOnExistingObservations()
}
settleSummarizeIfDone()
reschedulePoll()
},
// Settles here too: with no summary row loaded, `pollUntil` is the only poll condition
// left, so a run of failed reloads would otherwise stop polling with the button still
// pending and nothing to clear it before the dock remounts.
loadObservationsFailure: () => {
settleSummarizeIfDone()
reschedulePoll()
},
showObservations: ({ inWatchLayout }) => {
if (inWatchLayout) {
actions.setWatchPanelTab('observations')
return
}
actions.setSidebarOpen(true)
actions.setTab(SessionRecordingSidebarTab.OBSERVATIONS)
},
observe: async ({ scannerId, forSummary }) => {
// The button waits on the summary, so every path here that starts no scan has to
// release it. A scan the sidebar started must not, even though it shares this logic.
const failSummarize = (): void => {
if (forSummary) {
actions.summarizeFailure()
}
}
// A cache flag, not `values.observing`: the reducer has already flipped that to true by the
// time this listener runs, so it would reject every call. Say so rather than dropping the
// click, which left the user in front of a control that looked live and answered with nothing.
// It names who is running, because a second summarize click is rejected by the run it
// is already waiting for, while a sidebar scan leaves it nothing to wait for.
if (cache.observeInFlight) {
lemonToast.info('A scan of this recording is already starting.')
if (cache.observeInFlight !== 'summary') {
failSummarize()
}
return
}
actions.setScannerPickerOpen(false)
const teamId = teamLogic.values.currentTeamId
if (!teamId) {
actions.observeFailure()
failSummarize()
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()
failSummarize()
return
}
cache.observeInFlight = forSummary ? 'summary' : 'scan'
try {
await visionScannersObserveCreate(String(teamId), scannerId, { session_id: props.sessionId })
lemonToast.success('Observation started')
if (forSummary) {
cache.summarizeScannerId = scannerId
}
cache.focusScannerId = scannerId
actions.observeSuccess()
afterScanStarted()
} catch (error) {
// Counted here rather than on observeFailure, which also fires for benign
// paths (scanner already run, no team) that would pollute the failure rate.
reportTriggerFailure(
error,
'replay_vision_frontend_observe_failures',
'Failed to start observation'
)
actions.observeFailure()
failSummarize()
} finally {
cache.observeInFlight = null
}
},
// Runs whatever the button currently resolves to, without disturbing the stored preference.
summarize: ({ inWatchLayout }) => runSummary(values.defaultSummarizer?.id ?? null, inWatchLayout),
// An explicit pick from the dropdown, which also becomes the preference for next time.
summarizeWith: ({ scannerId, inWatchLayout }) => {
actions.setPreferredSummarizerId(scannerId ?? BUILT_IN_SUMMARIZER)
return runSummary(scannerId, inWatchLayout)
},
retryObservation: async ({ observationId }) => {
if (!(await requestObservationRetry(observationId))) {
actions.retryObservationFailure(observationId)
return
}
actions.retryObservationSuccess(observationId)
actions.loadObservations()
},
}
}),
afterMount(({ actions, cache }) => {
cache.openingLoadDone = false
actions.loadObservations()
}),
beforeUnmount(({ actions }) => {
actions.setAutoTab(null)
}),
])