Skip to content

: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.

feat(autoresearch): prefill the create form from templates (#113121)

posthog[bot]403ab832c682
diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.md
index 6f157565e4fa..a9beac03c9d3 100644
--- a/products/autoresearch/frontend/AGENTS.md
+++ b/products/autoresearch/frontend/AGENTS.md
@@ -11,10 +11,11 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st
| `AutoresearchScene.tsx` | `/autoresearch` — the model list: a container-query grid of model cards and the "New model" entry point. |
| `AutoresearchModelCard.tsx` | One model card: the question as title, a state body (scored, training, draft), and counts. `ModelCardMenu.tsx` holds pause, resume, delete. |
| `pipelineQuestion.ts` | The model's question in plain words ("Who will do X in the next N days?"), shared by the list cards and the detail header. |
-| `AutoresearchNewScene.tsx` | `/autoresearch/new` — the create form. |
+| `AutoresearchNewScene.tsx` | `/autoresearch/new` — the create form. Its parts live in `newModel/`. |
| `AutoresearchPipelineScene.tsx` | `/autoresearch/:id` — the detail shell: title bar actions and the tab strip. Each tab lives in `pipeline/`. |
| `autoresearchLogic.ts` | List logic — loads pipelines, lifecycle actions, and setup-status detection for the empty-state gate. |
| `autoresearchNewLogic.ts` | Create form — a `kea-forms` form that validates the target, then calls the generated `autoresearchCreate`. |
+| `newModel/` | Create-form parts: template chips, the definition sentence (population, target, horizon), and the collapsed Advanced section. |
| `autoresearchPipelineLogic.ts` | Detail logic. |
| `PipelineStatusTag.tsx` | Status tag + tooltip shared by the list and detail scenes. |
| `ProbabilityHistogram.tsx` | Decile histogram of the latest scoring run's probabilities. |
@@ -46,7 +47,7 @@ Follow `frontend/src/AGENTS.md` — it applies to product frontends too.
- TypeScript with explicit return types; Tailwind utilities rather than inline styles.
- Reuse Lemon / quill components instead of hand-rolling tables, badges, or tags.
- Any button that fires a request must guard against double-submission — `loading` / `disabledReason` on `LemonButton`, reset on both success and error paths. The lifecycle actions here (train, score, archive, pause, resume) are all network calls, and several are expensive: firing `train` twice starts two sandbox agent runs and spends the budget twice.
-- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
+- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, and `autoresearch model advanced opened`. Buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
## Copy
@@ -55,6 +56,13 @@ Sentence case, not Title Case. Invoke `/writing-user-facing-copy` before adding
The settled user-facing word for the entity is **"model"** ("New model", "Delete model", "Model paused").
"Pipeline" is the internal name — it stays in code symbols and the backend, and must not appear in copy.
+## Templates in the create form
+
+A template chip calls resolve-template and writes the result into the same `newPipeline` form that a custom definition uses.
+The template's semantic population spec (`{"kind": ...}`) sits in `inference_population_kind` and `training_population_kind`, and the request merges it with the property filters.
+A change to the target or the horizon re-resolves the template. The name and the training lookback follow the template only until the user edits them.
+Templates take event targets only, so the target picker hides actions while a template is selected.
+
## When editing this flow
- Regenerate types after any serializer change and commit the result; CI checks for drift.
diff --git a/products/autoresearch/frontend/AutoresearchNewScene.tsx b/products/autoresearch/frontend/AutoresearchNewScene.tsx
index 3f7d864e92a4..c7d10f93b6de 100644
--- a/products/autoresearch/frontend/AutoresearchNewScene.tsx
+++ b/products/autoresearch/frontend/AutoresearchNewScene.tsx
@@ -6,9 +6,6 @@ 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'
@@ -18,6 +15,9 @@ import { SceneContent } from '~/layout/scenes/components/SceneContent'
import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { autoresearchNewLogic, hasTarget } from './autoresearchNewLogic'
+import { AdvancedSettings } from './newModel/AdvancedSettings'
+import { DefinitionSentence } from './newModel/DefinitionSentence'
+import { TemplateChips } from './newModel/TemplateChips'
export const scene: SceneExport = {
component: AutoresearchNewScene,
@@ -159,8 +159,8 @@ function ValidationPanel(): JSX.Element {
export function AutoresearchNewScene(): JSX.Element {
const isEnabled = useFeatureFlag('AUTORESEARCH')
- const { validation, isNewPipelineSubmitting, newPipeline, newPipelineErrors } = useValues(autoresearchNewLogic)
- const { submitNewPipeline, setNewPipelineValues } = useActions(autoresearchNewLogic)
+ const { validation, isNewPipelineSubmitting, resolvedTemplateLoading } = useValues(autoresearchNewLogic)
+ const { submitNewPipeline } = useActions(autoresearchNewLogic)
if (!isEnabled) {
return <NotFound object="Autoresearch" caption="This feature is not enabled for your project." />
@@ -177,7 +177,7 @@ export function AutoresearchNewScene(): JSX.Element {
</div>
<SceneTitleSection
name="New model"
- description="Define a target event or action, horizon, and population. Autoresearch will train models to predict it."
+ description="Pick a template or describe who to predict, what they will do, and when. Autoresearch trains models to predict it."
resourceType={{ type: 'experiment' }}
/>
@@ -187,114 +187,15 @@ export function AutoresearchNewScene(): JSX.Element {
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>
+ <TemplateChips />
- <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>
+ <DefinitionSentence />
- <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>
+ <LemonField name="name" label="Name">
+ <LemonInput placeholder="e.g. File sharing prediction" />
+ </LemonField>
- <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>
+ <AdvancedSettings />
<div className="flex justify-end gap-2 mt-2">
<LemonButton
@@ -307,7 +208,13 @@ export function AutoresearchNewScene(): JSX.Element {
<LemonButton
type="primary"
loading={isNewPipelineSubmitting}
- disabledReason={blockingError ? 'Resolve blocking warnings before creating' : undefined}
+ disabledReason={
+ blockingError
+ ? 'Resolve blocking warnings before creating'
+ : resolvedTemplateLoading
+ ? 'Wait for the template to load'
+ : undefined
+ }
onClick={() => submitNewPipeline()}
data-attr="autoresearch-new-create"
>
diff --git a/products/autoresearch/frontend/autoresearchNewLogic.test.ts b/products/autoresearch/frontend/autoresearchNewLogic.test.ts
index 4b58e2b9b420..39f8db212325 100644
--- a/products/autoresearch/frontend/autoresearchNewLogic.test.ts
+++ b/products/autoresearch/frontend/autoresearchNewLogic.test.ts
@@ -1,16 +1,72 @@
import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
+import { PersonPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'
import { autoresearchNewLogic } from './autoresearchNewLogic'
-import { autoresearchValidateCreate } from './generated/api'
+import {
+ autoresearchCreate,
+ autoresearchResolveTemplateCreate,
+ autoresearchTemplatesList,
+ autoresearchValidateCreate,
+} from './generated/api'
jest.mock('./generated/api', () => ({
autoresearchCreate: jest.fn(),
autoresearchValidateCreate: jest.fn(),
+ autoresearchTemplatesList: jest.fn(),
+ autoresearchResolveTemplateCreate: jest.fn(),
}))
+const mockCreate = autoresearchCreate as jest.Mock
const mockValidate = autoresearchValidateCreate as jest.Mock
+const mockTemplates = autoresearchTemplatesList as jest.Mock
+const mockResolve = autoresearchResolveTemplateCreate as jest.Mock
+
+const TEMPLATES = [
+ {
+ key: 'likely_active_soon',
+ display_name: 'Likely active soon',
+ description: '',
+ default_horizon_days: 7,
+ requires_user_event: false,
+ requires_activity_resolution: true,
+ notes: '',
+ },
+ {
+ key: 'feature_adoption',
+ display_name: 'Likely to adopt a feature',
+ description: '',
+ default_horizon_days: 14,
+ requires_user_event: true,
+ requires_activity_resolution: false,
+ notes: '',
+ },
+]
+
+function resolved(overrides: Record<string, unknown>): Record<string, unknown> {
+ return {
+ template_key: 'likely_active_soon',
+ display_name: 'Likely active soon',
+ description: '',
+ suggested_name: 'Likely active soon',
+ target_event: '$pageview',
+ resolved_activity_event: '$pageview',
+ activity_event_alternatives: [],
+ horizon_days: 7,
+ training_lookback_days: 180,
+ training_population: { kind: 'performed_event_within_days', days: 30, event: '$pageview' },
+ inference_population: { kind: 'performed_event_within_days', days: 30, event: '$pageview' },
+ output_person_property: 'predicted_p_active_soon_pageview_7d',
+ notes: '',
+ ...overrides,
+ }
+}
+
+async function settle(logic: ReturnType<typeof autoresearchNewLogic.build>): Promise<void> {
+ await jest.advanceTimersByTimeAsync(1000)
+ await expectLogic(logic).toFinishAllListeners()
+}
describe('autoresearchNewLogic', () => {
beforeEach(() => {
@@ -18,6 +74,7 @@ describe('autoresearchNewLogic', () => {
jest.useFakeTimers()
initKeaTests()
mockValidate.mockResolvedValue({ can_proceed: true, warnings: [] })
+ mockTemplates.mockResolvedValue(TEMPLATES)
})
afterEach(() => {
@@ -36,10 +93,152 @@ describe('autoresearchNewLogic', () => {
logic.mount()
logic.actions.setNewPipelineValues({ target_event: '$pageview', ...days })
- await jest.advanceTimersByTimeAsync(1000)
- await expectLogic(logic).toFinishAllListeners()
+ await settle(logic)
expect(mockValidate).toHaveBeenCalledTimes(expectedCalls)
expect(logic.values.validationFailed).toBe(false)
})
+
+ it('scores all identified users when only the separate training population has filters', async () => {
+ const trainingFilter: PersonPropertyFilter = {
+ key: 'plan',
+ value: 'pro',
+ operator: PropertyOperator.Exact,
+ type: PropertyFilterType.Person,
+ }
+ const logic = autoresearchNewLogic()
+ logic.mount()
+
+ logic.actions.setNewPipelineValues({
+ target_event: '$pageview',
+ separate_training_population: true,
+ training_population: [trainingFilter],
+ })
+ await settle(logic)
+
+ expect(mockValidate).toHaveBeenLastCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ training_population: { properties: [trainingFilter] },
+ inference_population: { properties: [] },
+ })
+ )
+ })
+
+ it('fills the form from an activity template, validates with its population, and lets an unedited name follow a template switch', async () => {
+ mockResolve.mockResolvedValue(resolved({}))
+ const logic = autoresearchNewLogic()
+ logic.mount()
+ await settle(logic)
+
+ logic.actions.selectTemplate('likely_active_soon')
+ await settle(logic)
+
+ expect(mockResolve).toHaveBeenCalledTimes(1)
+ expect(mockResolve.mock.calls[0][1]).toEqual({ template_key: 'likely_active_soon' })
+ expect(logic.values.newPipeline).toMatchObject({
+ name: 'Likely active soon',
+ target_event: '$pageview',
+ horizon_days: 7,
+ output_person_property: 'predicted_p_active_soon_pageview_7d',
+ })
+ const population = { kind: 'performed_event_within_days', days: 30, event: '$pageview' }
+ expect(mockValidate).toHaveBeenLastCalledWith(
+ expect.anything(),
+ expect.objectContaining({ training_population: population, inference_population: population })
+ )
+
+ mockResolve.mockResolvedValueOnce(
+ resolved({ template_key: 'feature_adoption', suggested_name: 'Likely to adopt a feature: $pageview' })
+ )
+ logic.actions.selectTemplate('feature_adoption')
+ await settle(logic)
+ expect(logic.values.newPipeline).toMatchObject({
+ template_key: 'feature_adoption',
+ name: 'Likely to adopt a feature: $pageview',
+ })
+ })
+
+ it('asks for a target before it resolves a template that needs one, and keeps an edited name and lookback', async () => {
+ mockResolve.mockImplementation((_team, { target_event, horizon_days }) =>
+ Promise.resolve(
+ resolved({
+ template_key: 'feature_adoption',
+ suggested_name: `Likely to adopt a feature: ${target_event}`,
+ target_event,
+ resolved_activity_event: null,
+ horizon_days: horizon_days ?? 14,
+ training_population: { kind: 'active_not_performed_target', active_within_days: 30 },
+ inference_population: { kind: 'active_not_performed_target', active_within_days: 30 },
+ })
+ )
+ )
+ const logic = autoresearchNewLogic()
+ logic.mount()
+ await settle(logic)
+
+ logic.actions.selectTemplate('feature_adoption')
+ await settle(logic)
+ expect(mockResolve).not.toHaveBeenCalled()
+ expect(logic.values.newPipeline).toMatchObject({ template_key: 'feature_adoption', horizon_days: 14 })
+
+ logic.actions.setNewPipelineValues({ training_lookback_days: 365 })
+ logic.actions.setNewPipelineValues({ target_event: 'file_shared' })
+ await settle(logic)
+ expect(mockResolve.mock.calls[0][1]).toEqual({
+ template_key: 'feature_adoption',
+ target_event: 'file_shared',
+ horizon_days: 14,
+ })
+ expect(logic.values.newPipeline).toMatchObject({
+ name: 'Likely to adopt a feature: file_shared',
+ training_lookback_days: 365,
+ inference_population_kind: { kind: 'active_not_performed_target', active_within_days: 30 },
+ })
+
+ logic.actions.setNewPipelineValues({ name: 'Sharing adoption' })
+ logic.actions.setNewPipelineValues({ horizon_days: 30 })
+ await settle(logic)
+ expect(mockResolve).toHaveBeenCalledTimes(2)
+ expect(logic.values.newPipeline).toMatchObject({ name: 'Sharing adoption', horizon_days: 30 })
+ })
+
+ it.each([
+ ['experiment budget', { iteration_budget: NaN }],
+ ['training lookback', { training_lookback_days: 5 }],
+ ])('opens Advanced when an invalid %s blocks submit', async (_, advancedValues) => {
+ const logic = autoresearchNewLogic()
+ logic.mount()
+ logic.actions.setNewPipelineValues({ name: 'Model', target_event: '$pageview', ...advancedValues })
+ await settle(logic)
+ expect(logic.values.advancedOpen).toBe(false)
+
+ logic.actions.submitNewPipeline()
+ await settle(logic)
+ expect(logic.values.advancedOpen).toBe(true)
+ expect(mockCreate).not.toHaveBeenCalled()
+ })
+
+ it('blocks creation until the template resolves for the current target', async () => {
+ mockResolve.mockResolvedValue(resolved({}))
+ mockCreate.mockResolvedValue({ id: 'pipeline-1', name: 'Likely active soon' })
+ const logic = autoresearchNewLogic()
+ logic.mount()
+ await settle(logic)
+ logic.actions.selectTemplate('likely_active_soon')
+ await settle(logic)
+
+ mockResolve.mockRejectedValueOnce({ detail: 'Resolve failed' })
+ logic.actions.setNewPipelineValues({ target_event: '$autocapture' })
+ await settle(logic)
+ logic.actions.submitNewPipeline()
+ await settle(logic)
+ expect(mockCreate).not.toHaveBeenCalled()
+
+ logic.actions.selectTemplate('likely_active_soon')
+ await settle(logic)
+ logic.actions.submitNewPipeline()
+ await settle(logic)
+ expect(mockCreate).toHaveBeenCalledTimes(1)
+ })
})
diff --git a/products/autoresearch/frontend/autoresearchNewLogic.ts b/products/autoresearch/frontend/autoresearchNewLogic.ts
index bbd9320c9044..90153969ee5d 100644
--- a/products/autoresearch/frontend/autoresearchNewLogic.ts
+++ b/products/autoresearch/frontend/autoresearchNewLogic.ts
@@ -1,4 +1,15 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers } from 'kea'
+import {
+ MakeLogicType,
+ actions,
+ afterMount,
+ connect,
+ isBreakpoint,
+ kea,
+ listeners,
+ path,
+ reducers,
+ selectors,
+} from 'kea'
import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { loaders } from 'kea-loaders'
@@ -15,15 +26,26 @@ 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 {
+ autoresearchCreate,
+ autoresearchResolveTemplateCreate,
+ autoresearchTemplatesList,
+ autoresearchValidateCreate,
+} from './generated/api'
import {
AutoresearchPipelineCreateApi,
+ ResolvedTemplateApi,
+ TemplateInfoApi,
+ TemplateKeyEnumApi,
ValidatePipelineRequestApi,
ValidatePipelineResponseApi,
} from './generated/api.schemas'
type TargetType = 'event' | 'action'
+/** A semantic population spec (`{"kind": ...}`) from resolve-template. */
+type PopulationKind = Record<string, unknown>
+
interface NewPipelineFormValues {
name: string
target_type: TargetType
@@ -33,8 +55,16 @@ interface NewPipelineFormValues {
target_action_id: number | null
horizon_days: number
training_lookback_days: number
- training_population: AnyPropertyFilter[]
+ // The people the model scores. Training uses them too unless separate_training_population is on.
inference_population: AnyPropertyFilter[]
+ separate_training_population: boolean
+ training_population: AnyPropertyFilter[]
+ iteration_budget: number
+ // Null for a custom definition.
+ template_key: TemplateKeyEnumApi | null
+ inference_population_kind: PopulationKind | null
+ training_population_kind: PopulationKind | null
+ output_person_property: string
}
const DEFAULTS: NewPipelineFormValues = {
@@ -44,11 +74,20 @@ const DEFAULTS: NewPipelineFormValues = {
target_action_id: null,
horizon_days: 30,
training_lookback_days: 180,
- training_population: [],
inference_population: [],
+ separate_training_population: false,
+ training_population: [],
+ iteration_budget: 50,
+ template_key: null,
+ inference_population_kind: null,
+ training_population_kind: null,
+ output_person_property: '',
}
+export const HORIZON_PRESETS = [7, 14, 30, 90]
+
const VALIDATE_DEBOUNCE_MS = 500
+const RESOLVE_DEBOUNCE_MS = 300
/** True once the chosen target (event name, or action id) is complete enough to validate/create. */
export function hasTarget(values: NewPipelineFormValues): boolean {
@@ -70,12 +109,86 @@ function targetRequestFields(values: NewPipelineFormValues): {
return { target_event: values.target_event.trim(), target_definition: {} }
}
+function populationBody(kind: PopulationKind | null, filters: AnyPropertyFilter[]): Record<string, unknown> {
+ return { ...kind, ...(filters.length > 0 ? { properties: filters } : {}) }
+}
+
+/** Build the population request fields shared by validate + create. */
+function populationRequestFields(values: NewPipelineFormValues): {
+ training_population: Record<string, unknown>
+ inference_population: Record<string, unknown>
+} {
+ const inference_population = populationBody(values.inference_population_kind, values.inference_population)
+ if (!values.separate_training_population) {
+ return { training_population: inference_population, inference_population }
+ }
+ return {
+ training_population: populationBody(values.training_population_kind, values.training_population),
+ // The API replaces an empty scoring population with the training one. An empty filter list
+ // is not empty to the API, so the model still scores all identified users.
+ inference_population: Object.keys(inference_population).length > 0 ? inference_population : { properties: [] },
+ }
+}
+
+function kindPhrase(kind: PopulationKind | null): string | null {
+ const days = kind?.days ?? kind?.active_within_days
+ switch (kind?.kind) {
+ case 'performed_event_within_days':
+ return `users who did ${kind.event ?? 'any event'} in the last ${days} days`
+ case 'person_first_seen_within_days':
+ return `users first seen in the last ${days} days`
+ case 'active_not_performed_target':
+ return `users active in the last ${days} days who haven't done it yet`
+ case 'ever_performed_event':
+ return `users who have done ${kind.event}`
+ case 'ever_performed_target':
+ return 'users who have done it before'
+ default:
+ return null
+ }
+}
+
+/** A short noun phrase for a population, e.g. "users first seen in the last 14 days matching 2 filters". */
+export function populationSummary(kind: PopulationKind | null, filters: AnyPropertyFilter[]): string {
+ const base = kindPhrase(kind) ?? 'all identified users'
+ if (filters.length === 0) {
+ return base
+ }
+ return `${base} matching ${filters.length} ${filters.length === 1 ? 'filter' : 'filters'}`
+}
+
+/** The form values a resolve-template response sets. Fields the user edited keep their value. */
+function valuesFromResolvedTemplate(
+ resolved: ResolvedTemplateApi,
+ lastSuggestedName: string | null,
+ lastSuggestedLookback: number,
+ current: NewPipelineFormValues
+): Partial<NewPipelineFormValues> {
+ const nameFollowsTemplate = !current.name.trim() || current.name === lastSuggestedName
+ const lookbackFollowsTemplate = current.training_lookback_days === lastSuggestedLookback
+ return {
+ template_key: resolved.template_key,
+ target_type: 'event',
+ target_event: resolved.target_event,
+ target_action_id: null,
+ horizon_days: resolved.horizon_days,
+ inference_population_kind: resolved.inference_population as PopulationKind,
+ training_population_kind: resolved.training_population as PopulationKind,
+ output_person_property: resolved.output_person_property,
+ ...(nameFollowsTemplate ? { name: resolved.suggested_name } : {}),
+ ...(lookbackFollowsTemplate ? { training_lookback_days: resolved.training_lookback_days } : {}),
+ }
+}
+
// 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
+ advancedOpen: boolean
isNewPipelineSubmitting: boolean
isNewPipelineValid: boolean
+ lastSuggestedLookback: number
+ lastSuggestedName: string | null
newPipeline: NewPipelineFormValues
newPipelineAllErrors: Record<string, any>
newPipelineChanged: boolean
@@ -85,7 +198,12 @@ export interface autoresearchNewLogicValues {
newPipelineTouched: boolean
newPipelineTouches: Record<string, boolean>
newPipelineValidationErrors: DeepPartialMap<NewPipelineFormValues, ValidationErrorType>
+ resolvedTemplate: ResolvedTemplateApi | null
+ resolvedTemplateLoading: boolean
+ resolvedTemplateStale: boolean
showNewPipelineErrors: boolean
+ templates: TemplateInfoApi[]
+ templatesLoading: boolean
validation: ValidatePipelineResponseApi | null
validationFailed: boolean
validationLoading: boolean
@@ -96,9 +214,39 @@ export interface autoresearchNewLogicActions {
clearValidation: () => {
value: boolean
}
+ loadTemplates: () => any
+ loadTemplatesFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTemplatesSuccess: (
+ templates: TemplateInfoApi[],
+ payload?: any
+ ) => {
+ templates: TemplateInfoApi[]
+ payload?: any
+ }
resetNewPipeline: (values?: NewPipelineFormValues) => {
values?: NewPipelineFormValues
}
+ resolveTemplate: (
+ templateKey: TemplateKeyEnumApi,
+ targetEvent?: string,
+ horizonDays?: number
+ ) => {
+ horizonDays: number | undefined
+ targetEvent: string | undefined
+ templateKey: TemplateKeyEnumApi
+ }
+ resolveTemplateFailure: () => {
+ value: true
+ }
+ resolveTemplateSuccess: (resolved: ResolvedTemplateApi) => {
+ resolved: ResolvedTemplateApi
+ }
runValidate: (_payload: any) => any
runValidateFailure: (
error: string,
@@ -114,6 +262,12 @@ export interface autoresearchNewLogicActions {
validation: ValidatePipelineResponseApi | null
payload?: any
}
+ selectTemplate: (templateKey: TemplateKeyEnumApi | null) => {
+ templateKey: TemplateKeyEnumApi | null
+ }
+ setAdvancedOpen: (open: boolean) => {
+ open: boolean
+ }
setNewPipelineManualErrors: (errors: Record<string, any>) => {
errors: Record<string, any>
}
@@ -148,7 +302,22 @@ export interface autoresearchNewLogicActions {
}
}
-export type autoresearchNewLogicType = MakeLogicType<autoresearchNewLogicValues, autoresearchNewLogicActions>
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface autoresearchNewLogicMeta {
+ __keaTypeGenInternalSelectorTypes: {
+ resolvedTemplateStale: (
+ newPipeline: NewPipelineFormValues,
+ resolvedTemplate: ResolvedTemplateApi | null
+ ) => boolean
+ }
+}
+
+export type autoresearchNewLogicType = MakeLogicType<
+ autoresearchNewLogicValues,
+ autoresearchNewLogicActions,
+ Record<string, any>,
+ autoresearchNewLogicMeta
+>
export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
path(['products', 'autoresearch', 'autoresearchNewLogic']),
@@ -157,16 +326,35 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
}),
actions({
clearValidation: () => ({ value: true }),
+ selectTemplate: (templateKey: TemplateKeyEnumApi | null) => ({ templateKey }),
+ resolveTemplate: (templateKey: TemplateKeyEnumApi, targetEvent?: string, horizonDays?: number) => ({
+ templateKey,
+ targetEvent,
+ horizonDays,
+ }),
+ resolveTemplateSuccess: (resolved: ResolvedTemplateApi) => ({ resolved }),
+ resolveTemplateFailure: true,
+ setAdvancedOpen: (open: boolean) => ({ open }),
}),
loaders(({ values }) => ({
+ templates: [
+ [] as TemplateInfoApi[],
+ {
+ loadTemplates: async () => {
+ if (!values.currentTeamId) {
+ return []
+ }
+ return await autoresearchTemplatesList(String(values.currentTeamId))
+ },
+ },
+ ],
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
+ const { horizon_days, training_lookback_days } = values.newPipeline
const { horizon_days: horizonError, training_lookback_days: lookbackError } =
values.newPipelineValidationErrors
// A cleared number input holds NaN, which serializes to null and the API rejects.
@@ -174,14 +362,14 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
return null
}
const { target_event, target_definition } = targetRequestFields(values.newPipeline)
+ const { training_population, inference_population } = populationRequestFields(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 } : {},
+ training_population,
+ inference_population,
}
const response = await autoresearchValidateCreate(String(teamId), body)
breakpoint()
@@ -206,6 +394,43 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
clearValidation: () => false,
},
],
+ resolvedTemplate: [
+ null as ResolvedTemplateApi | null,
+ {
+ selectTemplate: () => null,
+ resolveTemplateSuccess: (_, { resolved }) => resolved,
+ },
+ ],
+ // selectTemplate clears resolvedTemplate, so these keep the name and lookback the last template set.
+ // A field that still matches its value follows the next template.
+ lastSuggestedName: [
+ null as string | null,
+ {
+ resolveTemplateSuccess: (_, { resolved }) => resolved.suggested_name,
+ },
+ ],
+ // Starts at the form default, so a lookback the user edits before the first resolution stays.
+ lastSuggestedLookback: [
+ DEFAULTS.training_lookback_days,
+ {
+ resolveTemplateSuccess: (_, { resolved }) => resolved.training_lookback_days,
+ },
+ ],
+ resolvedTemplateLoading: [
+ false,
+ {
+ resolveTemplate: () => true,
+ resolveTemplateSuccess: () => false,
+ resolveTemplateFailure: () => false,
+ selectTemplate: () => false,
+ },
+ ],
+ advancedOpen: [
+ false,
+ {
+ setAdvancedOpen: (_, { open }) => open,
+ },
+ ],
}),
forms(({ actions, values }) => ({
newPipeline: {
@@ -236,12 +461,30 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
: !Number.isInteger(formValues.training_lookback_days)
? 'Training lookback must be a whole number of days'
: undefined,
+ iteration_budget:
+ !formValues.iteration_budget || formValues.iteration_budget < 1
+ ? 'Experiment budget must be at least 1'
+ : formValues.iteration_budget > 500
+ ? 'Experiment budget must be 500 or fewer'
+ : !Number.isInteger(formValues.iteration_budget)
+ ? 'Experiment budget must be a whole number'
+ : undefined,
}),
submit: async (payload: NewPipelineFormValues) => {
if (!values.currentTeamId) {
lemonToast.error('Select a project before creating a model')
return
}
+ if (values.resolvedTemplateStale) {
+ // The populations and output property come from the last resolution, so they may
+ // belong to an older target or horizon.
+ lemonToast.error(
+ values.resolvedTemplateLoading
+ ? 'The template is still loading. Wait for it to finish, then create.'
+ : "The template didn't load for this target and horizon. Select it again, or use Custom."
+ )
+ return
+ }
if (values.validationFailed) {
lemonToast.error('Validation failed to run. Retry it, then create.')
return
@@ -257,36 +500,36 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
return
}
const { target_event, target_definition } = targetRequestFields(payload)
+ const { training_population, inference_population } = populationRequestFields(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']),
+ training_population,
+ inference_population,
+ iteration_budget: payload.iteration_budget,
+ // Without a template the API derives the property from the target.
+ ...(payload.output_person_property
+ ? { output_person_property: payload.output_person_property }
+ : {}),
}
try {
const created = await autoresearchCreate(String(values.currentTeamId), body)
posthog.capture('autoresearch model created', {
pipeline_id: created.id,
target_type: payload.target_type,
+ template_key: payload.template_key,
})
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 })
+ posthog.capture('autoresearch model create failed', {
+ target_type: payload.target_type,
+ template_key: payload.template_key,
+ })
lemonToast.error(
error?.detail ??
error?.data?.detail ??
@@ -297,15 +540,115 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
},
},
})),
- listeners(({ values }) => ({
+ selectors({
+ resolvedTemplateStale: [
+ (s) => [s.newPipeline, s.resolvedTemplate],
+ (newPipeline: NewPipelineFormValues, resolved: ResolvedTemplateApi | null): boolean =>
+ !!newPipeline.template_key &&
+ (resolved?.template_key !== newPipeline.template_key ||
+ resolved.target_event !== newPipeline.target_event.trim() ||
+ resolved.horizon_days !== newPipeline.horizon_days),
+ ],
+ }),
+ listeners(({ actions, values }) => ({
runValidateSuccess: ({ validation }) => {
if (validation) {
posthog.capture('autoresearch model validated', {
can_proceed: validation.can_proceed,
target_type: values.newPipeline.target_type,
+ template_key: values.newPipeline.template_key,
})
}
},
+ selectTemplate: ({ templateKey }) => {
+ if (templateKey === null) {
+ posthog.capture('autoresearch model custom chosen')
+ actions.setNewPipelineValues({
+ template_key: null,
+ inference_population_kind: null,
+ training_population_kind: null,
+ output_person_property: '',
+ })
+ return
+ }
+ posthog.capture('autoresearch model template selected', { template_key: templateKey })
+ const template = values.templates.find((t) => t.key === templateKey)
+ if (template?.requires_user_event) {
+ // Templates take an event target. Keep the current event, and wait for one otherwise.
+ const targetEvent = values.newPipeline.target_type === 'event' ? values.newPipeline.target_event : ''
+ actions.setNewPipelineValues({
+ template_key: templateKey,
+ target_type: 'event',
+ target_event: targetEvent,
+ target_action_id: null,
+ horizon_days: template.default_horizon_days,
+ inference_population_kind: null,
+ training_population_kind: null,
+ output_person_property: '',
+ })
+ if (targetEvent.trim()) {
+ actions.resolveTemplate(templateKey, targetEvent.trim())
+ }
+ return
+ }
+ actions.setNewPipelineValues({ template_key: templateKey })
+ actions.resolveTemplate(templateKey)
+ },
+ resolveTemplate: async ({ templateKey, targetEvent, horizonDays }, breakpoint) => {
+ const teamId = values.currentTeamId
+ if (!teamId) {
+ actions.resolveTemplateFailure()
+ return
+ }
+ try {
+ await breakpoint(RESOLVE_DEBOUNCE_MS)
+ const resolved = await autoresearchResolveTemplateCreate(String(teamId), {
+ template_key: templateKey,
+ ...(targetEvent ? { target_event: targetEvent } : {}),
+ ...(horizonDays ? { horizon_days: horizonDays } : {}),
+ })
+ breakpoint()
+ if (values.newPipeline.template_key !== templateKey) {
+ actions.resolveTemplateFailure()
+ return
+ }
+ const { lastSuggestedName, lastSuggestedLookback } = values
+ actions.resolveTemplateSuccess(resolved)
+ // kea-forms types its setter with DeepPartial, which does not accept an opaque population spec.
+ actions.setNewPipelineValues(
+ valuesFromResolvedTemplate(
+ resolved,
+ lastSuggestedName,
+ lastSuggestedLookback,
+ values.newPipeline
+ ) as DeepPartial<NewPipelineFormValues>
+ )
+ } catch (error: any) {
+ if (isBreakpoint(error)) {
+ throw error
+ }
+ actions.resolveTemplateFailure()
+ lemonToast.error(
+ error?.detail ?? error?.data?.detail ?? "Couldn't load this template. Try again, or use Custom."
+ )
+ // A template that never resolved has no populations, so fall back to a custom definition.
+ if (!values.resolvedTemplate && values.newPipeline.template_key === templateKey) {
+ actions.setNewPipelineValues({ template_key: null })
+ }
+ }
+ },
+ setAdvancedOpen: ({ open }) => {
+ if (open) {
+ posthog.capture('autoresearch model advanced opened')
+ }
+ },
+ submitNewPipelineFailure: () => {
+ // A closed Advanced section unmounts its fields, so their errors stay hidden until it opens.
+ const { training_lookback_days, iteration_budget } = values.newPipelineValidationErrors
+ if (!values.advancedOpen && (training_lookback_days || iteration_budget)) {
+ actions.setAdvancedOpen(true)
+ }
+ },
})),
urlToAction(({ values }) => ({
[urls.autoresearchNew()]: () => {
@@ -315,7 +658,7 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
}
},
})),
- subscriptions(({ actions }) => ({
+ subscriptions(({ actions, values }) => ({
newPipeline: (next: NewPipelineFormValues, prev: NewPipelineFormValues | undefined) => {
if (!prev) {
return
@@ -332,12 +675,32 @@ export const autoresearchNewLogic = kea<autoresearchNewLogicType>([
next.target_action_id !== prev.target_action_id ||
next.horizon_days !== prev.horizon_days ||
next.training_lookback_days !== prev.training_lookback_days ||
+ next.separate_training_population !== prev.separate_training_population ||
+ next.inference_population_kind !== prev.inference_population_kind ||
+ next.training_population_kind !== prev.training_population_kind ||
trainingChanged ||
inferenceChanged
) {
actions.clearValidation()
actions.runValidate(null)
}
+ // A template derives its populations and output property from the target and horizon,
+ // so a change to either re-resolves it. A value the last resolution set needs no call.
+ const resolved = values.resolvedTemplate
+ const targetEvent = next.target_event.trim()
+ if (
+ next.template_key &&
+ next.template_key === prev.template_key &&
+ (next.target_event !== prev.target_event || next.horizon_days !== prev.horizon_days) &&
+ targetEvent &&
+ !values.newPipelineValidationErrors.horizon_days &&
+ (targetEvent !== resolved?.target_event || next.horizon_days !== resolved?.horizon_days)
+ ) {
+ actions.resolveTemplate(next.template_key, targetEvent, next.horizon_days)
+ }
},
})),
+ afterMount(({ actions }) => {
+ actions.loadTemplates()
+ }),
])
diff --git a/products/autoresearch/frontend/newModel/AdvancedSettings.tsx b/products/autoresearch/frontend/newModel/AdvancedSettings.tsx
new file mode 100644
index 000000000000..cbf54813b15f
--- /dev/null
+++ b/products/autoresearch/frontend/newModel/AdvancedSettings.tsx
@@ -0,0 +1,83 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonCollapse, LemonInput, LemonSwitch } from '@posthog/lemon-ui'
+
+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { autoresearchNewLogic, populationSummary } from '../autoresearchNewLogic'
+import { POPULATION_FILTER_GROUP_TYPES } from './DefinitionSentence'
+
+export function AdvancedSettings(): JSX.Element {
+ const { newPipeline, advancedOpen } = useValues(autoresearchNewLogic)
+ const { setNewPipelineValues, setAdvancedOpen } = useActions(autoresearchNewLogic)
+
+ return (
+ <LemonCollapse
+ activeKey={advancedOpen ? 'advanced' : null}
+ onChange={(key) => setAdvancedOpen(key === 'advanced')}
+ panels={[
+ {
+ key: 'advanced',
+ header: 'Advanced',
+ dataAttr: 'autoresearch-new-advanced',
+ content: (
+ <div className="flex flex-col gap-4">
+ <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."
+ >
+ <LemonInput type="number" min={7} max={730} />
+ </LemonField>
+ <div className="flex flex-col gap-2">
+ <LemonSwitch
+ label="Learn from different people than it scores"
+ checked={newPipeline.separate_training_population}
+ onChange={(checked) =>
+ setNewPipelineValues({
+ separate_training_population: checked,
+ ...(checked && newPipeline.training_population.length === 0
+ ? { training_population: newPipeline.inference_population }
+ : {}),
+ })
+ }
+ bordered
+ data-attr="autoresearch-new-separate-training"
+ />
+ {newPipeline.separate_training_population && (
+ <LemonField
+ name="training_population"
+ label="Training population"
+ help={`Learns from ${populationSummary(
+ newPipeline.training_population_kind,
+ newPipeline.training_population
+ )}.`}
+ info="Who the model learns from. Often people with enough history to be informative, for example people who signed up."
+ >
+ {({ value, onChange }) => (
+ <PropertyFilters
+ pageKey="autoresearch-new-training-population"
+ propertyFilters={value ?? []}
+ onChange={(filters) => onChange(filters)}
+ taxonomicGroupTypes={POPULATION_FILTER_GROUP_TYPES}
+ buttonText="Add filter"
+ />
+ )}
+ </LemonField>
+ )}
+ </div>
+ <LemonField
+ name="iteration_budget"
+ label="Experiment budget"
+ info="The most experiments the agent runs while it searches for a better model. Training stops earlier when the model stops improving."
+ >
+ <LemonInput type="number" min={1} max={500} />
+ </LemonField>
+ </div>
+ ),
+ },
+ ]}
+ />
+ )
+}
diff --git a/products/autoresearch/frontend/newModel/DefinitionSentence.tsx b/products/autoresearch/frontend/newModel/DefinitionSentence.tsx
new file mode 100644
index 000000000000..6ae6734a91b7
--- /dev/null
+++ b/products/autoresearch/frontend/newModel/DefinitionSentence.tsx
@@ -0,0 +1,145 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'
+
+import { PropertyFilters } from 'lib/components/PropertyFilters/PropertyFilters'
+import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
+import { TaxonomicPopover } from 'lib/components/TaxonomicPopover/TaxonomicPopover'
+import { LemonField } from 'lib/lemon-ui/LemonField'
+
+import { HORIZON_PRESETS, autoresearchNewLogic, populationSummary } from '../autoresearchNewLogic'
+
+export const POPULATION_FILTER_GROUP_TYPES = [
+ TaxonomicFilterGroupType.PersonProperties,
+ TaxonomicFilterGroupType.EventProperties,
+ TaxonomicFilterGroupType.Cohorts,
+]
+
+function formatDays(days: number): string {
+ return Number.isFinite(days) ? `${days} ${days === 1 ? 'day' : 'days'}` : 'N days'
+}
+
+export function DefinitionSentence(): JSX.Element {
+ const { newPipeline, newPipelineErrors, resolvedTemplate } = useValues(autoresearchNewLogic)
+ const { setNewPipelineValues } = useActions(autoresearchNewLogic)
+ const hasTemplate = newPipeline.template_key !== null
+ const targetError = newPipelineErrors.target_event ?? newPipelineErrors.target_action_id
+ const kindSummary = newPipeline.inference_population_kind
+ ? populationSummary(newPipeline.inference_population_kind, [])
+ : null
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-2 text-base">
+ <span>Predict who among</span>
+ <LemonDropdown
+ closeOnClickInside={false}
+ placement="bottom-start"
+ overlay={
+ <div className="flex flex-col gap-2 p-2 max-w-120">
+ {kindSummary && (
+ <p className="text-sm mb-0">
+ The template limits this to {kindSummary}. Add filters to narrow it further.
+ </p>
+ )}
+ <LemonField
+ name="inference_population"
+ label="People to score"
+ info="Who the model scores each day. Leave empty to score all identified users. The model also learns from these people unless you set a separate training population in Advanced."
+ >
+ {({ value, onChange }) => (
+ <PropertyFilters
+ pageKey="autoresearch-new-inference-population"
+ propertyFilters={value ?? []}
+ onChange={(filters) => onChange(filters)}
+ taxonomicGroupTypes={POPULATION_FILTER_GROUP_TYPES}
+ buttonText="Add filter"
+ />
+ )}
+ </LemonField>
+ </div>
+ }
+ >
+ <LemonButton type="secondary" size="small" data-attr="autoresearch-new-population">
+ {populationSummary(newPipeline.inference_population_kind, newPipeline.inference_population)}
+ </LemonButton>
+ </LemonDropdown>
+ <span>will</span>
+ <TaxonomicPopover
+ type="secondary"
+ size="small"
+ groupType={TaxonomicFilterGroupType.Events}
+ groupTypes={
+ hasTemplate
+ ? [TaxonomicFilterGroupType.Events]
+ : [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 || 'do something'}</>}
+ placeholder="do something"
+ allowClear
+ data-attr="autoresearch-new-target"
+ />
+ <span>within the next</span>
+ <LemonDropdown
+ closeOnClickInside={false}
+ placement="bottom-start"
+ overlay={
+ <div className="flex flex-col gap-2 p-2">
+ <div className="flex gap-1">
+ {HORIZON_PRESETS.map((days) => (
+ <LemonButton
+ key={days}
+ type="secondary"
+ size="small"
+ active={newPipeline.horizon_days === days}
+ onClick={() => setNewPipelineValues({ horizon_days: days })}
+ data-attr={`autoresearch-new-horizon-${days}`}
+ >
+ {formatDays(days)}
+ </LemonButton>
+ ))}
+ </div>
+ <LemonField name="horizon_days" label="Days">
+ <LemonInput type="number" min={1} max={365} size="small" />
+ </LemonField>
+ </div>
+ }
+ >
+ <LemonButton type="secondary" size="small" data-attr="autoresearch-new-horizon">
+ {formatDays(newPipeline.horizon_days)}
+ </LemonButton>
+ </LemonDropdown>
+ </div>
+ {(targetError || newPipelineErrors.horizon_days) && (
+ <div className="text-danger text-xs">{targetError ?? newPipelineErrors.horizon_days}</div>
+ )}
+ {hasTemplate && !newPipeline.target_event && (
+ <div className="text-muted text-xs">Pick the event this template predicts.</div>
+ )}
+ {resolvedTemplate?.resolved_activity_event && (
+ <div className="text-muted text-xs">
+ The template picked {resolvedTemplate.resolved_activity_event} as the activity event from your data.
+ Change the target to use another event.
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/newModel/TemplateChips.tsx b/products/autoresearch/frontend/newModel/TemplateChips.tsx
new file mode 100644
index 000000000000..28b0fd014e98
--- /dev/null
+++ b/products/autoresearch/frontend/newModel/TemplateChips.tsx
@@ -0,0 +1,50 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
+
+import { autoresearchNewLogic } from '../autoresearchNewLogic'
+
+export function TemplateChips(): JSX.Element | null {
+ const { templates, templatesLoading, newPipeline, resolvedTemplateLoading } = useValues(autoresearchNewLogic)
+ const { selectTemplate } = useActions(autoresearchNewLogic)
+
+ if (templatesLoading && templates.length === 0) {
+ return <LemonSkeleton className="h-8 w-full" />
+ }
+ // Without templates the form is the custom definition, so a lone Custom chip adds nothing.
+ if (templates.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <h3 className="text-base font-semibold mb-0">Start from a template</h3>
+ <div className="flex flex-wrap gap-2">
+ {templates.map((template) => (
+ <LemonButton
+ key={template.key}
+ type="secondary"
+ size="small"
+ active={newPipeline.template_key === template.key}
+ loading={resolvedTemplateLoading && newPipeline.template_key === template.key}
+ tooltip={template.description}
+ onClick={() => selectTemplate(template.key)}
+ data-attr={`autoresearch-new-template-${template.key}`}
+ >
+ {template.display_name}
+ </LemonButton>
+ ))}
+ <LemonButton
+ type="secondary"
+ size="small"
+ active={newPipeline.template_key === null}
+ tooltip="Define the target, population, and horizon yourself. Supports actions as targets."
+ onClick={() => selectTemplate(null)}
+ data-attr="autoresearch-new-template-custom"
+ >
+ Custom
+ </LemonButton>
+ </div>
+ </div>
+ )
+}