: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 { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'
import { dateStringToDayJs, isValidRelativeOrAbsoluteDate } from 'lib/utils/dateFilters'
import { objectsEqual } from 'lib/utils/objects'
import { projectLogic } from 'scenes/projectLogic'
import { sceneLogic } from 'scenes/sceneLogic'
import { filterTestAccountsDefaultsLogic } from 'scenes/settings/environment/filterTestAccountDefaultsLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { userLogic } from 'scenes/userLogic'
import { isAnyPropertyFilters } from '~/queries/schema-guards'
import { ProductIntentContext, ProductKey } from '~/queries/schema/schema-general'
import { AnyPropertyFilter, Breadcrumb } from '~/types'
import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'
import type { ProductIntentProperties } from '../../../frontend/src/lib/utils/product-intents'
import type { UserType } from '../../../frontend/src/types'
import { AI_OBSERVABILITY_CLUSTER_URL_PATTERN } from './clusters/constants'
import { buildAiObservabilityStorageConfig } from './preferenceStorage'
import { scorerFiltersFromSearchParams } from './scoreDefinitions/scoreDefinitionNavigation'
import { parserRecipesLogic } from './settings/parserRecipesLogic'
import { hasRecentAIEvents } from './utils/aiEvents'
export const AI_OBSERVABILITY_DATA_COLLECTION_NODE_ID = 'ai-observability-data'
// Params this logic owns and rewrites when its state changes. Everything else is
// passed through untouched — other logics (e.g. reviews' `review_*`, queues'
// `queue_*`) own their params, so an allowlist here must never strip them.
// `trace_search`, not `search`: the trace view owns `search` for its in-trace
// search, and back navigation would leak it into the list's content filter.
const SHARED_PARAMS = new Set(['filters', 'date_from', 'date_to', 'filter_test_accounts', 'trace_search'])
// Params from the trace view that must not linger on list-tab URLs.
const STALE_PARAMS = new Set(['event', 'timestamp', 'msg'])
export type AIObservabilityTabId =
| 'dashboard'
| 'self-driving'
| 'generations'
| 'reviews'
| 'traces'
| 'users'
| 'errors'
| 'tools'
| 'sentiment'
| 'sessions'
| 'playground'
| 'datasets'
| 'evaluations'
| 'prompts'
| 'clusters'
export type SortDirection = 'ASC' | 'DESC'
export interface SortState {
column: string
direction: SortDirection
}
// Cadence of the setup-detection re-check while the team has no AI events yet.
const SETUP_POLL_INTERVAL_MS = 20000
// Ceiling for that cadence, because whatever stops the check answering does not clear in one tick.
const SETUP_POLL_MAX_INTERVAL_MS = 5 * 60 * 1000
const INITIAL_DASHBOARD_DATE_FROM = '-7d' as string | null
const INITIAL_EVENTS_DATE_FROM = '-1h' as string | null
const INITIAL_DATE_TO = null as string | null
export interface AIObservabilitySharedLogicProps {
logicKey?: string
personId?: string
group?: {
groupKey: string
groupTypeIndex: number
}
}
export interface ApplyUrlStatePayload {
propertyFilters: AnyPropertyFilter[]
dateFrom: string | null
dateTo: string | null
shouldFilterTestAccounts: boolean
searchQuery?: string
datesChanged: boolean
}
interface BuildApplyUrlStatePayloadInput {
dateFrom: string | null
dateTo: string | null
shouldFilterTestAccounts: boolean
propertyFilters: AnyPropertyFilter[]
searchQuery?: string
currentDateFilter: { dateFrom: string | null; dateTo: string | null }
currentPropertyFilters: AnyPropertyFilter[]
}
/**
* Build the payload for `applyUrlState` from a DataTable's query source. Preserves
* reference identity on unchanged `propertyFilters` so Kea selectors short-circuit,
* and computes `datesChanged` so the dashboard-tab date picker is not overwritten
* when only filters change.
*/
export function buildApplyUrlStatePayload({
dateFrom,
dateTo,
shouldFilterTestAccounts,
propertyFilters,
searchQuery,
currentDateFilter,
currentPropertyFilters,
}: BuildApplyUrlStatePayloadInput): ApplyUrlStatePayload {
return {
propertyFilters: objectsEqual(propertyFilters, currentPropertyFilters)
? currentPropertyFilters
: propertyFilters,
dateFrom,
dateTo,
shouldFilterTestAccounts,
searchQuery,
datesChanged: dateFrom !== currentDateFilter.dateFrom || dateTo !== currentDateFilter.dateTo,
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilitySharedLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
filterTestAccountsDefault: boolean // filterTestAccountsDefaultsLogic
setupStatus: ProductSetupStatus // productSetupStatusLogic
currentProjectId: number | null // projectLogic
sceneKey: string | null // sceneLogic
user: UserType | null // userLogic
activeTab: AIObservabilityTabId
breadcrumbs: Breadcrumb[]
dashboardDateFilter: {
dateFrom: string | null
dateTo: string | null
}
dashboardDateOverride: boolean
dashboardExternalDateFilters: {
date_from: string | null | undefined
date_to: string | null | undefined
}
dateFilter: {
dateFrom: string | null
dateTo: string | null
}
hasSentAiEvent: boolean | null | undefined
hasSentAiEventLoading: boolean
instrumentationVerdictApplies: (windowDays: number | null) => boolean
propertyFilters: AnyPropertyFilter[]
savedDashboardDateFilter: {
dateFrom: string | null
dateTo: string | null
}
searchQuery: string
shouldFilterSupportTraces: boolean
shouldFilterTestAccounts: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilitySharedLogicActions {
setLocalDefault: (value: boolean) => {
value: boolean
} // filterTestAccountsDefaultsLogic
setDetectedStatus: (status: ProductSetupStatus) => {
status: ProductSetupStatus
} // productSetupStatusLogic
addProductIntent: (properties: ProductIntentProperties) => ProductIntentProperties // teamLogic
applyDashboardUrlDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
applyUrlState: (state: ApplyUrlStatePayload) => ApplyUrlStatePayload
loadAIEventDefinition: () => any
loadAIEventDefinitionFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadAIEventDefinitionSuccess: (
hasSentAiEvent: boolean | null,
payload?: any
) => {
hasSentAiEvent: boolean | null
payload?: any
}
restoreSavedDashboardDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setDashboardDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setPropertyFilters: (propertyFilters: AnyPropertyFilter[]) => {
propertyFilters: AnyPropertyFilter[]
}
setSavedDashboardDates: (
dateFrom: string | null,
dateTo: string | null
) => {
dateFrom: string | null
dateTo: string | null
}
setSearchQuery: (searchQuery: string) => {
searchQuery: string
}
setShouldFilterSupportTraces: (shouldFilterSupportTraces: boolean) => {
shouldFilterSupportTraces: boolean
}
setShouldFilterTestAccounts: (shouldFilterTestAccounts: boolean) => {
shouldFilterTestAccounts: boolean
}
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface aiObservabilitySharedLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
dashboardExternalDateFilters: (
dashboardDateFilter: {
dateFrom: string | null
dateTo: string | null
},
dashboardDateOverride: boolean
) => {
date_from: string | null | undefined
date_to: string | null | undefined
}
activeTab: (sceneKey: string | null) => AIObservabilityTabId
instrumentationVerdictApplies: (
propertyFilters: AnyPropertyFilter[],
dateFilter: {
dateFrom: string | null
dateTo: string | null
},
shouldFilterTestAccounts: boolean
) => (windowDays: number | null) => boolean
}
}
export type aiObservabilitySharedLogicType = MakeLogicType<
aiObservabilitySharedLogicValues,
aiObservabilitySharedLogicActions,
AIObservabilitySharedLogicProps,
aiObservabilitySharedLogicMeta
>
export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([
path(['products', 'ai_observability', 'frontend', 'aiObservabilitySharedLogic']),
props({} as AIObservabilitySharedLogicProps),
key((props: AIObservabilitySharedLogicProps) => props.logicKey || props.personId || 'aiObservabilityScene'),
connect(() => ({
// Mount the parser-recipe logic so a team's custom recipes reach the trace-rendering
// normalizer on any AI observability page, not just the settings scene.
logic: [parserRecipesLogic],
values: [
sceneLogic,
['sceneKey'],
featureFlagLogic,
['featureFlags'],
userLogic,
['user'],
filterTestAccountsDefaultsLogic,
['filterTestAccountsDefault'],
productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }),
['status as setupStatus'],
projectLogic,
['currentProjectId'],
],
actions: [
teamLogic,
['addProductIntent'],
filterTestAccountsDefaultsLogic,
['setLocalDefault'],
productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }),
['setDetectedStatus'],
],
})),
actions({
setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setDashboardDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
applyDashboardUrlDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
restoreSavedDashboardDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setSavedDashboardDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),
setShouldFilterTestAccounts: (shouldFilterTestAccounts: boolean) => ({ shouldFilterTestAccounts }),
setShouldFilterSupportTraces: (shouldFilterSupportTraces: boolean) => ({ shouldFilterSupportTraces }),
setPropertyFilters: (propertyFilters: AnyPropertyFilter[]) => ({ propertyFilters }),
setSearchQuery: (searchQuery: string) => ({ searchQuery }),
// Batched action for URL-to-state sync. Dispatched once from urlToAction
// or scene-level setQuery handlers instead of multiple individual actions,
// producing a single actionToUrl URL change instead of 3-4 separate ones.
applyUrlState: (state: ApplyUrlStatePayload) => state,
}),
reducers(({ props }) => ({
dateFilter: [
{
dateFrom: INITIAL_EVENTS_DATE_FROM,
dateTo: INITIAL_DATE_TO,
},
{
...buildAiObservabilityStorageConfig('events.dateFilter'),
persist: !props.logicKey,
},
{
setDates: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),
applyUrlState: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),
},
],
dashboardDateFilter: [
{
dateFrom: INITIAL_DASHBOARD_DATE_FROM,
dateTo: INITIAL_DATE_TO,
},
{
// `setDates` (the events tabs' picker) is deliberately absent: it would move the
// dashboard picker without setting `dashboardDateOverride`, which gates the range
// the tiles actually run on.
setDashboardDates: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),
applyDashboardUrlDates: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),
restoreSavedDashboardDates: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),
},
],
dashboardDateOverride: [
false,
{
setDashboardDates: () => true,
applyDashboardUrlDates: () => true,
restoreSavedDashboardDates: () => false,
},
],
savedDashboardDateFilter: [
{
dateFrom: INITIAL_DASHBOARD_DATE_FROM,
dateTo: INITIAL_DATE_TO,
},
{
setSavedDashboardDates: (_, { dateFrom, dateTo }) => ({ dateFrom, dateTo }),
},
],
shouldFilterTestAccounts: [
false,
{
setShouldFilterTestAccounts: (_, { shouldFilterTestAccounts }) => shouldFilterTestAccounts,
applyUrlState: (_, { shouldFilterTestAccounts }) => shouldFilterTestAccounts,
},
],
shouldFilterSupportTraces: [
false, // For impersonated users, default to NOT filtering (show support traces)
{
setShouldFilterSupportTraces: (_, { shouldFilterSupportTraces }) => shouldFilterSupportTraces,
},
],
propertyFilters: [
[] as AnyPropertyFilter[],
{
setPropertyFilters: (_, { propertyFilters }) => propertyFilters,
applyUrlState: (_, { propertyFilters }) => propertyFilters,
},
],
searchQuery: [
'' as string,
{
setSearchQuery: (_, { searchQuery }) => searchQuery,
applyUrlState: (state, { searchQuery }) => searchQuery ?? state,
},
],
})),
loaders(() => ({
hasSentAiEvent: {
__default: undefined as boolean | null | undefined,
loadAIEventDefinition: async (): Promise<boolean | null> => {
return hasRecentAIEvents()
},
},
})),
listeners(({ actions, values, cache }) => ({
setSavedDashboardDates: ({ dateFrom, dateTo }) => {
if (!values.dashboardDateOverride) {
actions.restoreSavedDashboardDates(dateFrom, dateTo)
}
},
loadAIEventDefinitionSuccess: ({ hasSentAiEvent }) => {
if (hasSentAiEvent === null) {
// The check says nothing about this team, so publish `unknown` only where nothing
// has answered yet. That fails the gate open without downgrading a real answer.
if (values.setupStatus === 'loading') {
actions.setDetectedStatus('unknown')
}
cache.setSetupPollInterval(Math.min(cache.setupPollIntervalMs * 2, SETUP_POLL_MAX_INTERVAL_MS))
return
}
// Feed the app-wide setup-status layer (drives the scene empty-state gate).
actions.setDetectedStatus(hasSentAiEvent ? 'has-data' : 'needs-setup')
if (hasSentAiEvent) {
cache.disposables.dispose('setupPoll')
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.IngestFirstLlmEvent)
return
}
// The check works again, so a user waiting on their first event gets the fast flip back.
cache.setSetupPollInterval(SETUP_POLL_INTERVAL_MS)
},
loadAIEventDefinitionFailure: () => {
// A failing detection query must not strand the empty-state gate on its
// spinner. If nothing (preload included) has answered yet, publish
// `unknown` so the gate fails open to the real scene. A failure never
// downgrades an existing answer.
if (values.setupStatus === 'loading') {
actions.setDetectedStatus('unknown')
}
},
setShouldFilterTestAccounts: ({ shouldFilterTestAccounts }) => {
const divergesFromEffectiveDefault = shouldFilterTestAccounts !== values.filterTestAccountsDefault
if (divergesFromEffectiveDefault) {
actions.setLocalDefault(shouldFilterTestAccounts)
}
},
})),
selectors({
dashboardExternalDateFilters: [
(s) => [s.dashboardDateFilter, s.dashboardDateOverride],
(
dashboardDateFilter: {
dateFrom: string | null
dateTo: string | null
},
dashboardDateOverride: boolean
) => ({
date_from: dashboardDateOverride ? dashboardDateFilter.dateFrom : undefined,
date_to: dashboardDateOverride ? dashboardDateFilter.dateTo : undefined,
}),
],
activeTab: [
(s) => [s.sceneKey],
(sceneKey: string | null): AIObservabilityTabId => {
if (sceneKey === 'aiObservabilitySelfDriving') {
return 'self-driving'
} else if (sceneKey === 'aiObservabilityGenerations') {
return 'generations'
} else if (sceneKey === 'aiObservabilityReviews') {
return 'reviews'
} else if (sceneKey === 'aiObservabilityTraces') {
return 'traces'
} else if (sceneKey === 'aiObservabilityUsers') {
return 'users'
} else if (sceneKey === 'aiObservabilityErrors') {
return 'errors'
} else if (sceneKey === 'aiObservabilityTools') {
return 'tools'
} else if (sceneKey === 'aiObservabilitySentiment') {
return 'sentiment'
} else if (sceneKey === 'aiObservabilitySessions') {
return 'sessions'
} else if (sceneKey === 'aiObservabilityPlayground') {
return 'playground'
} else if (sceneKey === 'aiObservabilityDatasets') {
return 'datasets'
} else if (sceneKey === 'aiObservabilityEvaluations') {
return 'evaluations'
} else if (sceneKey === 'aiObservabilityPrompts') {
return 'prompts'
} else if (sceneKey === 'aiObservabilityClusters') {
return 'clusters'
}
return 'dashboard'
},
],
// Whether an instrumentation verdict graded over the last `windowDays` days can account
// for the rows the current view is showing.
//
// `searchQuery` is deliberately absent: it only reaches the traces query, so a term left
// over on the Traces tab would silence tabs whose contents it never touched.
instrumentationVerdictApplies: [
(s) => [s.propertyFilters, s.dateFilter, s.shouldFilterTestAccounts],
(
propertyFilters: AnyPropertyFilter[],
dateFilter: {
dateFrom: string | null
dateTo: string | null
},
shouldFilterTestAccounts: boolean
): ((windowDays: number | null) => boolean) => {
return (windowDays: number | null) => {
if (windowDays === null || propertyFilters.length > 0 || shouldFilterTestAccounts) {
return false
}
// The verdict only ever looked at the window, so it cannot vouch for a range
// starting before it. An unresolvable start ('all', or nothing at all) has no
// lower bound, which reaches earlier than any window.
//
// Both sides are anchored to UTC's start of day, where `dateStringToDayJs`
// anchors day-and-larger units, so a range of exactly the window's length,
// '-30d' against 30 days, stays inside its own window whatever the browser's
// timezone. Instants are compared directly because dayjs's timezone plugin
// re-reads a `.tz()`-derived value through the browser's wall clock inside
// `isBefore`, moving it by the local offset.
const rangeStart = dateStringToDayJs(dateFilter.dateFrom)
const windowStart = dayjs.utc().subtract(windowDays, 'day').startOf('day')
return rangeStart !== null && rangeStart.valueOf() >= windowStart.valueOf()
}
},
],
breadcrumbs: [
() => [],
(): Breadcrumb[] => {
return [
{
key: 'llm_analytics',
name: 'AI observability',
iconType: 'llm_analytics',
},
]
},
],
}),
urlToAction(({ actions, values, cache }) => {
function applySearchParams(searchParams: Record<string, unknown>, applyEventDateParams: boolean = true): void {
const { filters, date_from, date_to, filter_test_accounts, trace_search } = searchParams
const parsedFilters = isAnyPropertyFilters(filters) ? filters : []
const hasDateFromParam = applyEventDateParams && typeof date_from === 'string' && date_from.length > 0
const hasDateToParam = applyEventDateParams && typeof date_to === 'string' && date_to.length > 0
const hasDateFromOverride =
applyEventDateParams &&
typeof date_from === 'string' &&
date_from.length > 0 &&
isValidRelativeOrAbsoluteDate(date_from)
const hasDateToOverride =
applyEventDateParams &&
typeof date_to === 'string' &&
date_to.length > 0 &&
isValidRelativeOrAbsoluteDate(date_to)
const hasInvalidDateParam =
(hasDateFromParam && !hasDateFromOverride) || (hasDateToParam && !hasDateToOverride)
const hasDateOverride = hasDateFromOverride || hasDateToOverride
const newDateFrom = hasDateOverride
? hasDateFromOverride
? date_from
: INITIAL_EVENTS_DATE_FROM
: values.dateFilter.dateFrom
const newDateTo = hasDateOverride
? hasDateToOverride
? date_to
: INITIAL_DATE_TO
: values.dateFilter.dateTo
// A DataTable `person` cell mounts this logic on whatever scene renders it, so the team
// default is applied only once a route of this product matches. Applying it on mount would
// write this product's params over that scene's URL and drop its `#q=` state.
const filterTestAccountsValue =
filter_test_accounts === undefined && !cache.enteredAIObservabilityRoute
? values.filterTestAccountsDefault
: [true, 'true', 1, '1'].includes(filter_test_accounts as string | number | boolean)
markAIObservabilityRouteEntered()
const newSearchQuery = typeof trace_search === 'string' ? trace_search : ''
const filtersChanged = !objectsEqual(parsedFilters, values.propertyFilters)
const datesChanged = newDateFrom !== values.dateFilter.dateFrom || newDateTo !== values.dateFilter.dateTo
const testAccountsChanged = filterTestAccountsValue !== values.shouldFilterTestAccounts
const searchQueryChanged = newSearchQuery !== values.searchQuery
if (filtersChanged || datesChanged || testAccountsChanged || searchQueryChanged || hasInvalidDateParam) {
// Dispatch a single batched action so actionToUrl produces one URL
// change instead of up to 3 separate ones. The actionToUrl handler
// for applyUrlState rewrites the shared params and drops stale
// trace-view params, passing all other params through.
actions.applyUrlState({
propertyFilters: parsedFilters,
dateFrom: newDateFrom,
dateTo: newDateTo,
shouldFilterTestAccounts: filterTestAccountsValue,
searchQuery: newSearchQuery,
datesChanged,
})
} else {
// No state changed, but stale params from the trace view may
// still need stripping (e.g. event, timestamp, msg).
const hasStaleParams = Object.keys(searchParams).some((key) => STALE_PARAMS.has(key))
if (hasStaleParams) {
const cleanParams: Record<string, unknown> = {}
for (const [key, value] of Object.entries(searchParams)) {
if (!STALE_PARAMS.has(key)) {
cleanParams[key] = value
}
}
router.actions.replace(router.values.location.pathname, cleanParams, router.values.hashParams)
}
}
}
function markAIObservabilityRouteEntered(): void {
if (cache.enteredAIObservabilityRoute) {
return
}
cache.enteredAIObservabilityRoute = true
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.TrackCosts)
}
function clearDashboardTimer(): void {
clearTimeout(cache.dashboardDwellTimer)
cache.dashboardDwellTimer = undefined
}
function startDashboardTimer(): void {
clearDashboardTimer()
cache.dashboardDwellTimer = setTimeout(() => {
actions.addProductIntent({
product_type: ProductKey.AI_OBSERVABILITY,
intent_context: ProductIntentContext.LLM_ANALYTICS_VIEWED,
})
}, 15000)
}
function applyNonDashboard(searchParams: Record<string, unknown>): void {
clearDashboardTimer()
applySearchParams(searchParams)
}
function applyDashboard(searchParams: Record<string, unknown>): void {
applySearchParams(searchParams, false)
const hasDateOverride =
typeof searchParams.date_from === 'string' || typeof searchParams.date_to === 'string'
if (hasDateOverride) {
const dateFrom =
typeof searchParams.date_from === 'string' ? searchParams.date_from : INITIAL_EVENTS_DATE_FROM
const dateTo = typeof searchParams.date_to === 'string' ? searchParams.date_to : INITIAL_DATE_TO
if (
!values.dashboardDateOverride ||
dateFrom !== values.dashboardDateFilter.dateFrom ||
dateTo !== values.dashboardDateFilter.dateTo
) {
actions.applyDashboardUrlDates(dateFrom, dateTo)
}
} else if (
values.dashboardDateOverride ||
values.dashboardDateFilter.dateFrom !== values.savedDashboardDateFilter.dateFrom ||
values.dashboardDateFilter.dateTo !== values.savedDashboardDateFilter.dateTo
) {
actions.restoreSavedDashboardDates(
values.savedDashboardDateFilter.dateFrom,
values.savedDashboardDateFilter.dateTo
)
}
}
return {
[urls.aiObservabilityDashboard()]: (_, searchParams) => {
applyDashboard(searchParams)
startDashboardTimer()
},
[urls.aiObservabilitySelfDriving()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityGenerations()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityReviews()]: (_, searchParams) => {
if (searchParams.human_reviews_tab === 'scorers') {
router.actions.replace(urls.aiObservabilityScorers(), scorerFiltersFromSearchParams(searchParams))
return
}
applyNonDashboard(searchParams)
},
[urls.aiObservabilityTraces()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityUsers()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityErrors()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityTools()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilitySentiment()]: (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilitySessions()]: (_, searchParams) => applyNonDashboard(searchParams),
'/ai-observability/sessions/:id': (_, searchParams) => applyNonDashboard(searchParams),
[urls.aiObservabilityPlayground()]: (_, searchParams) => applyNonDashboard(searchParams),
// Cluster list and detail both honor the same `filters` / `filter_test_accounts`
// params so deep links from generations/traces tabs carry their filter set through.
[urls.aiObservabilityClusters()]: (_, searchParams) => applyNonDashboard(searchParams),
'/ai-observability/clusters/:runId': (_, searchParams) => applyNonDashboard(searchParams),
[AI_OBSERVABILITY_CLUSTER_URL_PATTERN]: (_, searchParams) => applyNonDashboard(searchParams),
}
}),
trackedActionToUrl(() => {
// Pass through params owned by other logics (e.g. review_*, queue_*) —
// only rewrite the shared params and drop stale trace-view params.
function passthroughSearchParams(): Record<string, unknown> {
const passthrough: Record<string, unknown> = {}
for (const [key, value] of Object.entries(router.values.searchParams)) {
if (!SHARED_PARAMS.has(key) && !STALE_PARAMS.has(key)) {
passthrough[key] = value
}
}
return passthrough
}
function sharedSearchParams(): Record<string, unknown> {
const { filters, date_from, date_to, filter_test_accounts, trace_search } = router.values.searchParams
return { ...passthroughSearchParams(), filters, date_from, date_to, filter_test_accounts, trace_search }
}
function dateSearchParams(dateFrom: string | null, dateTo: string | null): Record<string, unknown> {
if (router.values.location.pathname.endsWith(urls.aiObservabilityDashboard())) {
return {
date_from: router.values.searchParams.date_from,
date_to: router.values.searchParams.date_to,
}
}
return {
date_from: dateFrom === INITIAL_EVENTS_DATE_FROM ? undefined : dateFrom || undefined,
date_to: dateTo || undefined,
}
}
return {
applyUrlState: ({ propertyFilters, dateFrom, dateTo, shouldFilterTestAccounts, searchQuery }) => [
router.values.location.pathname,
{
...passthroughSearchParams(),
filters: propertyFilters.length > 0 ? propertyFilters : undefined,
...dateSearchParams(dateFrom, dateTo),
filter_test_accounts: shouldFilterTestAccounts ? 'true' : undefined,
trace_search:
(searchQuery ?? (router.values.searchParams.trace_search as string | undefined)) || undefined,
},
router.values.hashParams,
],
setPropertyFilters: ({ propertyFilters }) => [
router.values.location.pathname,
{
...sharedSearchParams(),
filters: propertyFilters.length > 0 ? propertyFilters : undefined,
},
router.values.hashParams,
],
setDates: ({ dateFrom, dateTo }) => [
router.values.location.pathname,
{
...sharedSearchParams(),
date_from: dateFrom === INITIAL_EVENTS_DATE_FROM ? undefined : dateFrom || undefined,
date_to: dateTo || undefined,
},
router.values.hashParams,
],
setDashboardDates: ({ dateFrom, dateTo }) => [
router.values.location.pathname,
{
...sharedSearchParams(),
date_from: dateFrom ?? 'all',
date_to: dateTo || undefined,
},
router.values.hashParams,
],
setShouldFilterTestAccounts: ({ shouldFilterTestAccounts }) => [
router.values.location.pathname,
{
...sharedSearchParams(),
filter_test_accounts: shouldFilterTestAccounts ? 'true' : undefined,
},
router.values.hashParams,
],
setSearchQuery: ({ searchQuery }) => [
router.values.location.pathname,
{
...sharedSearchParams(),
trace_search: searchQuery || undefined,
},
router.values.hashParams,
],
}
}),
afterMount(({ actions, values, cache }) => {
// The API layer takes the project id from bootstrap state, not from the URL, so a detection
// fired before the project resolves throws instead of answering. Skipping those ticks keeps
// the answer at "not known yet"; the poll below picks the check up once bootstrap settles.
const detectAIEventsIfProjectKnown = (): void => {
if (values.currentProjectId) {
actions.loadAIEventDefinition()
}
}
// While the empty state (or its post-skip reminder banner) is up, re-check on a
// timer so the page flips to the real product on its own once events land.
// Disposed as soon as data is detected; paused automatically on hidden tabs.
const registerSetupPoll = (): void => {
cache.disposables.add(() => {
const id = window.setInterval(detectAIEventsIfProjectKnown, cache.setupPollIntervalMs)
return () => clearInterval(id)
}, 'setupPoll')
}
// A call at the interval already in force leaves the running timer alone.
cache.setupPollIntervalMs = SETUP_POLL_INTERVAL_MS
cache.setSetupPollInterval = (intervalMs: number): void => {
if (cache.setupPollIntervalMs === intervalMs) {
return
}
cache.setupPollIntervalMs = intervalMs
registerSetupPoll()
}
detectAIEventsIfProjectKnown()
registerSetupPoll()
}),
beforeUnmount(({ cache }) => {
clearTimeout(cache.dashboardDwellTimer)
}),
])