: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
feat(autoresearch): add the model create form (#101573)
Andrew Maguire1b0da4bb3290
diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 9f71808cdfcb..51d6b94e5944 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -40,6 +40,7 @@ export const productScenes: Record<string, () => Promise<any>> = {PrecomputeDebug: () => import('../../products/analytics_platform/frontend/PrecomputeDebugScene'),Annotations: () => import('../../products/annotations/frontend/pages/Annotations'),Autoresearch: () => import('../../products/autoresearch/frontend/AutoresearchScene'),+ AutoresearchNew: () => import('../../products/autoresearch/frontend/AutoresearchNewScene'),BusinessKnowledge: () => import('../../products/business_knowledge/frontend/scenes/sources/BusinessKnowledgeScene'),BusinessKnowledgePlayground: () =>import('products/business_knowledge/frontend/scenes/playground/BusinessKnowledgePlaygroundScene'),diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex d22447bc8e6e..f99e950ae4df 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -100,6 +100,7 @@ export const productRoutes: Record<string, [string, string]> = {'/data-management/annotations': ['Annotations', 'annotations'],'/data-management/annotations/:id': ['Annotations', 'annotation'],'/autoresearch': ['Autoresearch', 'autoresearch'],+ '/autoresearch/new': ['AutoresearchNew', 'autoresearchNew'],'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],'/business-knowledge/settings': ['BusinessKnowledgeSettings', 'businessKnowledgeSettings'],'/business-knowledge/playground': ['BusinessKnowledgePlayground', 'businessKnowledgePlayground'],@@ -619,6 +620,7 @@ export const productConfiguration: Record<string, any> = {description: 'Automatically find the best model to predict user behavior and score your users on a schedule.',iconType: 'experiment',},+ AutoresearchNew: { name: 'New model', projectBased: true },BusinessKnowledge: {name: 'Business knowledge',projectBased: true,@@ -2151,7 +2153,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [iconType: 'experiment',tags: ['alpha'],sceneKey: 'Autoresearch',- sceneKeys: ['Autoresearch'],+ sceneKeys: ['Autoresearch', 'AutoresearchNew'],},{path: 'Broadcasts',diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 425b76d80f6e..64ada43e53c3 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -18,6 +18,7 @@ export enum Scene {Alerts = 'Alerts',Annotations = 'Annotations',Autoresearch = 'Autoresearch',+ AutoresearchNew = 'AutoresearchNew',Approval = 'Approval',AsyncMigrations = 'AsyncMigrations',BatchExport = 'BatchExport',diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.mdindex 10b602a108ed..65162a2f45e5 100644--- a/products/autoresearch/frontend/AGENTS.md+++ b/products/autoresearch/frontend/AGENTS.md@@ -1,6 +1,6 @@# Frontend-Three scenes behind the `autoresearch` feature flag: the pipeline list, the create form, and a single pipeline's detail view. This piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464) lands the list scene; the create form (`/autoresearch/new`) and the detail scene (`/autoresearch/:id`) arrive in the next pieces, so the list's "New model" button and row links point at routes that do not resolve yet.+Three scenes behind the `autoresearch` feature flag: the pipeline list, the create form, and a single pipeline's detail view. The list and the create form are here; the detail scene (`/autoresearch/:id`) arrives in the next piece of the split tracked in [#88464](https://github.com/PostHog/posthog/pull/88464), so the list's row links do not resolve yet.The product is mostly a backend, and the UI is deliberately thin — it reads status and results rather than doing any modeling work. What it mainly has to get right is honestly representing a long-running, partly-asynchronous process whose rows arrive at different times.diff --git a/products/autoresearch/frontend/AutoresearchNewScene.tsx b/products/autoresearch/frontend/AutoresearchNewScene.tsxnew file mode 100644index 000000000000..0d48f567de33--- /dev/null+++ b/products/autoresearch/frontend/AutoresearchNewScene.tsx@@ -0,0 +1,311 @@+import { useActions, useValues } from 'kea'+import { Form } from 'kea-forms'+import { router } from 'kea-router'++import { IconArrowLeft, IconInfo } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonInput, LemonSkeleton, Spinner, Tooltip } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import { autoresearchNewLogic, hasTarget } from './autoresearchNewLogic'++export const scene: SceneExport = {+ component: AutoresearchNewScene,+ logic: autoresearchNewLogic,+}++function formatPercent(value: number | null | undefined): string {+ if (value === null || value === undefined) {+ return '—'+ }+ return `${(value * 100).toFixed(2)}%`+}++function formatNumber(value: number | null | undefined): string {+ if (value === null || value === undefined) {+ return '—'+ }+ return value.toLocaleString()+}++function ValidationPanel(): JSX.Element {+ const { validation, validationLoading, validationFailed, newPipeline } = useValues(autoresearchNewLogic)+ const { runValidate } = useActions(autoresearchNewLogic)++ if (validationFailed && !validationLoading) {+ return (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: () => runValidate(null),+ 'data-attr': 'autoresearch-new-validate-retry',+ }}+ >+ Couldn't check this model definition. Retry, or change a field to check again.+ </LemonBanner>+ )+ }++ if (!validation && !validationLoading && !hasTarget(newPipeline)) {+ return (+ <div className="border rounded p-4 bg-bg-light text-muted text-sm">+ Pick a target event to see live training estimates.+ </div>+ )+ }++ return (+ <div className="border rounded p-4 flex flex-col gap-3">+ <div className="flex items-center justify-between">+ <h3 className="text-base font-semibold mb-0">Live estimate</h3>+ {validationLoading && <Spinner className="text-sm" />}+ </div>++ {validation ? (+ <>+ <div className="grid grid-cols-2 gap-2 text-sm">+ <div>+ <div className="text-muted">Training rows</div>+ <div className="font-mono">{formatNumber(validation.estimated_training_rows)}</div>+ </div>+ <div>+ <div className="text-muted">Prediction users</div>+ <div className="font-mono">{formatNumber(validation.inference_population_size)}</div>+ </div>+ <div>+ <div className="text-muted">Positives</div>+ <div className="font-mono">{formatNumber(validation.positive_count)}</div>+ </div>+ <div>+ <div className="text-muted">Negatives</div>+ <div className="font-mono">{formatNumber(validation.negative_count)}</div>+ </div>+ <div className="col-span-2">+ <div className="text-muted flex items-center gap-1">+ Base rate+ <Tooltip+ title={+ <span>+ For each user in the training population we pick a random reference point in+ their history and check whether the target event fired in the following+ "Prediction horizon" days. Base rate is the fraction labeled positive: the+ conversion rate the model is trained to predict.+ <br />+ <br />+ Computed from a sample of up to 5,000 users for speed; the sampled rate is+ an unbiased estimate of what the trainer sees unsampled.+ </span>+ }+ >+ <IconInfo className="text-sm cursor-help" />+ </Tooltip>+ </div>+ <div className="font-mono">{formatPercent(validation.base_rate)}</div>+ </div>+ </div>++ {validation.warnings.length > 0 && (+ <div className="flex flex-col gap-2 mt-2">+ {validation.warnings.map((w, i) => (+ <LemonBanner+ key={`${w.code}-${i}`}+ type={+ w.severity === 'error' ? 'error' : w.severity === 'warning' ? 'warning' : 'info'+ }+ >+ {w.message}+ </LemonBanner>+ ))}+ </div>+ )}++ {validation.error && (+ <LemonBanner type="error">Validation failed to run: {validation.error}</LemonBanner>+ )}+ </>+ ) : (+ <>+ <LemonSkeleton className="h-4 w-full" />+ <LemonSkeleton className="h-4 w-3/4" />+ <LemonSkeleton className="h-4 w-1/2" />+ </>+ )}+ </div>+ )+}++export function AutoresearchNewScene(): JSX.Element {+ const isEnabled = useFeatureFlag('AUTORESEARCH')+ const { validation, isNewPipelineSubmitting, newPipeline, newPipelineErrors } = useValues(autoresearchNewLogic)+ const { submitNewPipeline, setNewPipelineValues } = useActions(autoresearchNewLogic)++ if (!isEnabled) {+ return <NotFound object="Autoresearch" caption="This feature is not enabled for your project." />+ }++ const blockingError = validation?.warnings.some((w) => w.severity === 'error') ?? false++ return (+ <SceneContent>+ <div className="mb-2">+ <LemonButton type="tertiary" size="small" icon={<IconArrowLeft />} to={urls.autoresearch()}>+ Back to models+ </LemonButton>+ </div>+ <SceneTitleSection+ name="New model"+ description="Define a target event or action, horizon, and population. Autoresearch will train models to predict it."+ resourceType={{ type: 'experiment' }}+ />++ <div className="grid grid-cols-1 @min-[48rem]/main-content:grid-cols-[1fr_360px] gap-6 items-start">+ <Form+ logic={autoresearchNewLogic}+ formKey="newPipeline"+ className="flex flex-col gap-4 border rounded p-4"+ >+ <LemonField name="name" label="Name">+ <LemonInput placeholder="e.g. File sharing prediction" autoFocus />+ </LemonField>++ <LemonField.Pure+ label="Target"+ info="The event or action to predict. Pick an event for a single signal, or an action to predict a multi-step / property / autocapture matcher. Everything else flows from this pick."+ >+ <TaxonomicPopover+ groupType={TaxonomicFilterGroupType.Events}+ groupTypes={[TaxonomicFilterGroupType.Events, TaxonomicFilterGroupType.Actions]}+ value={+ newPipeline.target_type === 'action'+ ? newPipeline.target_action_id+ : newPipeline.target_event+ }+ onChange={(picked, groupType, item) => {+ if (groupType === TaxonomicFilterGroupType.Actions) {+ setNewPipelineValues({+ target_type: 'action',+ target_action_id: typeof picked === 'number' ? picked : Number(picked),+ target_event: item?.name ?? `action ${picked}`,+ })+ } else {+ setNewPipelineValues({+ target_type: 'event',+ target_event: String(picked ?? ''),+ target_action_id: null,+ })+ }+ }}+ renderValue={() => <>{newPipeline.target_event || 'Search events or actions…'}</>}+ placeholder="Search events or actions…"+ allowClear+ data-attr="autoresearch-new-target"+ />+ {(newPipelineErrors.target_event || newPipelineErrors.target_action_id) && (+ <div className="text-danger text-xs mt-1">+ {newPipelineErrors.target_event ?? newPipelineErrors.target_action_id}+ </div>+ )}+ </LemonField.Pure>++ <div className="flex flex-col gap-3 border-t pt-4">+ <div>+ <h3 className="text-base font-semibold mb-1">Training</h3>+ <p className="text-xs text-muted mb-0">What the model learns from.</p>+ </div>+ <LemonField+ name="training_lookback_days"+ label="Training lookback (days)"+ info="How far back to pull training examples from. Larger windows give more data but may include stale behavior. Default: 180 days."+ >+ <LemonInput type="number" min={7} max={730} />+ </LemonField>+ <LemonField+ name="training_population"+ label="Training population"+ info="Who the model learns from. Leave empty to include all identified users. Often this is users with enough history to be informative (e.g. signed up, has activity)."+ >+ {({ value, onChange }) => (+ <PropertyFilters+ pageKey="autoresearch-new-training-population"+ propertyFilters={value ?? []}+ onChange={(filters) => onChange(filters)}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.Cohorts,+ ]}+ buttonText="Add filter"+ />+ )}+ </LemonField>+ </div>++ <div className="flex flex-col gap-3 border-t pt-4">+ <div>+ <h3 className="text-base font-semibold mb-1">Prediction</h3>+ <p className="text-xs text-muted mb-0">What the model predicts, and who it scores.</p>+ </div>+ <LemonField+ name="horizon_days"+ label="Prediction horizon (days)"+ info="We will predict whether a user does the target event within this many days. Shorter horizons train and validate faster; longer ones capture slower-moving behaviors."+ >+ <LemonInput type="number" min={1} max={365} />+ </LemonField>+ <LemonField+ name="inference_population"+ label="Prediction population"+ info="Who the model scores on a schedule. Often a different group from training, e.g. train on signed-up users with history, predict on brand new users. Leave empty to use the training population."+ >+ {({ value, onChange }) => (+ <PropertyFilters+ pageKey="autoresearch-new-inference-population"+ propertyFilters={value ?? []}+ onChange={(filters) => onChange(filters)}+ taxonomicGroupTypes={[+ TaxonomicFilterGroupType.PersonProperties,+ TaxonomicFilterGroupType.EventProperties,+ TaxonomicFilterGroupType.Cohorts,+ ]}+ buttonText="Add filter"+ />+ )}+ </LemonField>+ </div>++ <div className="flex justify-end gap-2 mt-2">+ <LemonButton+ type="secondary"+ onClick={() => router.actions.push(urls.autoresearch())}+ data-attr="autoresearch-new-cancel"+ >+ Cancel+ </LemonButton>+ <LemonButton+ type="primary"+ loading={isNewPipelineSubmitting}+ disabledReason={blockingError ? 'Resolve blocking warnings before creating' : undefined}+ onClick={() => submitNewPipeline()}+ data-attr="autoresearch-new-create"+ >+ Create model+ </LemonButton>+ </div>+ </Form>++ <ValidationPanel />+ </div>+ </SceneContent>+ )+}diff --git a/products/autoresearch/frontend/autoresearchNewLogic.ts b/products/autoresearch/frontend/autoresearchNewLogic.tsnew file mode 100644index 000000000000..7a4bbade37ab--- /dev/null+++ b/products/autoresearch/frontend/autoresearchNewLogic.ts@@ -0,0 +1,336 @@+import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'+import { forms } from 'kea-forms'+import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'+import { loaders } from 'kea-loaders'+import { router, urlToAction } from 'kea-router'+import { subscriptions } from 'kea-subscriptions'+import posthog from 'posthog-js'++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 { AnyPropertyFilter } from '~/types'++import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'+import { autoresearchCreate, autoresearchValidateCreate } from './generated/api'+import {+ AutoresearchPipelineCreateApi,+ ValidatePipelineRequestApi,+ ValidatePipelineResponseApi,+} from './generated/api.schemas'++type TargetType = 'event' | 'action'++interface NewPipelineFormValues {+ name: string+ target_type: TargetType+ // For event targets this is the event name; for action targets it's the action's+ // display name (kept for the UI label and output-person-property derivation).+ target_event: string+ target_action_id: number | null+ horizon_days: number+ training_lookback_days: number+ training_population: AnyPropertyFilter[]+ inference_population: AnyPropertyFilter[]+}++const DEFAULTS: NewPipelineFormValues = {+ name: '',+ target_type: 'event',+ target_event: '',+ target_action_id: null,+ horizon_days: 30,+ training_lookback_days: 180,+ training_population: [],+ inference_population: [],+}++const VALIDATE_DEBOUNCE_MS = 500++/** True once the chosen target (event name, or action id) is complete enough to validate/create. */+export function hasTarget(values: NewPipelineFormValues): boolean {+ return values.target_type === 'action' ? values.target_action_id != null : !!values.target_event.trim()+}++/** Build the target request fields shared by validate + create. */+function targetRequestFields(values: NewPipelineFormValues): {+ target_event: string+ target_definition: Record<string, unknown>+} {+ if (values.target_type === 'action' && values.target_action_id != null) {+ // The API derives target_event from the action. The display name can exceed its 255-character limit.+ return {+ target_event: '',+ target_definition: { type: 'action', action_id: values.target_action_id },+ }+ }+ return { target_event: values.target_event.trim(), target_definition: {} }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface autoresearchNewLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ currentTeamId: number | null // teamLogic+ isNewPipelineSubmitting: boolean+ isNewPipelineValid: boolean+ newPipeline: NewPipelineFormValues+ newPipelineAllErrors: Record<string, any>+ newPipelineChanged: boolean+ newPipelineErrors: DeepPartialMap<NewPipelineFormValues, ValidationErrorType>+ newPipelineHasErrors: boolean+ newPipelineManualErrors: Record<string, any>+ newPipelineTouched: boolean+ newPipelineTouches: Record<string, boolean>+ newPipelineValidationErrors: DeepPartialMap<NewPipelineFormValues, ValidationErrorType>+ showNewPipelineErrors: boolean+ validation: ValidatePipelineResponseApi | null+ validationFailed: boolean+ validationLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface autoresearchNewLogicActions {+ clearValidation: () => {+ value: boolean+ }+ resetNewPipeline: (values?: NewPipelineFormValues) => {+ values?: NewPipelineFormValues+ }+ runValidate: (_payload: any) => any+ runValidateFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ runValidateSuccess: (+ validation: ValidatePipelineResponseApi | null,+ payload?: any+ ) => {+ validation: ValidatePipelineResponseApi | null+ payload?: any+ }+ setNewPipelineManualErrors: (errors: Record<string, any>) => {+ errors: Record<string, any>+ }+ setNewPipelineValue: (+ key: FieldName,+ value: any+ ) => {+ name: FieldName+ value: any+ }+ setNewPipelineValues: (values: DeepPartial<NewPipelineFormValues>) => {+ values: DeepPartial<NewPipelineFormValues>+ }+ submitNewPipeline: () => {+ value: boolean+ }+ submitNewPipelineFailure: (+ error: Error,+ errors: Record<string, any>+ ) => {+ error: Error+ errors: Record<string, any>+ }+ submitNewPipelineRequest: (newPipeline: NewPipelineFormValues) => {+ newPipeline: NewPipelineFormValues+ }+ submitNewPipelineSuccess: (newPipeline: NewPipelineFormValues) => {+ newPipeline: NewPipelineFormValues+ }+ touchNewPipelineField: (key: string) => {+ key: string+ }+}++export type autoresearchNewLogicType = MakeLogicType<autoresearchNewLogicValues, autoresearchNewLogicActions>++export const autoresearchNewLogic = kea<autoresearchNewLogicType>([+ path(['products', 'autoresearch', 'autoresearchNewLogic']),+ connect({+ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],+ }),+ actions({+ clearValidation: () => ({ value: true }),+ }),+ loaders(({ values }) => ({+ validation: [+ null as ValidatePipelineResponseApi | null,+ {+ runValidate: async (_payload, breakpoint) => {+ await breakpoint(VALIDATE_DEBOUNCE_MS)+ const teamId = values.currentTeamId+ const { horizon_days, training_lookback_days, training_population, inference_population } =+ values.newPipeline+ if (!teamId || !hasTarget(values.newPipeline)) {+ return null+ }+ const { target_event, target_definition } = targetRequestFields(values.newPipeline)+ const body: ValidatePipelineRequestApi = {+ target_event,+ target_definition: target_definition as ValidatePipelineRequestApi['target_definition'],+ horizon_days,+ training_lookback_days,+ training_population: training_population.length > 0 ? { properties: training_population } : {},+ inference_population:+ inference_population.length > 0 ? { properties: inference_population } : {},+ }+ const response = await autoresearchValidateCreate(String(teamId), body)+ breakpoint()+ return response+ },+ },+ ],+ })),+ reducers({+ validation: [+ null as ValidatePipelineResponseApi | null,+ {+ clearValidation: () => null,+ },+ ],+ validationFailed: [+ false,+ {+ runValidate: () => false,+ runValidateSuccess: () => false,+ runValidateFailure: () => true,+ clearValidation: () => false,+ },+ ],+ }),+ forms(({ actions, values }) => ({+ newPipeline: {+ defaults: DEFAULTS,+ errors: (formValues: NewPipelineFormValues) => ({+ name: !formValues.name.trim() ? 'Give the model a name' : undefined,+ target_event:+ formValues.target_type === 'event' && !formValues.target_event.trim()+ ? 'Pick a target event to predict'+ : undefined,+ target_action_id:+ formValues.target_type === 'action' && formValues.target_action_id == null+ ? 'Pick a target action to predict'+ : undefined,+ horizon_days:+ !formValues.horizon_days || formValues.horizon_days < 1+ ? 'Prediction horizon must be at least 1 day'+ : formValues.horizon_days > 365+ ? 'Prediction horizon must be 365 days or fewer'+ : undefined,+ training_lookback_days:+ !formValues.training_lookback_days || formValues.training_lookback_days < 7+ ? 'Training lookback must be at least 7 days'+ : formValues.training_lookback_days > 730+ ? 'Training lookback must be 730 days or fewer'+ : undefined,+ }),+ submit: async (payload: NewPipelineFormValues) => {+ if (!values.currentTeamId) {+ lemonToast.error('Select a project before creating a model')+ return+ }+ if (values.validationFailed) {+ lemonToast.error('Validation failed to run. Retry it, then create.')+ return+ }+ if (values.validationLoading || !values.validation) {+ // The form clears its validation on every change and re-runs it debounced, so a+ // null or in-flight result means these values have never been checked.+ lemonToast.error('Validation is still running. Wait for it to finish, then create.')+ return+ }+ if (!values.validation.can_proceed) {+ lemonToast.error('Validation found blocking errors. Fix them before creating.')+ return+ }+ const { target_event, target_definition } = targetRequestFields(payload)+ const body: AutoresearchPipelineCreateApi = {+ name: payload.name.trim(),+ target_event,+ target_definition: target_definition as AutoresearchPipelineCreateApi['target_definition'],+ horizon_days: payload.horizon_days,+ training_lookback_days: payload.training_lookback_days,+ training_population:+ payload.training_population.length > 0+ ? ({+ properties: payload.training_population,+ } as unknown as AutoresearchPipelineCreateApi['training_population'])+ : ({} as unknown as AutoresearchPipelineCreateApi['training_population']),+ inference_population:+ payload.inference_population.length > 0+ ? ({+ properties: payload.inference_population,+ } as unknown as AutoresearchPipelineCreateApi['inference_population'])+ : ({} as unknown as AutoresearchPipelineCreateApi['inference_population']),+ }+ try {+ const created = await autoresearchCreate(String(values.currentTeamId), body)+ posthog.capture('autoresearch model created', {+ pipeline_id: created.id,+ target_type: payload.target_type,+ })+ lemonToast.success(`Created "${created.name}"`)+ actions.resetNewPipeline()+ router.actions.push(urls.autoresearch())+ } catch (error: any) {+ posthog.capture('autoresearch model create failed', { target_type: payload.target_type })+ lemonToast.error(+ error?.detail ??+ error?.data?.detail ??+ 'Failed to create the model. Check the form and try again.'+ )+ throw error+ }+ },+ },+ })),+ listeners(({ values }) => ({+ runValidateSuccess: ({ validation }) => {+ if (validation) {+ posthog.capture('autoresearch model validated', {+ can_proceed: validation.can_proceed,+ target_type: values.newPipeline.target_type,+ })+ }+ },+ })),+ urlToAction(({ values }) => ({+ [urls.autoresearchNew()]: () => {+ // With the flag off the scene shows NotFound, so there is no create flow to record.+ if (values.featureFlags[FEATURE_FLAGS.AUTORESEARCH]) {+ posthog.capture('autoresearch model create started')+ }+ },+ })),+ subscriptions(({ actions }) => ({+ newPipeline: (next: NewPipelineFormValues, prev: NewPipelineFormValues | undefined) => {+ if (!prev) {+ return+ }+ const trainingChanged =+ next.training_population !== prev.training_population &&+ JSON.stringify(next.training_population) !== JSON.stringify(prev.training_population)+ const inferenceChanged =+ next.inference_population !== prev.inference_population &&+ JSON.stringify(next.inference_population) !== JSON.stringify(prev.inference_population)+ if (+ next.target_type !== prev.target_type ||+ next.target_event !== prev.target_event ||+ next.target_action_id !== prev.target_action_id ||+ next.horizon_days !== prev.horizon_days ||+ next.training_lookback_days !== prev.training_lookback_days ||+ trainingChanged ||+ inferenceChanged+ ) {+ actions.clearValidation()+ actions.runValidate(null)+ }+ },+ })),+])diff --git a/products/autoresearch/manifest.tsx b/products/autoresearch/manifest.tsxindex d0cf1fd478c4..d953ae18ec6d 100644--- a/products/autoresearch/manifest.tsx+++ b/products/autoresearch/manifest.tsx@@ -15,9 +15,15 @@ export const manifest: ProductManifest = {'Automatically find the best model to predict user behavior and score your users on a schedule.',iconType: 'experiment',},+ AutoresearchNew: {+ name: 'New model',+ import: () => import('./frontend/AutoresearchNewScene'),+ projectBased: true,+ },},routes: {'/autoresearch': ['Autoresearch', 'autoresearch'],+ '/autoresearch/new': ['AutoresearchNew', 'autoresearchNew'],},urls: {autoresearch: (): string => '/autoresearch',