: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, connect, kea, listeners, path, reducers } from 'kea'
import { loaders } from 'kea-loaders'
import { urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { productSetupStatusLogic } from 'lib/components/ProductEmptyState/productSetupStatusLogic'
import type { ProductSetupStatus } from 'lib/components/ProductEmptyState/types'
import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { ProductKey } from '~/queries/schema/schema-general'
import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'
import {
autoresearchDestroy,
autoresearchList,
autoresearchPauseCreate,
autoresearchResumeCreate,
autoresearchTrainCreate,
} from './generated/api'
import { AutoresearchPipelineApi } from './generated/api.schemas'
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface autoresearchLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
setupStatus: ProductSetupStatus // productSetupStatusLogic
currentTeamId: number | null // teamLogic
mutatingPipelineIds: Record<string, boolean>
pipelines: AutoresearchPipelineApi[]
pipelinesLoadFailed: boolean
pipelinesLoading: boolean
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface autoresearchLogicActions {
setFeatureFlags: (
flags: string[],
variants: Record<string, boolean | string>
) => {
flags: string[]
variants: Record<string, boolean | string>
} // featureFlagLogic
setDetectedStatus: (status: ProductSetupStatus) => {
status: ProductSetupStatus
} // productSetupStatusLogic
loadCurrentTeamSuccess: (
currentTeam: null | import('~/types').TeamPublicType,
payload?: any
) => {
currentTeam: null | import('~/types').TeamPublicType
payload?: any
} // teamLogic
deletePipeline: (
id: string,
name: string
) => {
id: string
name: string
}
loadPipelines: (_: void) => void
loadPipelinesFailure: (
error: string,
errorObject?: any
) => {
error: string
errorObject?: any
}
loadPipelinesSuccess: (
pipelines: AutoresearchPipelineApi[],
payload?: void
) => {
pipelines: AutoresearchPipelineApi[]
payload?: void
}
modelCardOpened: (id: string) => {
id: string
}
pausePipeline: (pipeline: AutoresearchPipelineApi) => {
pipeline: AutoresearchPipelineApi
}
pipelineRemoved: (id: string) => {
id: string
}
pipelineUpdated: (pipeline: AutoresearchPipelineApi) => {
pipeline: AutoresearchPipelineApi
}
resumePipeline: (pipeline: AutoresearchPipelineApi) => {
pipeline: AutoresearchPipelineApi
}
setPipelineMutating: (
id: string,
mutating: boolean
) => {
id: string
mutating: boolean
}
startTraining: (pipeline: AutoresearchPipelineApi) => {
pipeline: AutoresearchPipelineApi
}
}
export type autoresearchLogicType = MakeLogicType<autoresearchLogicValues, autoresearchLogicActions>
export const autoresearchLogic = kea<autoresearchLogicType>([
path(['products', 'autoresearch', 'autoresearchLogic']),
connect(() => ({
values: [
teamLogic,
['currentTeamId'],
featureFlagLogic,
['featureFlags'],
productSetupStatusLogic({ productKey: ProductKey.AUTORESEARCH }),
['status as setupStatus'],
],
actions: [
productSetupStatusLogic({ productKey: ProductKey.AUTORESEARCH }),
['setDetectedStatus'],
teamLogic,
['loadCurrentTeamSuccess'],
featureFlagLogic,
['setFeatureFlags'],
],
})),
actions({
deletePipeline: (id: string, name: string) => ({ id, name }),
pausePipeline: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
resumePipeline: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
startTraining: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
modelCardOpened: (id: string) => ({ id }),
setPipelineMutating: (id: string, mutating: boolean) => ({ id, mutating }),
pipelineUpdated: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
pipelineRemoved: (id: string) => ({ id }),
}),
reducers({
// Apply a successful row action at once, so the row cannot offer a stale action while the list reloads.
// Give the default here too: this reducer registers before the loader, so without it the list starts as null.
pipelines: [
[] as AutoresearchPipelineApi[],
{
pipelineUpdated: (state, { pipeline }) => state.map((row) => (row.id === pipeline.id ? pipeline : row)),
pipelineRemoved: (state, { id }) => state.filter((row) => row.id !== id),
},
],
mutatingPipelineIds: [
{} as Record<string, boolean>,
{
setPipelineMutating: (
state: Record<string, boolean>,
{ id, mutating }: { id: string; mutating: boolean }
) => ({ ...state, [id]: mutating }),
},
],
pipelinesLoadFailed: [
false,
{
loadPipelines: () => false,
loadPipelinesSuccess: () => false,
loadPipelinesFailure: () => true,
},
],
}),
loaders(({ values }) => ({
pipelines: [
[] as AutoresearchPipelineApi[],
{
loadPipelines: async (_: void, breakpoint) => {
if (!values.currentTeamId) {
return []
}
// The endpoint pages at 100 rows. Follow every page so a team with more models sees all of them.
const pipelines: AutoresearchPipelineApi[] = []
for (;;) {
let response
try {
response = await autoresearchList(String(values.currentTeamId), {
offset: pipelines.length,
})
} catch (error) {
breakpoint()
throw error
}
// Stop here when a newer load started, so this one cannot publish an older list or error.
breakpoint()
pipelines.push(...response.results)
if (!response.next || response.results.length === 0) {
return pipelines
}
}
},
},
],
})),
listeners(({ actions, values }) => ({
// Detection for the scene empty-state gate: this is a creation-first product,
// so "set up" simply means at least one pipeline exists.
loadPipelinesSuccess: ({ pipelines }: { pipelines: AutoresearchPipelineApi[] }) => {
// With no team yet the loader returns an empty list that says nothing about setup.
if (!values.currentTeamId) {
return
}
actions.setDetectedStatus(pipelines.length > 0 ? 'has-data' : 'needs-setup')
},
loadCurrentTeamSuccess: () => {
if (values.featureFlags[FEATURE_FLAGS.AUTORESEARCH]) {
actions.loadPipelines()
}
},
setFeatureFlags: () => {
// Flags can arrive after mount, when afterMount already skipped the load. Start it once the flag is on.
if (
values.featureFlags[FEATURE_FLAGS.AUTORESEARCH] &&
values.setupStatus === 'loading' &&
!values.pipelinesLoading
) {
posthog.capture('autoresearch model list viewed')
actions.loadPipelines()
}
},
loadPipelinesFailure: () => {
posthog.capture('autoresearch model list load failed')
// Never strand the gate on its spinner: with no earlier answer, fail open
// to the real scene. Don't downgrade an existing answer on a reload blip.
if (values.setupStatus === 'loading') {
actions.setDetectedStatus('unknown')
}
},
deletePipeline: async ({ id, name }: { id: string; name: string }) => {
if (!values.currentTeamId || values.mutatingPipelineIds[id]) {
return
}
actions.setPipelineMutating(id, true)
try {
await autoresearchDestroy(String(values.currentTeamId), id)
actions.pipelineRemoved(id)
posthog.capture('autoresearch model deleted', { pipeline_id: id })
lemonToast.success(`Deleted "${name}"`)
actions.loadPipelines()
} catch (error: any) {
posthog.capture('autoresearch model action failed', { action: 'delete', pipeline_id: id })
lemonToast.error(error?.detail ?? error?.data?.detail ?? 'Failed to delete the model')
} finally {
actions.setPipelineMutating(id, false)
}
},
pausePipeline: async ({ pipeline }: { pipeline: AutoresearchPipelineApi }) => {
if (!values.currentTeamId || values.mutatingPipelineIds[pipeline.id]) {
return
}
actions.setPipelineMutating(pipeline.id, true)
try {
actions.pipelineUpdated(await autoresearchPauseCreate(String(values.currentTeamId), pipeline.id))
posthog.capture('autoresearch model paused', { pipeline_id: pipeline.id })
lemonToast.success(`Paused "${pipeline.name}". Scheduled scoring is on hold.`)
actions.loadPipelines()
} catch (error: any) {
posthog.capture('autoresearch model action failed', { action: 'pause', pipeline_id: pipeline.id })
lemonToast.error(error?.detail ?? error?.data?.detail ?? 'Failed to pause the model')
} finally {
actions.setPipelineMutating(pipeline.id, false)
}
},
resumePipeline: async ({ pipeline }: { pipeline: AutoresearchPipelineApi }) => {
if (!values.currentTeamId || values.mutatingPipelineIds[pipeline.id]) {
return
}
actions.setPipelineMutating(pipeline.id, true)
try {
actions.pipelineUpdated(await autoresearchResumeCreate(String(values.currentTeamId), pipeline.id))
posthog.capture('autoresearch model resumed', { pipeline_id: pipeline.id })
lemonToast.success(`Resumed "${pipeline.name}"`)
actions.loadPipelines()
} catch (error: any) {
posthog.capture('autoresearch model action failed', { action: 'resume', pipeline_id: pipeline.id })
lemonToast.error(error?.detail ?? error?.data?.detail ?? 'Failed to resume the model')
} finally {
actions.setPipelineMutating(pipeline.id, false)
}
},
startTraining: async ({ pipeline }: { pipeline: AutoresearchPipelineApi }) => {
if (!values.currentTeamId || values.mutatingPipelineIds[pipeline.id]) {
return
}
actions.setPipelineMutating(pipeline.id, true)
try {
await autoresearchTrainCreate(String(values.currentTeamId), pipeline.id)
posthog.capture('autoresearch model training started', { pipeline_id: pipeline.id, source: 'list' })
lemonToast.success(`Started training "${pipeline.name}"`)
actions.loadPipelines()
} catch (error: any) {
posthog.capture('autoresearch model action failed', {
action: 'train',
pipeline_id: pipeline.id,
status: error?.status,
})
lemonToast.error(error?.detail ?? error?.data?.detail ?? 'Failed to start training')
} finally {
actions.setPipelineMutating(pipeline.id, false)
}
},
modelCardOpened: ({ id }: { id: string }) => {
posthog.capture('autoresearch model card clicked', { pipeline_id: id })
},
})),
urlToAction(({ actions, values }) => ({
// Reload whenever the list route is entered — the scene logic can stay mounted across
// navigation (e.g. returning from the create flow), so afterMount alone leaves the list
// showing a stale snapshot that omits a just-created pipeline.
// Skip the initial call that urlToAction makes on mount, because afterMount already loads.
[urls.autoresearch()]: (_, __, ___, { initial }) => {
// With the flag off the scene shows NotFound, so there is no list view to record or load.
if (!values.featureFlags[FEATURE_FLAGS.AUTORESEARCH]) {
return
}
posthog.capture('autoresearch model list viewed')
if (!initial) {
actions.loadPipelines()
}
},
})),
afterMount(({ actions, values }) => {
if (values.featureFlags[FEATURE_FLAGS.AUTORESEARCH]) {
actions.loadPipelines()
}
}),
])