: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): link predictions to a flag, a workflow and an insight (#113125)
posthog[bot]fa2307c34da2
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex da93b05423c6..a933e1b147db 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -50,6 +50,7 @@ import type { WorkflowsSceneTab } from '../../products/workflows/frontend/Workflimport {ActionType,AnnotationType,+ AnyPropertyFilter,DashboardType,FileSystemIconColor,InsightSceneSource,@@ -1573,12 +1574,14 @@ export const productUrls = {template,intent,format,+ properties,}: {type?: 'boolean' | 'multivariate' | 'remote_config'sourceId?: number | string | nulltemplate?: 'simple' | 'targeted' | 'multivariate' | 'targeted-multivariate'intent?: 'local-eval' | 'first-page-load'format?: 'rules_v2'+ properties?: AnyPropertyFilter[]}): string => {const params = new URLSearchParams()if (type) {@@ -1596,6 +1599,9 @@ export const productUrls = {if (format) {params.set('format', format)}+ if (properties?.length) {+ params.set('properties', JSON.stringify(properties))+ }return `/feature_flags/new?${params.toString()}`},game368hedgehogs: (): string => `/games/368hedgehogs`,diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.tsindex 41d2a4b14350..f5abd234b668 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts@@ -37,6 +37,7 @@ import {FeatureFlagType,FeatureFlagWithV1Config,OrganizationFeatureFlag,+ PersonPropertyFilter,PropertyFilterType,PropertyOperator,RecurrenceInterval,@@ -4512,6 +4513,30 @@ describe('a flag in config version 2', () => {expect(router.values.searchParams.sourceId).toBeUndefined()newLogic.unmount()})++ it('prefills one fully rolled out release condition from a properties link', async () => {+ defaultReleaseConditionsLogic.actions.loadDefaultReleaseConditionsSuccess({+ enabled: false,+ default_groups: [],+ })+ const properties: PersonPropertyFilter[] = [+ {+ key: 'p_signed_up',+ type: PropertyFilterType.Person,+ operator: PropertyOperator.GreaterThanOrEqual,+ value: 0.6,+ },+ ]+ router.actions.push(urls.featureFlagNew({ properties }))+ const newLogic = featureFlagLogic({ id: 'new' })+ newLogic.mount()+ await expectLogic(newLogic).toFinishAllListeners()++ expect(newLogic.values.featureFlag.filters.groups).toEqual([+ { properties, rollout_percentage: 100, variant: null },+ ])+ newLogic.unmount()+ })})describe('the editor a flag opens in', () => {diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.tsindex 2c283fe05199..548e034b4dba 100644--- a/frontend/src/scenes/feature-flags/featureFlagLogic.ts+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.ts@@ -3197,6 +3197,18 @@ export const featureFlagLogic = kea<featureFlagLogicType>([}}+ const prefilledProperties = router.values.searchParams.properties+ if (Array.isArray(prefilledProperties) && prefilledProperties.length > 0) {+ baseFlagConfig = {+ ...baseFlagConfig,+ filters: {+ ...baseFlagConfig.filters,+ groups: [{ properties: prefilledProperties, rollout_percentage: 100, variant: null }],+ aggregation_group_type_index: null,+ },+ }+ }+// Apply type-specific configurationif (flagType === 'multivariate') {baseFlagConfig = {@@ -5377,6 +5389,11 @@ export const featureFlagLogic = kea<featureFlagLogicType>([actions.loadFeatureFlag()return}+ // When there are properties, we load the feature flag (for prefilling a release condition)+ if (props.id === 'new' && searchParams.properties != null) {+ actions.loadFeatureFlag()+ return+ }// When pushing to `/new` and the feature flag already has default tags loaded, do not load the flag againif (props.id === 'new' && values.featureFlag.id == null && values.featureFlag.tags?.length > 0) {return@@ -5414,7 +5431,8 @@ export const featureFlagLogic = kea<featureFlagLogicType>([(router.values.searchParams.sourceId ||router.values.searchParams.type ||router.values.searchParams.template ||- router.values.searchParams.intent)+ router.values.searchParams.intent ||+ router.values.searchParams.properties)) {actions.loadFeatureFlag()returndiff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsindex 695990bd2b66..607d6a17549e 100644--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -46,6 +46,7 @@ import {import {PREDICTION_SEGMENTS,PREDICTION_SEGMENT_THRESHOLDS,+ type PredictionLinkDestination,type PredictionSegmentCounts,type PredictionSegmentKey,predictionSegmentCohortFilters,@@ -551,6 +552,9 @@ export interface autoresearchPipelineLogicActions {reportNotebookOpened: (runId: string) => {runId: string}+ reportPredictionLinkClicked: (destination: PredictionLinkDestination) => {+ destination: PredictionLinkDestination+ }resumePipeline: () => anyresumePipelineFailure: (error: string,@@ -715,6 +719,7 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([loadDetail: true,toggleRunArtifacts: (runId: string) => ({ runId }),reportNotebookOpened: (runId: string) => ({ runId }),+ reportPredictionLinkClicked: (destination: PredictionLinkDestination) => ({ destination }),setSuggestionDraft: (draft: string) => ({ draft }),setSuggestionPriority: (priority: CreateSuggestionPriorityEnumApi) => ({ priority }),setActiveScoreRun: (run: AutoresearchRunApi | null) => ({ run }),@@ -1373,6 +1378,9 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([reportNotebookOpened: ({ runId }) => {posthog.capture('autoresearch model report notebook opened', { pipeline_id: props.id, run_id: runId })},+ reportPredictionLinkClicked: ({ destination }) => {+ posthog.capture('autoresearch model prediction link clicked', { pipeline_id: props.id, destination })+ },setPredictionsPeopleView: ({ view }) => {posthog.capture('autoresearch model predictions view changed', { pipeline_id: props.id, view })},diff --git a/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx b/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsxnew file mode 100644index 000000000000..72fc779529eb--- /dev/null+++ b/products/autoresearch/frontend/pipeline/PredictionActionsPanel.tsx@@ -0,0 +1,59 @@+import { useActions, useValues } from 'kea'++import { IconDecisionTree, IconFlag, IconGraph } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import {+ PREDICTION_SEGMENTS,+ likelySegmentFeatureFlagUrl,+ likelySegmentWorkflowUrl,+ predictionBreakdownInsightUrl,+} from '../predictionSegments'++export function PredictionActionsPanel(): JSX.Element | null {+ const { pipeline } = useValues(autoresearchPipelineLogic)+ const { reportPredictionLinkClicked } = useActions(autoresearchPipelineLogic)++ const outputProperty = pipeline?.output_person_property+ if (!pipeline || !outputProperty) {+ return null+ }+ const likelyRange = PREDICTION_SEGMENTS[0].range.toLowerCase()++ return (+ <div className="border rounded p-4 bg-surface-primary">+ <h3 className="font-semibold mb-1">Act on these predictions</h3>+ <p className="text-sm text-secondary mb-3">Each link opens a prefilled draft. Review it, then save.</p>+ <div className="flex flex-col gap-1">+ <LemonButton+ icon={<IconFlag />}+ to={likelySegmentFeatureFlagUrl(outputProperty)}+ onClick={() => reportPredictionLinkClicked('feature_flag')}+ data-attr="autoresearch-predictions-create-flag"+ fullWidth+ >+ Create a feature flag for people who score {likelyRange}+ </LemonButton>+ <LemonButton+ icon={<IconDecisionTree />}+ to={likelySegmentWorkflowUrl(outputProperty)}+ onClick={() => reportPredictionLinkClicked('workflow')}+ data-attr="autoresearch-predictions-create-workflow"+ fullWidth+ >+ Start a workflow for people who score {likelyRange}+ </LemonButton>+ <LemonButton+ icon={<IconGraph />}+ to={predictionBreakdownInsightUrl(pipeline, outputProperty)}+ onClick={() => reportPredictionLinkClicked('insight')}+ data-attr="autoresearch-predictions-create-insight"+ fullWidth+ >+ Chart {pipeline.target_event} by predicted probability+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx b/products/autoresearch/frontend/pipeline/PredictionsTab.tsxindex a341fd338ee6..58fa67f270bc 100644--- a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx+++ b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx@@ -9,6 +9,7 @@ import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'import { DailyVolumeChart } from '../DailyVolumeChart'import { ProbabilityHistogram } from '../ProbabilityHistogram'import { EmptyTab } from './EmptyTab'+import { PredictionActionsPanel } from './PredictionActionsPanel'import { PredictionSegmentCards } from './PredictionSegmentCards'import { ProbabilityUsersTable } from './ProbabilityUsersTable'import { ScoreNowButton } from './ScoreNowButton'@@ -95,6 +96,8 @@ export function PredictionsTab(): JSX.Element {<PredictionSegmentCards />+ <PredictionActionsPanel />+<LemonCollapsemultipledefaultActiveKeys={['distribution', 'people']}diff --git a/products/autoresearch/frontend/predictionSegments.test.ts b/products/autoresearch/frontend/predictionSegments.test.tsindex b7031e69d95c..414ba690cabf 100644--- a/products/autoresearch/frontend/predictionSegments.test.ts+++ b/products/autoresearch/frontend/predictionSegments.test.ts@@ -1,4 +1,11 @@-import { PREDICTION_SEGMENTS, predictionSegmentCohortFilters, predictionSegmentFor } from './predictionSegments'+import { parseWorkflowTriggerPrefill } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'++import {+ PREDICTION_SEGMENTS,+ likelySegmentWorkflowUrl,+ predictionSegmentCohortFilters,+ predictionSegmentFor,+} from './predictionSegments'function cohortMatches(filters: ReturnType<typeof predictionSegmentCohortFilters>, probability: number): boolean {return filters.properties.values.every((group) =>@@ -22,4 +29,13 @@ describe('predictionSegments', () => {expect(matching.map(({ key }) => key)).toEqual([predictionSegmentFor(probability).key])})++ test('the workflow link opens a batch workflow whose audience is the likely segment', () => {+ const raw = new URLSearchParams(likelySegmentWorkflowUrl('p_signed_up').split('?')[1]).get('trigger')++ expect(parseWorkflowTriggerPrefill(raw ?? undefined)).toEqual({+ type: 'batch',+ filters: { properties: [{ type: 'person', key: 'p_signed_up', operator: 'gte', value: 0.6 }] },+ })+ })})diff --git a/products/autoresearch/frontend/predictionSegments.ts b/products/autoresearch/frontend/predictionSegments.tsindex 458595b910a6..9aa033b4eb80 100644--- a/products/autoresearch/frontend/predictionSegments.ts+++ b/products/autoresearch/frontend/predictionSegments.ts@@ -3,11 +3,14 @@ import { combineUrl } from 'kea-router'import { urls } from 'scenes/urls'import { defaultDataTableColumns } from '~/queries/nodes/DataTable/utils'-import { DataTableNode, NodeKind } from '~/queries/schema/schema-general'+import { DataTableNode, InsightVizNode, NodeKind } from '~/queries/schema/schema-general'import { escapePropertyAsHogQLIdentifier } from '~/queries/utils'-import { PersonPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'+import { BaseMathType, PersonPropertyFilter, PropertyFilterType, PropertyOperator } from '~/types'import type { CohortFiltersApi, PersonFilterApi } from 'products/cohorts/frontend/generated/api.schemas'+import { urlForNewWorkflowWithTrigger } from 'products/workflows/frontend/Workflows/workflowTriggerPrefill'++import type { AutoresearchPipelineApi } from './generated/api.schemas'/*** Probability cut points between the segments. Both sit on a histogram decile boundary,@@ -74,14 +77,18 @@ export function predictionSegmentCohortFilters(key: PredictionSegmentKey, properreturn { properties: { type: 'OR', values: [{ type: 'AND', values }] } }}-/** The persons list, filtered with the same conditions as the segment's cohort. */-export function predictionSegmentPeopleUrl(key: PredictionSegmentKey, property: string): string {- const properties: PersonPropertyFilter[] = segmentBounds(key).map(({ operator, value }) => ({+function segmentPropertyFilters(key: PredictionSegmentKey, property: string): PersonPropertyFilter[] {+ return segmentBounds(key).map(({ operator, value }) => ({type: PropertyFilterType.Person,key: property,operator,value,}))+}++/** The persons list, filtered with the same conditions as the segment's cohort. */+export function predictionSegmentPeopleUrl(key: PredictionSegmentKey, property: string): string {+ const properties = segmentPropertyFilters(key, property)const query: DataTableNode = {kind: NodeKind.DataTableNode,source: {@@ -97,3 +104,42 @@ export function predictionSegmentPeopleUrl(key: PredictionSegmentKey, property:}return combineUrl(urls.persons(), {}, { q: query }).url}++export type PredictionLinkDestination = 'feature_flag' | 'workflow' | 'insight'++/** A new feature flag released to the likely segment. */+export function likelySegmentFeatureFlagUrl(property: string): string {+ return urls.featureFlagNew({ properties: segmentPropertyFilters('likely', property) })+}++/** A new batch workflow whose audience is the likely segment. */+export function likelySegmentWorkflowUrl(property: string): string {+ return urlForNewWorkflowWithTrigger({+ type: 'batch',+ filters: { properties: segmentPropertyFilters('likely', property) },+ })+}++/** A new trends insight of the people who did the target, broken down by their predicted probability. */+export function predictionBreakdownInsightUrl(+ { target_definition: target, target_event: event }: AutoresearchPipelineApi,+ property: string+): string {+ const query: InsightVizNode = {+ kind: NodeKind.InsightVizNode,+ source: {+ kind: NodeKind.TrendsQuery,+ series: [+ target.type === 'action'+ ? { kind: NodeKind.ActionsNode, id: target.action_id, math: BaseMathType.UniqueUsers }+ : { kind: NodeKind.EventsNode, event, name: event, math: BaseMathType.UniqueUsers },+ ],+ breakdownFilter: {+ breakdown: property,+ breakdown_type: 'person',+ breakdown_histogram_bin_count: 10,+ },+ },+ }+ return urls.insightNew({ query })+}diff --git a/products/feature_flags/manifest.tsx b/products/feature_flags/manifest.tsxindex f8b44cac14ca..498740b33fd1 100644--- a/products/feature_flags/manifest.tsx+++ b/products/feature_flags/manifest.tsx@@ -2,7 +2,7 @@ import { urls } from 'scenes/urls'import { ProductItemCategory, ProductKey } from '~/queries/schema/schema-general'-import { FileSystemIconColor, ProductManifest } from '../../frontend/src/types'+import { AnyPropertyFilter, FileSystemIconColor, ProductManifest } from '../../frontend/src/types'export const manifest: ProductManifest = {name: 'Feature Flags',@@ -36,12 +36,15 @@ export const manifest: ProductManifest = {template,intent,format,+ properties,}: {type?: 'boolean' | 'multivariate' | 'remote_config'sourceId?: number | string | nulltemplate?: 'simple' | 'targeted' | 'multivariate' | 'targeted-multivariate'intent?: 'local-eval' | 'first-page-load'format?: 'rules_v2'+ /** Release condition properties for a single condition set rolled out to 100%. */+ properties?: AnyPropertyFilter[]}): string => {const params = new URLSearchParams()if (type) {@@ -59,6 +62,9 @@ export const manifest: ProductManifest = {if (format) {params.set('format', format)}+ if (properties?.length) {+ params.set('properties', JSON.stringify(properties))+ }return `/feature_flags/new?${params.toString()}`},},