: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
fix(aio): guard AI event detection on the project id (#80327)
Carlos Marchal98466158b68e
diff --git a/products/ai_observability/frontend/aiObservabilityLogic.test.ts b/products/ai_observability/frontend/aiObservabilityLogic.test.tsindex 4a838c7dc77b..45e8d8f429a9 100644--- a/products/ai_observability/frontend/aiObservabilityLogic.test.ts+++ b/products/ai_observability/frontend/aiObservabilityLogic.test.ts@@ -6,6 +6,7 @@ import { expectLogic } from 'kea-test-utils'import api from 'lib/api'import { FEATURE_FLAGS } from 'lib/constants'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { projectLogic } from 'scenes/projectLogic'import { emptySceneParams } from 'scenes/scenes'import { Scene } from 'scenes/sceneTypes'import { urls } from 'scenes/urls'@@ -239,6 +240,35 @@ describe('aiObservabilitySharedLogic', () => {})})+describe('aiObservabilitySharedLogic AI event detection', () => {+ let logic: ReturnType<typeof aiObservabilitySharedLogic.build>++ beforeEach(() => {+ initKeaTests()+ sceneLogic.mount()+ router.actions.push(urls.aiObservabilityTraces())+ logic = aiObservabilitySharedLogic({})+ })++ afterEach(() => {+ logic.unmount()+ })++ it('waits for the project before probing for AI events', async () => {+ // Probing without a project id throws, and the setup poll would repeat that every 20s.+ projectLogic.actions.loadCurrentProjectSuccess(null)+ logic.mount()++ await expectLogic(logic).toNotHaveDispatchedActions(['loadAIEventDefinition'])+ })++ it('probes for AI events once the project is known', async () => {+ logic.mount()++ await expectLogic(logic).toDispatchActions(['loadAIEventDefinition'])+ })+})+describe('aiObservabilitySessionsViewLogic', () => {let sharedLogic: ReturnType<typeof aiObservabilitySharedLogic.build>let logic: ReturnType<typeof aiObservabilitySessionsViewLogic.build>diff --git a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts b/products/ai_observability/frontend/aiObservabilitySharedLogic.tsindex cffa0b0b3b11..7fdf4db5952e 100644--- a/products/ai_observability/frontend/aiObservabilitySharedLogic.ts+++ b/products/ai_observability/frontend/aiObservabilitySharedLogic.ts@@ -21,6 +21,7 @@ import { SetupTaskId, globalSetupLogic } from 'lib/components/ProductSetup'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { trackedActionToUrl } from 'lib/logic/scenes/trackedActionToUrl'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'@@ -140,6 +141,7 @@ export interface aiObservabilitySharedLogicValues {featureFlags: FeatureFlagsSet // featureFlagLogicfilterTestAccountsDefault: boolean // filterTestAccountsDefaultsLogicsetupStatus: ProductSetupStatus // productSetupStatusLogic+ currentProjectId: number | null // projectLogicsceneKey: string | null // sceneLogicuser: UserType | null // userLogicactiveTab: AIObservabilityTabId@@ -240,6 +242,8 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([['filterTestAccountsDefault'],productSetupStatusLogic({ productKey: ProductKey.AI_OBSERVABILITY }),['status as setupStatus'],+ projectLogic,+ ['currentProjectId'],],actions: [teamLogic,@@ -560,12 +564,21 @@ export const aiObservabilitySharedLogic = kea<aiObservabilitySharedLogicType>([}),afterMount(({ actions, values, cache }) => {- actions.loadAIEventDefinition()+ // 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()+ }+ }++ detectAIEventsIfProjectKnown()// 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.cache.disposables.add(() => {- const id = window.setInterval(() => actions.loadAIEventDefinition(), SETUP_POLL_INTERVAL_MS)+ const id = window.setInterval(detectAIEventsIfProjectKnown, SETUP_POLL_INTERVAL_MS)return () => clearInterval(id)}, 'setupPoll')globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(SetupTaskId.TrackCosts)diff --git a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.tsindex 1c4771f53d29..9dcbf629c992 100644--- a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts+++ b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts@@ -1,10 +1,12 @@-import { MakeLogicType, actions, afterMount, kea, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, kea, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'import { Sorting } from 'lib/lemon-ui/LemonTable'import { objectsEqual } from 'lib/utils/objects'import { pluralize } from 'lib/utils/strings'+import { projectLogic } from 'scenes/projectLogic'import { ApiConfig } from '~/lib/api'import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'@@ -86,6 +88,7 @@ export type AIObservabilityScoreDefinitionsLogicProps = Record<string, never>// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiObservabilityScoreDefinitionsLogicValues {+ currentProjectId: number | null // projectLogicarchivingDefinitionIds: Set<string>count: numberfilters: ScoreDefinitionFilters@@ -179,6 +182,9 @@ export type aiObservabilityScoreDefinitionsLogicType = MakeLogicType<export const aiObservabilityScoreDefinitionsLogic = kea<aiObservabilityScoreDefinitionsLogicType>([path(['products', 'ai_observability', 'frontend', 'scoreDefinitions', 'aiObservabilityScoreDefinitionsLogic']),props({} as AIObservabilityScoreDefinitionsLogicProps),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),actions({setFilters: (filters: Partial<ScoreDefinitionFilters>, merge: boolean = true, debounce: boolean = true) => ({@@ -250,6 +256,13 @@ export const aiObservabilityScoreDefinitionsLogic = kea<aiObservabilityScoreDefi{ results: [], count: 0, next: null, previous: null } as PaginatedScoreDefinitionListApi,{loadScoreDefinitions: async ({ debounce }, breakpoint) => {+ // The API reads the team id from bootstrap state, not the URL, so a load fired+ // before the project resolves throws. Bail while it's unknown; the currentProjectId+ // subscription re-fires this once bootstrap settles.+ if (!values.currentProjectId) {+ return values.scoreDefinitions+ }+if (debounce && values.scoreDefinitions.results.length > 0) {await breakpoint(300)}@@ -391,7 +404,13 @@ export const aiObservabilityScoreDefinitionsLogic = kea<aiObservabilityScoreDefi},})),- afterMount(({ actions }) => {- actions.loadScoreDefinitions()- }),+ // Fires on mount with the current value and again when the project resolves, so the+ // initial load waits for bootstrap instead of throwing "Team ID is not known.".+ subscriptions(({ actions }) => ({+ currentProjectId: (currentProjectId: number | null) => {+ if (currentProjectId) {+ actions.loadScoreDefinitions()+ }+ },+ })),])diff --git a/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts b/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.tsindex 3bc708dea245..cf1dec062921 100644--- a/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts+++ b/products/ai_observability/frontend/sentimentEvaluationAvailabilityLogic.ts@@ -1,7 +1,10 @@-import { MakeLogicType, afterMount, kea, path, reducers, selectors } from 'kea'+import { MakeLogicType, connect, kea, path, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'+import { subscriptions } from 'kea-subscriptions'-import { getCurrentTeamId } from '~/lib/utils/getAppContext'+import { projectLogic } from 'scenes/projectLogic'++import { getCurrentTeamIdOrNone } from '~/lib/utils/getAppContext'import { evaluationsList } from './generated/api'import type { EvaluationApi } from './generated/api.schemas'@@ -12,6 +15,7 @@ const SENTIMENT_EVALUATIONS_MAX = 1000// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface sentimentEvaluationAvailabilityLogicValues {+ currentProjectId: number | null // projectLogichasLoadedSentimentEvaluations: booleanhasSentimentEvaluations: booleansentimentEvaluations: EvaluationApi[]@@ -53,13 +57,23 @@ export type sentimentEvaluationAvailabilityLogicType = MakeLogicType<export const sentimentEvaluationAvailabilityLogic = kea<sentimentEvaluationAvailabilityLogicType>([path(['products', 'ai_observability', 'frontend', 'sentimentEvaluationAvailabilityLogic']),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),- loaders({+ loaders(({ values }) => ({sentimentEvaluations: [[] as EvaluationApi[],{loadSentimentEvaluations: async () => {- const teamId = String(getCurrentTeamId())+ // Bootstrap may not have resolved the project yet. Reading it as "none+ // available" hides the optional picker, where asking anyway would throw.+ const currentTeamId = getCurrentTeamIdOrNone()+ if (!currentTeamId) {+ return values.sentimentEvaluations+ }++ const teamId = String(currentTeamId)const evaluations: EvaluationApi[] = []// Page through so the picker lists every evaluation, not just the first page.@@ -82,7 +96,7 @@ export const sentimentEvaluationAvailabilityLogic = kea<sentimentEvaluationAvail},},],- }),+ })),reducers({hasLoadedSentimentEvaluations: [@@ -101,9 +115,13 @@ export const sentimentEvaluationAvailabilityLogic = kea<sentimentEvaluationAvail],}),- afterMount(({ actions, values }) => {- if (!values.hasLoadedSentimentEvaluations && !values.sentimentEvaluationsLoading) {- actions.loadSentimentEvaluations()- }- }),+ // Fires on mount with the current value and again when the project resolves, so the+ // availability check waits for bootstrap instead of settling on "no evaluations".+ subscriptions(({ actions }) => ({+ currentProjectId: (currentProjectId: number | null) => {+ if (currentProjectId) {+ actions.loadSentimentEvaluations()+ }+ },+ })),])diff --git a/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts b/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.tsindex 3dd5b7cb90bb..2e580dcdb73a 100644--- a/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts+++ b/products/ai_observability/frontend/traceReviews/aiObservabilityReviewsLogic.ts@@ -1,6 +1,7 @@-import { MakeLogicType, actions, afterMount, isBreakpoint, kea, listeners, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, connect, isBreakpoint, kea, listeners, path, props, reducers, selectors } from 'kea'import { loaders } from 'kea-loaders'import { router, urlToAction } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'import { lemonToast } from '@posthog/lemon-ui'@@ -8,6 +9,7 @@ import { Sorting } from 'lib/lemon-ui/LemonTable'import { copyToClipboard } from 'lib/utils/copyToClipboard'import { objectsEqual } from 'lib/utils/objects'import { pluralize } from 'lib/utils/strings'+import { projectLogic } from 'scenes/projectLogic'import { CountedPaginatedResponse } from '~/lib/api'import { ApiConfig } from '~/lib/api'@@ -72,6 +74,7 @@ export type AIObservabilityReviewsLogicProps = Record<string, never>// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiObservabilityReviewsLogicValues {+ currentProjectId: number | null // projectLogiccount: numberexportPath: stringfilters: TraceReviewFilters@@ -165,6 +168,9 @@ export type aiObservabilityReviewsLogicType = MakeLogicType<export const aiObservabilityReviewsLogic = kea<aiObservabilityReviewsLogicType>([path(['products', 'ai_observability', 'frontend', 'traceReviews', 'aiObservabilityReviewsLogic']),props({} as AIObservabilityReviewsLogicProps),+ connect(() => ({+ values: [projectLogic, ['currentProjectId']],+ })),actions({setFilters: (filters: Partial<TraceReviewFilters>, merge: boolean = true, debounce: boolean = true) => ({@@ -196,6 +202,13 @@ export const aiObservabilityReviewsLogic = kea<aiObservabilityReviewsLogicType>({ results: [], count: 0, offset: 0 } as CountedPaginatedResponse<TraceReview>,{loadReviews: async ({ debounce }, breakpoint) => {+ // The API reads the team id from bootstrap state, not the URL, so a load fired+ // before the project resolves throws. Bail while it's unknown; the currentProjectId+ // subscription re-fires this once bootstrap settles.+ if (!values.currentProjectId) {+ return values.reviews+ }+if (debounce && values.reviews.results.length > 0) {await breakpoint(300)}@@ -215,6 +228,10 @@ export const aiObservabilityReviewsLogic = kea<aiObservabilityReviewsLogicType>([] as ScoreDefinitionApi[],{loadScoreDefinitionOptions: async () => {+ if (!values.currentProjectId) {+ return values.scoreDefinitionOptions+ }+const response = await aiObservabilityScoreDefinitionsList(String(ApiConfig.getCurrentTeamId()), {archived: false,order_by: 'name',@@ -340,8 +357,14 @@ export const aiObservabilityReviewsLogic = kea<aiObservabilityReviewsLogicType>(},})),- afterMount(({ actions }) => {- actions.loadReviews()- actions.loadScoreDefinitionOptions()- }),+ // Fires on mount with the current value and again when the project resolves, so the+ // initial load waits for bootstrap instead of throwing "Team ID is not known.".+ subscriptions(({ actions }) => ({+ currentProjectId: (currentProjectId: number | null) => {+ if (currentProjectId) {+ actions.loadReviews()+ actions.loadScoreDefinitionOptions()+ }+ },+ })),])