: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 detail scene (#101575)
Andrew Maguire9d49f00fad1f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex b077b590f032..7ed690502b09 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -6062,6 +6062,22 @@ snapshots:hash: v1.k794b7964.0184f9ca79fe2726f803b9050b013dd0b44a260bb0a6f490400f818ffc27bb55.Y7wikoBvp2ZhegOiwx-qU2WNklUo6ycXa0yGL2beoQoproducts-alerts-simulation-summary--sub-detector-scores--light:hash: v1.k794b7964.0a77535b3969cac543ed48fdcd1117a5fe0305a6d7aa38c7bd8af446d4b1e422.ErlO5Qkh3fOCJ8BDf3qU9EkgKb_AUPbuFPhJpFrPr7M+ products-autoresearch-daily-volume-chart--sparse-days--dark:+ hash: v1.k794b7964.47b1e118bc8c9e9c27efac87a76591e9d2d31a6e2d0c728e9f71180bf65dbd68._gnh7qhODKrYgIH_Ec2BOaeKSqU-OFl8NQYJxMbXL4Y+ products-autoresearch-daily-volume-chart--sparse-days--light:+ hash: v1.k794b7964.870b0a67047e4178e67f74d634013503c70251933c6a413aeddbfe3c8caec512.OajUYKSqaj9iItNqm7LYVShj0OLD2SZVlOY8HQ-BO6w+ products-autoresearch-daily-volume-chart--two-weeks--dark:+ hash: v1.k794b7964.9a713abe443d5a52c29c22dd7555ad8005863f1a7a009702606fa5bd8384a98f.2nVLBkjlKykaLju4RbjgIlLkS-JsIqrCGxIqlHvj2ho+ products-autoresearch-daily-volume-chart--two-weeks--light:+ hash: v1.k794b7964.657b4864698965984216442d166b797580c2400a075a32a666088955114b6e26.5aBdQrW6RrKJjUXMDizdh6cpFHYQ1hqWTxPzdc2duvk+ products-autoresearch-probability-histogram--bimodal--dark:+ hash: v1.k794b7964.54848640bbeba7e0c519e2a4f939bd58aff008ea7f48b96c38f95c825859e29c.8bwWwevDVdQFiWK4kusQ_xTaxhGSYIyHuH6qZFWC18U+ products-autoresearch-probability-histogram--bimodal--light:+ hash: v1.k794b7964.7465c08474c8046d542766f38638d29b338aa735187618003250a820305a7f0a.E5Z0ct7fsOPeVK172KqNscasD4VWpkZqHNkAdPwxb0w+ products-autoresearch-probability-histogram--single-bucket--dark:+ hash: v1.k794b7964.47dc280e27c512035ac74d86134e2b5771f84b1454556c492f6319d9d3ffa29f.l0n9noDhYfjTrpN-tlvi5TJq4RJCDIkUCFKse51o1O4+ products-autoresearch-probability-histogram--single-bucket--light:+ hash: v1.k794b7964.492095448990e600a399d4212b8fb96e8f95c2e7bdafb3f84d8bdc10467fbf4e.1OfZFFoGzmeH8sxtbwrD-H9bR_n08l9kV63NB2Sv1jUproducts-dashboards--dashboard-states--dark:hash: v1.k794b7964.cc591635f83447f7bcfb802062302b8b1bbcd51826110b12fa0f68d4830dcfd3.CIgt_KxCyQRgbn7DPF4MDXc5JBlSxbaCPS0Snyx3cRsproducts-dashboards--dashboard-states--light:diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex 8894ab07f6bc..6078b65ce500 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -41,6 +41,7 @@ export const productScenes: Record<string, () => Promise<any>> = {Annotations: () => import('../../products/annotations/frontend/pages/Annotations'),Autoresearch: () => import('../../products/autoresearch/frontend/AutoresearchScene'),AutoresearchNew: () => import('../../products/autoresearch/frontend/AutoresearchNewScene'),+ AutoresearchPipeline: () => import('../../products/autoresearch/frontend/AutoresearchPipelineScene'),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 342c039f95fa..a02381971ca2 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -101,6 +101,7 @@ export const productRoutes: Record<string, [string, string]> = {'/data-management/annotations/:id': ['Annotations', 'annotation'],'/autoresearch': ['Autoresearch', 'autoresearch'],'/autoresearch/new': ['AutoresearchNew', 'autoresearchNew'],+ '/autoresearch/:id': ['AutoresearchPipeline', 'autoresearchPipeline'],'/business-knowledge': ['BusinessKnowledge', 'businessKnowledge'],'/business-knowledge/settings': ['BusinessKnowledgeSettings', 'businessKnowledgeSettings'],'/business-knowledge/playground': ['BusinessKnowledgePlayground', 'businessKnowledgePlayground'],@@ -623,6 +624,7 @@ export const productConfiguration: Record<string, any> = {iconType: 'experiment',},AutoresearchNew: { name: 'New model', projectBased: true },+ AutoresearchPipeline: { name: 'Autoresearch model', projectBased: true },BusinessKnowledge: {name: 'Business knowledge',projectBased: true,@@ -2158,7 +2160,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => [iconType: 'experiment',tags: ['alpha'],sceneKey: 'Autoresearch',- sceneKeys: ['Autoresearch', 'AutoresearchNew'],+ sceneKeys: ['Autoresearch', 'AutoresearchNew', 'AutoresearchPipeline'],},{path: 'Broadcasts',diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 9dbd2800c92c..890401a7d406 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -19,6 +19,7 @@ export enum Scene {Annotations = 'Annotations',Autoresearch = 'Autoresearch',AutoresearchNew = 'AutoresearchNew',+ AutoresearchPipeline = 'AutoresearchPipeline',Approval = 'Approval',AsyncMigrations = 'AsyncMigrations',BatchExport = 'BatchExport',diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.mdindex 65162a2f45e5..22a56c5110bd 100644--- a/products/autoresearch/frontend/AGENTS.md+++ b/products/autoresearch/frontend/AGENTS.md@@ -1,18 +1,25 @@# Frontend-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.+Three scenes behind the `autoresearch` feature flag: the pipeline list, the create form, and a single pipeline's detail view.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.## What lives here-| File | Scene / role |-| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |-| `AutoresearchScene.tsx` | `/autoresearch` — the pipeline list, with row actions (pause, resume, delete) and the "New model" entry point. |-| `autoresearchLogic.ts` | List logic — loads pipelines, lifecycle actions, and setup-status detection for the empty-state gate. |-| `PipelineStatusTag.tsx` | Status tag + tooltip, shared with the detail scene once it lands. |-| `emptyState/` | `ProductEmptyState` config + example-data preview for the first-run gate. |-| `generated/` | **Generated. Never hand-edit.** Change the serializer in `../backend/presentation/views/serializers.py` and run `hogli build:openapi`. |+| File | Scene / role |+| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------- |+| `AutoresearchScene.tsx` | `/autoresearch` — the pipeline list, with row actions (pause, resume, delete) and the "New model" entry point. |+| `AutoresearchNewScene.tsx` | `/autoresearch/new` — the create form. |+| `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`. |+| `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. |+| `DailyVolumeChart.tsx` | Bar-per-day chart of scoring volume. |+| `pipeline/` | One file per detail-scene tab (Overview, Training, Predictions, Online performance, Suggestions) and their components. |+| `emptyState/` | `ProductEmptyState` config + example-data preview for the first-run gate. |+| `generated/` | **Generated. Never hand-edit.** Change the serializer in `../backend/presentation/views/serializers.py` and run `hogli build:openapi`. |Scene registration, routes, and urls live in `../manifest.tsx`.`frontend/src/products.tsx` is generated from the manifests — hand-editing it there gets wiped by `pnpm build:products`. Only the `Scene` enum entries belong in `sceneTypes.ts`.diff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.tsxnew file mode 100644index 000000000000..146bd469b17f--- /dev/null+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.tsx@@ -0,0 +1,84 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonTab, LemonTabs, Spinner } from '@posthog/lemon-ui'++import { NotFound } from 'lib/components/NotFound'+import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'+import { SceneExport } from 'scenes/sceneTypes'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'++import {+ AutoresearchPipelineLogicProps,+ AutoresearchPipelineTab,+ autoresearchPipelineLogic,+} from './autoresearchPipelineLogic'+import { OnlinePerformanceTab } from './pipeline/OnlinePerformanceTab'+import { OverviewTab } from './pipeline/OverviewTab'+import { PipelineActions } from './pipeline/PipelineActions'+import { PredictionsTab } from './pipeline/PredictionsTab'+import { ScoreNowButton } from './pipeline/ScoreNowButton'+import { SuggestionsTab } from './pipeline/SuggestionsTab'+import { TrainingTab } from './pipeline/TrainingTab'++export const scene: SceneExport = {+ component: AutoresearchPipelineScene,+ logic: autoresearchPipelineLogic,+ paramsToProps: ({ params: { id } }): AutoresearchPipelineLogicProps => ({ id }),+}++export function AutoresearchPipelineScene(): JSX.Element {+ const { pipeline, pipelineLoading, pipelineError, activeTab } = useValues(autoresearchPipelineLogic)+ const { setActiveTab, loadDetail } = useActions(autoresearchPipelineLogic)+ const isEnabled = useFeatureFlag('AUTORESEARCH')++ const tabs: LemonTab<AutoresearchPipelineTab>[] = [+ { key: 'overview', label: 'Overview', content: <OverviewTab /> },+ { key: 'training', label: 'Training', content: <TrainingTab /> },+ { key: 'predictions', label: 'Predictions', content: <PredictionsTab /> },+ { key: 'online_performance', label: 'Online performance', content: <OnlinePerformanceTab /> },+ { key: 'suggestions', label: 'Suggestions', content: <SuggestionsTab /> },+ ]++ const heading = pipeline?.name ?? (pipelineLoading ? '' : 'Model')+ const subheading = pipeline ? `Predict ${pipeline.target_event} within ${pipeline.horizon_days ?? '?'}d` : undefined++ if (!isEnabled) {+ return <NotFound object="Autoresearch" caption="This feature is not enabled for your project." />+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name={heading}+ description={subheading}+ resourceType={{ type: 'experiment' }}+ actions={+ <>+ <ScoreNowButton />+ <PipelineActions />+ </>+ }+ />++ {pipelineLoading && !pipeline ? (+ <Spinner />+ ) : pipelineError && !pipeline ? (+ <LemonBanner+ type="error"+ action={{ children: 'Retry', onClick: () => loadDetail(), 'data-attr': 'autoresearch-model-retry' }}+ >+ Couldn't load this model. It may have been deleted. Try again, or go back to the model list.+ </LemonBanner>+ ) : (+ <LemonTabs+ activeKey={activeTab}+ onChange={(key) => setActiveTab(key as AutoresearchPipelineTab)}+ tabs={tabs}+ sceneInset+ />+ )}+ </SceneContent>+ )+}diff --git a/products/autoresearch/frontend/DailyVolumeChart.stories.tsx b/products/autoresearch/frontend/DailyVolumeChart.stories.tsxnew file mode 100644index 000000000000..f1d0aed22c7b--- /dev/null+++ b/products/autoresearch/frontend/DailyVolumeChart.stories.tsx@@ -0,0 +1,32 @@+import { Meta, StoryObj } from '@storybook/react'++import { DailyVolumeChart } from './DailyVolumeChart'++const meta: Meta<typeof DailyVolumeChart> = {+ title: 'Products/Autoresearch/Daily volume chart',+ component: DailyVolumeChart,+ tags: ['autodocs'],+}+export default meta+type Story = StoryObj<typeof DailyVolumeChart>++const USERS_PER_DAY = [110, 118, 0, 121, 125, 131, 129, 140, 138, 152, 149, 160, 158, 171]++export const TwoWeeks: Story = {+ args: {+ points: USERS_PER_DAY.map((users, i) => ({+ day: `2026-08-${String(i + 1).padStart(2, '0')}`,+ users,+ avgProbabilityPct: 12 + (i % 5),+ })),+ },+}++export const SparseDays: Story = {+ args: {+ points: [+ { day: '2026-06-20', users: 72, avgProbabilityPct: 14.2 },+ { day: '2026-06-25', users: 77, avgProbabilityPct: 15.8 },+ ],+ },+}diff --git a/products/autoresearch/frontend/DailyVolumeChart.tsx b/products/autoresearch/frontend/DailyVolumeChart.tsxnew file mode 100644index 000000000000..4d3545fd7646--- /dev/null+++ b/products/autoresearch/frontend/DailyVolumeChart.tsx@@ -0,0 +1,58 @@+import { Tooltip } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { DailyVolumePoint } from './autoresearchPipelineLogic'++// The h-40 track minus room for the count label above the tallest bar.+const BAR_MAX_HEIGHT_PX = 136++// Up to this many bars there is room to label each one; past it, counts live in+// the tooltips and only the endpoint dates render.+const PER_BAR_LABEL_LIMIT = 14++/** Bar-per-day chart of scoring volume, oldest day first. No chart deps, like ProbabilityHistogram. */+export function DailyVolumeChart({ points }: { points: DailyVolumePoint[] }): JSX.Element {+ const maxUsers = Math.max(...points.map((p) => p.users), 1)+ const labelEachBar = points.length <= PER_BAR_LABEL_LIMIT+ return (+ <div className="max-w-4xl">+ <div className="flex items-end gap-1">+ {points.map((p) => (+ <Tooltip+ key={p.day}+ title={`${dayjs(p.day).format('MMM D, YYYY')}: ${p.users.toLocaleString()} users scored · ${p.avgProbabilityPct}% average probability`}+ >+ <div className="flex-1 min-w-0 max-w-16 flex flex-col items-center gap-0.5">+ <div className="w-full h-40 flex flex-col items-center justify-end gap-0.5">+ {labelEachBar && (+ <span className="text-xs tabular-nums text-secondary">+ {p.users.toLocaleString()}+ </span>+ )}+ <div+ className="w-full rounded-t bg-[var(--data-color-1)] hover:bg-[var(--data-color-1-hover)]"+ style={{+ height: Math.round((BAR_MAX_HEIGHT_PX * p.users) / maxUsers),+ minHeight: p.users > 0 ? 3 : 0,+ }}+ />+ </div>+ {labelEachBar && (+ <span className="text-xs text-muted whitespace-nowrap">+ {dayjs(p.day).format('MMM D')}+ </span>+ )}+ </div>+ </Tooltip>+ ))}+ </div>+ {!labelEachBar && (+ <div className="flex justify-between text-xs text-muted mt-1">+ <span>{dayjs(points[0].day).format('MMM D')}</span>+ <span>{dayjs(points[points.length - 1].day).format('MMM D')}</span>+ </div>+ )}+ </div>+ )+}diff --git a/products/autoresearch/frontend/ProbabilityHistogram.stories.tsx b/products/autoresearch/frontend/ProbabilityHistogram.stories.tsxnew file mode 100644index 000000000000..32b5d4d52bf9--- /dev/null+++ b/products/autoresearch/frontend/ProbabilityHistogram.stories.tsx@@ -0,0 +1,25 @@+import { Meta, StoryObj } from '@storybook/react'++import { ProbabilityHistogram } from './ProbabilityHistogram'++const meta: Meta<typeof ProbabilityHistogram> = {+ title: 'Products/Autoresearch/Probability histogram',+ component: ProbabilityHistogram,+ tags: ['autodocs'],+}+export default meta+type Story = StoryObj<typeof ProbabilityHistogram>++const USERS_PER_DECILE = [30, 1, 4, 3, 0, 1, 3, 2, 3, 81]++export const Bimodal: Story = {+ args: {+ buckets: USERS_PER_DECILE.map((users, decile) => ({ lower: decile / 10, users })),+ },+}++export const SingleBucket: Story = {+ args: {+ buckets: Array.from({ length: 10 }, (_, decile) => ({ lower: decile / 10, users: decile === 9 ? 128 : 0 })),+ },+}diff --git a/products/autoresearch/frontend/ProbabilityHistogram.tsx b/products/autoresearch/frontend/ProbabilityHistogram.tsxnew file mode 100644index 000000000000..d45fdf9bff50--- /dev/null+++ b/products/autoresearch/frontend/ProbabilityHistogram.tsx@@ -0,0 +1,50 @@+import { Tooltip } from '@posthog/lemon-ui'++import { ProbabilityBucket } from './autoresearchPipelineLogic'++// The h-40 track minus room for the count label above the tallest bar.+const BAR_MAX_HEIGHT_PX = 136++/** Fixed-decile histogram of a scoring run's predicted probabilities. No chart deps, like MetricSparkline. */+export function ProbabilityHistogram({ buckets }: { buckets: ProbabilityBucket[] }): JSX.Element {+ const totalUsers = buckets.reduce((sum, bucket) => sum + bucket.users, 0)+ const maxUsers = Math.max(...buckets.map((bucket) => bucket.users), 1)+ return (+ <div className="flex items-end gap-2 max-w-4xl">+ {buckets.map((bucket) => {+ const label = `${Math.round(bucket.lower * 100)}-${Math.round((bucket.lower + 0.1) * 100)}%`+ const share = totalUsers > 0 ? (100 * bucket.users) / totalUsers : 0+ return (+ <Tooltip+ key={bucket.lower}+ title={`${label}: ${bucket.users.toLocaleString()} users (${share.toFixed(1)}% of ${totalUsers.toLocaleString()} scored)`}+ >+ <div className="flex-1 min-w-0 flex flex-col items-center gap-1">+ <div className="w-full h-40 flex flex-col items-center justify-end gap-0.5">+ <span+ className={`text-xs tabular-nums ${bucket.users > 0 ? 'text-secondary' : 'text-muted'}`}+ >+ {bucket.users.toLocaleString()}+ </span>+ <div+ className="w-full rounded-t bg-[var(--data-color-1)] hover:bg-[var(--data-color-1-hover)]"+ style={{+ height: Math.round((BAR_MAX_HEIGHT_PX * bucket.users) / maxUsers),+ minHeight: bucket.users > 0 ? 3 : 0,+ }}+ />+ </div>+ {/* A narrow scene leaves each bucket too little room for the full range, so show its lower bound. */}+ <span className="text-xs text-muted whitespace-nowrap @min-[48rem]/main-content:hidden">+ {Math.round(bucket.lower * 100)}%+ </span>+ <span className="text-xs text-muted whitespace-nowrap hidden @min-[48rem]/main-content:inline">+ {label}+ </span>+ </div>+ </Tooltip>+ )+ })}+ </div>+ )+}diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.test.tsnew file mode 100644index 000000000000..d88b53e074c7--- /dev/null+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts@@ -0,0 +1,133 @@+import { expectLogic } from 'kea-test-utils'++import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import { initKeaTests } from '~/test/init'++import { autoresearchPipelineLogic, trainingRunProgress } from './autoresearchPipelineLogic'+import { autoresearchModelsList, autoresearchRetrieve } from './generated/api'+import { AutoresearchTrainingRunApi, IterationTrailApi } from './generated/api.schemas'++jest.mock('./generated/api', () => ({+ autoresearchRetrieve: jest.fn(),+ autoresearchModelsList: jest.fn(),+ autoresearchTrainingRunsList: jest.fn(),+ autoresearchRunsList: jest.fn(),+ autoresearchSuggestionsList: jest.fn(),+}))++const mockRetrieve = autoresearchRetrieve as jest.Mock+const mockModelsList = autoresearchModelsList as jest.Mock++function makeRun(overrides: Partial<AutoresearchTrainingRunApi>): AutoresearchTrainingRunApi {+ return {+ id: 'run-1',+ pipeline: 'pipeline-1',+ task_url: null,+ status: 'running',+ iteration_count: 0,+ best_holdout_score: null,+ summary: null,+ iterations: [],+ error: '',+ started_at: null,+ completed_at: null,+ created_at: '2026-01-01T00:00:00Z',+ ...overrides,+ } as AutoresearchTrainingRunApi+}++function makeIteration(overrides: Partial<IterationTrailApi>): IterationTrailApi {+ return {+ iteration_number: 0,+ status: 'kept',+ holdout_score: null,+ ...overrides,+ } as IterationTrailApi+}++describe('autoresearchPipelineLogic', () => {+ it('follows every page of models so a champion past the first page still counts', async () => {+ jest.clearAllMocks()+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })+ mockRetrieve.mockResolvedValue({ id: 'pipeline-1', name: 'Model' })+ mockModelsList+ .mockResolvedValueOnce({ results: [{ id: 'challenger', role: 'challenger' }], next: 'page-2' })+ .mockResolvedValueOnce({ results: [{ id: 'champion', role: 'champion' }], next: null })+ const logic = autoresearchPipelineLogic({ id: 'pipeline-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.models.map((m) => m.id)).toEqual(['challenger', 'champion'])+ expect(mockModelsList).toHaveBeenLastCalledWith(expect.any(String), 'pipeline-1', { offset: 1 })+ })++ it('waits for the flag before it loads the model, then loads once', async () => {+ jest.clearAllMocks()+ initKeaTests()+ featureFlagLogic.mount()+ featureFlagLogic.actions.setFeatureFlags([], {})+ mockRetrieve.mockResolvedValue({ id: 'pipeline-1', name: 'Model' })+ const logic = autoresearchPipelineLogic({ id: 'pipeline-1' })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ expect(mockRetrieve).not.toHaveBeenCalled()++ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })+ await expectLogic(logic).toFinishAllListeners()+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })+ await expectLogic(logic).toFinishAllListeners()+ expect(mockRetrieve).toHaveBeenCalledTimes(1)+ })++ describe('trainingRunProgress', () => {+ it('derives progress from live iteration rows while the run is in flight', () => {+ // Persisted fields are only written at completion, so they read 0 / null here.+ const run = makeRun({+ status: 'running',+ iteration_count: 0,+ best_holdout_score: null,+ iterations: [+ makeIteration({ iteration_number: 0, holdout_score: 0.61 }),+ makeIteration({ iteration_number: 1, holdout_score: 0.72 }),+ makeIteration({ iteration_number: 2, status: 'crashed', holdout_score: null }),+ ],+ })+ expect(trainingRunProgress(run)).toEqual({ iterationCount: 3, bestHoldoutScore: 0.72 })+ })++ it('reports no score for an in-flight run whose iterations have no holdout scores yet', () => {+ const run = makeRun({+ status: 'running',+ iterations: [makeIteration({ iteration_number: 0, status: 'discarded', holdout_score: null })],+ })+ expect(trainingRunProgress(run)).toEqual({ iterationCount: 1, bestHoldoutScore: null })+ })++ it('uses the persisted fields once the run completes', () => {+ const run = makeRun({+ status: 'completed',+ iteration_count: 5,+ best_holdout_score: 0.81,+ // Persisted fields win at terminal state even if the serialized trail differs.+ iterations: [makeIteration({ iteration_number: 0, holdout_score: 0.5 })],+ })+ expect(trainingRunProgress(run)).toEqual({ iterationCount: 5, bestHoldoutScore: 0.81 })+ })++ it('reads the recorded iterations of a failed run, whose counters were never written', () => {+ const run = makeRun({+ status: 'failed',+ iteration_count: 0,+ best_holdout_score: null,+ iterations: [+ makeIteration({ iteration_number: 0, holdout_score: 0.64 }),+ makeIteration({ iteration_number: 1, holdout_score: 0.7 }),+ ],+ })+ expect(trainingRunProgress(run)).toEqual({ iterationCount: 2, bestHoldoutScore: 0.7 })+ })+ })+})diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.tsnew file mode 100644index 000000000000..00ec8b4ee211--- /dev/null+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts@@ -0,0 +1,1083 @@+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { actionToUrl, router, urlToAction } from 'kea-router'+import posthog from 'posthog-js'++import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { Scene } from 'scenes/sceneTypes'+import { teamLogic } from 'scenes/teamLogic'+import { urls } from 'scenes/urls'++import { hogql } from '~/queries/utils'+import { Breadcrumb } from '~/types'++import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'+import {+ autoresearchModelsList,+ autoresearchPauseCreate,+ autoresearchResumeCreate,+ autoresearchRetrieve,+ autoresearchRunsList,+ autoresearchScoreCreate,+ autoresearchSuggestionsCreate,+ autoresearchSuggestionsList,+ autoresearchTrainingRunsArtifactsGetCreate,+ autoresearchTrainingRunsArtifactsRetrieve,+ autoresearchTrainingRunsList,+ autoresearchTrainCreate,+} from './generated/api'+import {+ type AutoresearchModelApi,+ type AutoresearchPipelineApi,+ type AutoresearchRunApi,+ type AutoresearchSuggestionApi,+ type AutoresearchTrainingRunApi,+ CreateSuggestionPriorityEnumApi,+} from './generated/api.schemas'++export interface AutoresearchPipelineLogicProps {+ id: string+}++export type AutoresearchPipelineTab = 'overview' | 'training' | 'predictions' | 'online_performance' | 'suggestions'++const AUTORESEARCH_PIPELINE_TABS: AutoresearchPipelineTab[] = [+ 'overview',+ 'training',+ 'predictions',+ 'online_performance',+ 'suggestions',+]++function isPipelineTab(value: string | undefined): value is AutoresearchPipelineTab {+ return value !== undefined && (AUTORESEARCH_PIPELINE_TABS as string[]).includes(value)+}++/** One decile of the latest scoring run's predicted probabilities: `lower` ≤ p < `lower` + 0.1. */+/** How far back the Predictions tab looks for the latest scoring batch, so it never scans the full history. */+export const LATEST_BATCH_LOOKBACK_DAYS = 90++export interface ProbabilityBucket {+ lower: number+ users: number+}++/** Metrics stored in AutoresearchRun.metrics for validation runs. */+interface ValidationRunMetrics {+ prediction_date: string+ realized_labels_count?: number+ warning?: string+ per_model?: Record<+ string,+ {+ emitted_role?: string+ model_role: string+ n_scored: number+ n_positive?: number+ n_negative?: number+ base_rate?: number+ realized_auc?: number+ brier_score?: number+ calibration_error?: number+ lift_at_10?: number+ lift_at_20?: number+ warning?: string+ }+ >+}++/** The list endpoints page at 100 rows. Follow every page so a long-lived model shows its whole history. */+async function fetchAllPages<T>(+ fetchPage: (offset: number) => Promise<{ results: T[]; next?: string | null }>+): Promise<T[]> {+ const rows: T[] = []+ for (;;) {+ const response = await fetchPage(rows.length)+ rows.push(...response.results)+ if (!response.next || response.results.length === 0) {+ return rows+ }+ }+}++/** A decoded artifact bundle file, ready for display. */+interface ViewedArtifact {+ runId: string+ path: string+ sizeBytes: number+ /** UTF-8 text for text files; null when the file is binary (e.g. model.pkl, parquet). */+ text: string | null+}++/** Bundle paths we render inline as text; anything else is treated as binary. */+const TEXT_ARTIFACT_EXTENSIONS = ['.py', '.sql', '.yml', '.yaml', '.json', '.md', '.txt', '.ipynb', '.csv']++function isTextArtifact(path: string): boolean {+ return TEXT_ARTIFACT_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))+}++function base64ToUtf8(base64: string): string {+ const binary = atob(base64)+ const bytes = new Uint8Array(binary.length)+ for (let i = 0; i < binary.length; i++) {+ bytes[i] = binary.charCodeAt(i)+ }+ return new TextDecoder('utf-8').decode(bytes)+}++/** Displayed progress for a training run. */+interface TrainingRunProgress {+ iterationCount: number+ bestHoldoutScore: number | null+}++/**+ * The persisted iteration_count and best_holdout_score are only written at completion,+ * so while a run is in flight we derive progress from the iteration rows, which land live.+ */+export function trainingRunProgress(run: AutoresearchTrainingRunApi): TrainingRunProgress {+ // Only completion writes the counters; a failed run keeps them at zero, so read its recorded iterations.+ if (run.status === 'completed') {+ return { iterationCount: run.iteration_count, bestHoldoutScore: run.best_holdout_score }+ }+ const scores = run.iterations.map((it) => it.holdout_score).filter((score): score is number => score != null)+ return {+ iterationCount: run.iterations.length,+ bestHoldoutScore: scores.length > 0 ? Math.max(...scores) : null,+ }+}++/** One scoring day's volume: emitted prediction events and their average probability as a 0-100 percentage. */+export interface DailyVolumePoint {+ day: string+ users: number+ avgProbabilityPct: number+}++/** Flattened row for the online performance table. */+export interface OnlinePerformanceRow {+ run_id: string+ model_id: string+ prediction_date: string+ /** The role the model held when it emitted these predictions; `model_role` is its role now. */+ emitted_role: string+ model_role: string+ n_scored: number+ realized_auc: number | null+ brier_score: number | null+ calibration_error: number | null+ lift_at_10: number | null+ lift_at_20: number | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface autoresearchPipelineLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogic+ currentTeamId: number | null // teamLogic+ activeTab: AutoresearchPipelineTab+ artifactsByRun: Record<string, string[]>+ artifactsByRunLoading: boolean+ breadcrumbs: Breadcrumb[]+ dailyVolume: DailyVolumePoint[] | null+ dailyVolumeError: boolean+ dailyVolumeLoading: boolean+ detailRequested: boolean+ expandedRunId: string | null+ models: AutoresearchModelApi[]+ modelsLoading: boolean+ onlinePerformanceRows: OnlinePerformanceRow[]+ pipeline: AutoresearchPipelineApi | null+ pipelineError: boolean+ pipelineLoading: boolean+ probabilityDistribution: ProbabilityBucket[] | null+ probabilityDistributionError: boolean+ probabilityDistributionLoading: boolean+ probabilityHistogram: ProbabilityBucket[] | null+ reportByRun: Record<string, string | null>+ reportByRunLoading: boolean+ runs: AutoresearchRunApi[]+ runsError: boolean+ runsLoading: boolean+ scoreResult: AutoresearchRunApi | null+ scoreResultLoading: boolean+ startTrainingResult: AutoresearchTrainingRunApi | null+ startTrainingResultLoading: boolean+ suggestionDraft: string+ suggestionPriority: CreateSuggestionPriorityEnumApi+ suggestionSubmitResult: AutoresearchSuggestionApi | null+ suggestionSubmitResultLoading: boolean+ suggestions: AutoresearchSuggestionApi[]+ suggestionsError: boolean+ suggestionsLoading: boolean+ trainingRuns: AutoresearchTrainingRunApi[]+ trainingRunsError: boolean+ trainingRunsLoading: boolean+ validationRuns: AutoresearchRunApi[]+ viewedArtifact: ViewedArtifact | null+ viewedArtifactLoading: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface autoresearchPipelineLogicActions {+ setFeatureFlags: (+ flags: string[],+ variants: Record<string, boolean | string>+ ) => {+ flags: string[]+ variants: Record<string, boolean | string>+ } // featureFlagLogic+ loadCurrentTeamSuccess: (+ currentTeam: null | import('~/types').TeamPublicType,+ payload?: any+ ) => {+ currentTeam: null | import('~/types').TeamPublicType+ payload?: any+ } // teamLogic+ closeArtifact: () => any+ closeArtifactFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ closeArtifactSuccess: (+ viewedArtifact: null,+ payload?: any+ ) => {+ viewedArtifact: null+ payload?: any+ }+ loadDailyVolume: () => any+ loadDailyVolumeFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadDailyVolumeSuccess: (+ dailyVolume: {+ avgProbabilityPct: number+ day: string+ users: number+ }[],+ payload?: any+ ) => {+ dailyVolume: {+ avgProbabilityPct: number+ day: string+ users: number+ }[]+ payload?: any+ }+ loadDetail: () => {+ value: true+ }+ loadModels: () => any+ loadModelsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadModelsSuccess: (+ models: AutoresearchModelApi[],+ payload?: any+ ) => {+ models: AutoresearchModelApi[]+ payload?: any+ }+ loadPipeline: () => any+ loadPipelineFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadPipelineSuccess: (+ pipeline: AutoresearchPipelineApi | null,+ payload?: any+ ) => {+ pipeline: AutoresearchPipelineApi | null+ payload?: any+ }+ loadProbabilityDistribution: () => any+ loadProbabilityDistributionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadProbabilityDistributionSuccess: (+ probabilityDistribution: {+ lower: number+ users: number+ }[],+ payload?: any+ ) => {+ probabilityDistribution: {+ lower: number+ users: number+ }[]+ payload?: any+ }+ loadRunArtifacts: ({ runId }: { runId: string }) => {+ runId: string+ }+ loadRunArtifactsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunArtifactsSuccess: (+ artifactsByRun: Record<string, string[]>,+ payload?: {+ runId: string+ }+ ) => {+ artifactsByRun: Record<string, string[]>+ payload?: {+ runId: string+ }+ }+ loadRunReport: ({ runId }: { runId: string }) => {+ runId: string+ }+ loadRunReportFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunReportSuccess: (+ reportByRun: Record<string, string | null>,+ payload?: {+ runId: string+ }+ ) => {+ reportByRun: Record<string, string | null>+ payload?: {+ runId: string+ }+ }+ loadRuns: () => any+ loadRunsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadRunsSuccess: (+ runs: AutoresearchRunApi[],+ payload?: any+ ) => {+ runs: AutoresearchRunApi[]+ payload?: any+ }+ loadSuggestions: () => any+ loadSuggestionsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadSuggestionsSuccess: (+ suggestions: AutoresearchSuggestionApi[],+ payload?: any+ ) => {+ suggestions: AutoresearchSuggestionApi[]+ payload?: any+ }+ loadTrainingRuns: () => any+ loadTrainingRunsFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTrainingRunsSuccess: (+ trainingRuns: AutoresearchTrainingRunApi[],+ payload?: any+ ) => {+ trainingRuns: AutoresearchTrainingRunApi[]+ payload?: any+ }+ pausePipeline: () => any+ pausePipelineFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ pausePipelineSuccess: (+ pipeline: AutoresearchPipelineApi | null,+ payload?: any+ ) => {+ pipeline: AutoresearchPipelineApi | null+ payload?: any+ }+ resumePipeline: () => any+ resumePipelineFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ resumePipelineSuccess: (+ pipeline: AutoresearchPipelineApi | null,+ payload?: any+ ) => {+ pipeline: AutoresearchPipelineApi | null+ payload?: any+ }+ scoreNow: () => any+ scoreNowFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ scoreNowSuccess: (+ scoreResult: AutoresearchRunApi | null,+ payload?: any+ ) => {+ scoreResult: AutoresearchRunApi | null+ payload?: any+ }+ setActiveTab: (tab: AutoresearchPipelineTab) => {+ tab: AutoresearchPipelineTab+ }+ setSuggestionDraft: (draft: string) => {+ draft: string+ }+ setSuggestionPriority: (priority: CreateSuggestionPriorityEnumApi) => {+ priority: CreateSuggestionPriorityEnumApi+ }+ startTraining: () => any+ startTrainingFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ startTrainingSuccess: (+ startTrainingResult: AutoresearchTrainingRunApi | null,+ payload?: any+ ) => {+ startTrainingResult: AutoresearchTrainingRunApi | null+ payload?: any+ }+ submitSuggestion: () => any+ submitSuggestionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ submitSuggestionSuccess: (+ suggestionSubmitResult: AutoresearchSuggestionApi | null,+ payload?: any+ ) => {+ suggestionSubmitResult: AutoresearchSuggestionApi | null+ payload?: any+ }+ toggleRunArtifacts: (runId: string) => {+ runId: string+ }+ viewArtifact: ({ runId, path }: { path: string; runId: string }) => {+ runId: string+ path: string+ }+ viewArtifactFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ viewArtifactSuccess: (+ viewedArtifact: {+ path: string+ runId: string+ sizeBytes: number+ text: string | null+ } | null,+ payload?: {+ runId: string+ path: string+ }+ ) => {+ viewedArtifact: {+ path: string+ runId: string+ sizeBytes: number+ text: string | null+ } | null+ payload?: {+ runId: string+ path: string+ }+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface autoresearchPipelineLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ breadcrumbs: (pipeline: AutoresearchPipelineApi | null) => Breadcrumb[]+ validationRuns: (runs: AutoresearchRunApi[]) => AutoresearchRunApi[]+ onlinePerformanceRows: (validationRuns: AutoresearchRunApi[]) => OnlinePerformanceRow[]+ probabilityHistogram: (probabilityDistribution: ProbabilityBucket[] | null) => ProbabilityBucket[] | null+ }+}++export type autoresearchPipelineLogicType = MakeLogicType<+ autoresearchPipelineLogicValues,+ autoresearchPipelineLogicActions,+ AutoresearchPipelineLogicProps,+ autoresearchPipelineLogicMeta+>++export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([+ path((key) => ['products', 'autoresearch', 'autoresearchPipelineLogic', key]),+ props({} as AutoresearchPipelineLogicProps),+ key((props) => props.id),+ connect({+ values: [teamLogic, ['currentTeamId'], featureFlagLogic, ['featureFlags']],+ actions: [teamLogic, ['loadCurrentTeamSuccess'], featureFlagLogic, ['setFeatureFlags']],+ }),+ actions({+ setActiveTab: (tab: AutoresearchPipelineTab) => ({ tab }),+ loadDetail: true,+ toggleRunArtifacts: (runId: string) => ({ runId }),+ setSuggestionDraft: (draft: string) => ({ draft }),+ setSuggestionPriority: (priority: CreateSuggestionPriorityEnumApi) => ({ priority }),+ }),+ reducers({+ detailRequested: [+ false,+ {+ loadDetail: () => true,+ },+ ],+ activeTab: [+ 'overview' as AutoresearchPipelineTab,+ {+ setActiveTab: (_, { tab }) => tab,+ },+ ],+ expandedRunId: [+ null as string | null,+ {+ toggleRunArtifacts: (current, { runId }) => (current === runId ? null : runId),+ },+ ],+ suggestionDraft: [+ '',+ {+ setSuggestionDraft: (_, { draft }) => draft,+ submitSuggestionSuccess: () => '',+ },+ ],+ suggestionPriority: [+ CreateSuggestionPriorityEnumApi.Consider as CreateSuggestionPriorityEnumApi,+ {+ setSuggestionPriority: (_, { priority }) => priority,+ },+ ],+ probabilityDistributionError: [+ false,+ {+ loadProbabilityDistribution: () => false,+ loadProbabilityDistributionFailure: () => true,+ },+ ],+ pipelineError: [+ false,+ {+ loadPipeline: () => false,+ loadPipelineSuccess: () => false,+ loadPipelineFailure: () => true,+ },+ ],+ trainingRunsError: [+ false,+ {+ loadTrainingRuns: () => false,+ loadTrainingRunsFailure: () => true,+ },+ ],+ runsError: [+ false,+ {+ loadRuns: () => false,+ loadRunsFailure: () => true,+ },+ ],+ suggestionsError: [+ false,+ {+ loadSuggestions: () => false,+ loadSuggestionsFailure: () => true,+ },+ ],+ dailyVolumeError: [+ false,+ {+ loadDailyVolume: () => false,+ loadDailyVolumeFailure: () => true,+ },+ ],+ }),+ loaders(({ values, props }) => ({+ pipeline: [+ null as AutoresearchPipelineApi | null,+ {+ loadPipeline: async () => {+ if (!values.currentTeamId) {+ return null+ }+ return autoresearchRetrieve(String(values.currentTeamId), props.id)+ },+ pausePipeline: async () => {+ if (!values.currentTeamId || !values.pipeline) {+ return values.pipeline+ }+ // The endpoint ignores the body (it only flips status), but the generated+ // client types a pipeline body — pass the current one to satisfy it.+ return autoresearchPauseCreate(String(values.currentTeamId), props.id)+ },+ resumePipeline: async () => {+ if (!values.currentTeamId || !values.pipeline) {+ return values.pipeline+ }+ return autoresearchResumeCreate(String(values.currentTeamId), props.id)+ },+ },+ ],+ models: [+ [] as AutoresearchModelApi[],+ {+ loadModels: async () => {+ if (!values.currentTeamId) {+ return []+ }+ const teamId = String(values.currentTeamId)+ return fetchAllPages((offset) => autoresearchModelsList(teamId, props.id, { offset }))+ },+ },+ ],+ trainingRuns: [+ [] as AutoresearchTrainingRunApi[],+ {+ loadTrainingRuns: async () => {+ if (!values.currentTeamId) {+ return []+ }+ const teamId = String(values.currentTeamId)+ return fetchAllPages((offset) => autoresearchTrainingRunsList(teamId, props.id, { offset }))+ },+ },+ ],+ runs: [+ [] as AutoresearchRunApi[],+ {+ loadRuns: async () => {+ if (!values.currentTeamId) {+ return []+ }+ const teamId = String(values.currentTeamId)+ return fetchAllPages((offset) => autoresearchRunsList(teamId, props.id, { offset }))+ },+ },+ ],+ suggestions: [+ [] as AutoresearchSuggestionApi[],+ {+ loadSuggestions: async () => {+ if (!values.currentTeamId) {+ return []+ }+ const teamId = String(values.currentTeamId)+ return fetchAllPages((offset) => autoresearchSuggestionsList(teamId, props.id, { offset }))+ },+ },+ ],+ startTrainingResult: [+ null as AutoresearchTrainingRunApi | null,+ {+ startTraining: async () => {+ if (!values.currentTeamId) {+ return null+ }+ const result = await autoresearchTrainCreate(String(values.currentTeamId), props.id)+ return result+ },+ },+ ],+ artifactsByRun: [+ {} as Record<string, string[]>,+ {+ loadRunArtifacts: async ({ runId }: { runId: string }) => {+ if (!values.currentTeamId) {+ return values.artifactsByRun+ }+ const response = await autoresearchTrainingRunsArtifactsRetrieve(+ String(values.currentTeamId),+ props.id,+ runId+ )+ return { ...values.artifactsByRun, [runId]: response.paths }+ },+ },+ ],+ reportByRun: [+ {} as Record<string, string | null>,+ {+ // A run's report.md, decoded to text. null = loaded but the agent uploaded no report.+ loadRunReport: async ({ runId }: { runId: string }) => {+ if (!values.currentTeamId) {+ return values.reportByRun+ }+ try {+ const response = await autoresearchTrainingRunsArtifactsGetCreate(+ String(values.currentTeamId),+ props.id,+ runId,+ { path: 'report.md' }+ )+ return { ...values.reportByRun, [runId]: base64ToUtf8(response.content_base64) }+ } catch {+ return { ...values.reportByRun, [runId]: null }+ }+ },+ },+ ],+ viewedArtifact: [+ null as ViewedArtifact | null,+ {+ viewArtifact: async ({ runId, path }: { runId: string; path: string }) => {+ if (!values.currentTeamId) {+ return null+ }+ const response = await autoresearchTrainingRunsArtifactsGetCreate(+ String(values.currentTeamId),+ props.id,+ runId,+ { path }+ )+ return {+ runId,+ path: response.path,+ sizeBytes: response.size_bytes,+ text: isTextArtifact(response.path) ? base64ToUtf8(response.content_base64) : null,+ }+ },+ closeArtifact: () => null,+ },+ ],+ scoreResult: [+ null as AutoresearchRunApi | null,+ {+ scoreNow: async () => {+ if (!values.currentTeamId) {+ return null+ }+ return autoresearchScoreCreate(String(values.currentTeamId), props.id)+ },+ },+ ],+ probabilityDistribution: [+ null as ProbabilityBucket[] | null,+ {+ loadProbabilityDistribution: async () => {+ // A scoring run stamps its whole batch with one timestamp, so the latest batch is its exact timestamp.+ const response = await api.queryHogQL(+ hogql`+ SELECT least(floor(p * 10), 9) AS bucket, count() AS users+ FROM (+ SELECT+ coalesce(nullIf(properties.$autoresearch_person_id, ''), distinct_id) AS person_id,+ argMax(toFloat(properties.$autoresearch_p_y), timestamp) AS p+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = ${props.id}+ AND timestamp = (+ SELECT max(timestamp)+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = ${props.id}+ AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY+ )+ GROUP BY person_id+ )+ GROUP BY bucket+ ORDER BY bucket+ `,+ { productKey: 'autoresearch', name: 'autoresearch_probability_distribution' }+ )+ return (response.results ?? []).map((row: any[]) => ({+ lower: Number(row[0]) / 10,+ users: Number(row[1]),+ }))+ },+ },+ ],+ dailyVolume: [+ null as DailyVolumePoint[] | null,+ {+ loadDailyVolume: async () => {+ // The last 60 days, returned oldest-first for left-to-right display. The time bound keeps the scan off the full history.+ const response = await api.queryHogQL(+ hogql`+ SELECT toDate(timestamp) AS day,+ count() AS users_scored,+ round(100 * avg(toFloat(properties.$autoresearch_p_y)), 1) AS avg_probability+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = ${props.id}+ AND timestamp >= now() - INTERVAL 60 DAY+ GROUP BY day+ ORDER BY day DESC+ LIMIT 60+ `,+ { productKey: 'autoresearch', name: 'autoresearch_daily_volume' }+ )+ return (response.results ?? [])+ .map((row: any[]) => ({+ day: String(row[0]),+ users: Number(row[1]),+ avgProbabilityPct: Number(row[2]),+ }))+ .reverse()+ },+ },+ ],+ suggestionSubmitResult: [+ null as AutoresearchSuggestionApi | null,+ {+ submitSuggestion: async () => {+ if (!values.currentTeamId || !values.suggestionDraft.trim()) {+ return null+ }+ return autoresearchSuggestionsCreate(String(values.currentTeamId), props.id, {+ prompt: values.suggestionDraft.trim(),+ priority: values.suggestionPriority,+ })+ },+ },+ ],+ })),+ selectors({+ breadcrumbs: [+ (s) => [s.pipeline],+ (pipeline: AutoresearchPipelineApi | null): Breadcrumb[] => [+ {+ key: Scene.Autoresearch,+ name: 'Autoresearch',+ path: urls.autoresearch(),+ },+ {+ key: [Scene.AutoresearchPipeline, pipeline?.id ?? 'unknown'],+ name: pipeline?.name ?? 'Model',+ },+ ],+ ],+ validationRuns: [+ (s) => [s.runs],+ (runs: AutoresearchRunApi[]): AutoresearchRunApi[] =>+ runs.filter((r) => r.run_type === 'validation' && r.status === 'completed'),+ ],+ onlinePerformanceRows: [+ (s) => [s.validationRuns],+ (validationRuns: AutoresearchRunApi[]): OnlinePerformanceRow[] => {+ const rows: OnlinePerformanceRow[] = []+ for (const run of validationRuns) {+ const m = run.metrics as Partial<ValidationRunMetrics> | null+ if (!m?.prediction_date) {+ continue+ }+ if (!m.per_model || Object.keys(m.per_model).length === 0) {+ continue+ }+ for (const [modelId, model] of Object.entries(m.per_model)) {+ rows.push({+ run_id: run.id,+ model_id: modelId,+ prediction_date: m.prediction_date,+ emitted_role: model.emitted_role ?? model.model_role,+ model_role: model.model_role,+ n_scored: model.n_scored,+ realized_auc: model.realized_auc ?? null,+ brier_score: model.brier_score ?? null,+ calibration_error: model.calibration_error ?? null,+ lift_at_10: model.lift_at_10 ?? null,+ lift_at_20: model.lift_at_20 ?? null,+ })+ }+ }+ // Sort by date descending, champion before challenger within same date+ rows.sort((a, b) => {+ if (b.prediction_date !== a.prediction_date) {+ return b.prediction_date.localeCompare(a.prediction_date)+ }+ return a.emitted_role === 'champion' ? -1 : 1+ })+ return rows+ },+ ],+ probabilityHistogram: [+ (s) => [s.probabilityDistribution],+ (probabilityDistribution: ProbabilityBucket[] | null): ProbabilityBucket[] | null => {+ if (!probabilityDistribution) {+ return null+ }+ const usersByDecile = new Map(probabilityDistribution.map((b) => [Math.round(b.lower * 10), b.users]))+ return Array.from({ length: 10 }, (_, decile) => ({+ lower: decile / 10,+ users: usersByDecile.get(decile) ?? 0,+ }))+ },+ ],+ }),+ listeners(({ actions, values, props }) => ({+ loadDetail: () => {+ actions.loadPipeline()+ actions.loadModels()+ actions.loadTrainingRuns()+ actions.loadRuns()+ actions.loadSuggestions()+ },+ loadCurrentTeamSuccess: () => {+ if (values.featureFlags[FEATURE_FLAGS.AUTORESEARCH]) {+ actions.loadDetail()+ }+ },+ setFeatureFlags: () => {+ // Flags can arrive after mount, when afterMount already skipped the load. Start it once the flag is on.+ if (values.featureFlags[FEATURE_FLAGS.AUTORESEARCH] && !values.detailRequested) {+ posthog.capture('autoresearch model viewed', { pipeline_id: props.id })+ actions.loadDetail()+ }+ },+ loadPipelineFailure: () => {+ posthog.capture('autoresearch model load failed', { pipeline_id: props.id })+ },+ loadPipelineSuccess: ({ pipeline }) => {+ // The prediction-event queries are only worth running once the pipeline has ever scored.+ if (pipeline?.last_scored_at && !values.probabilityDistribution && !values.probabilityDistributionLoading) {+ actions.loadProbabilityDistribution()+ }+ if (pipeline?.last_scored_at && !values.dailyVolume && !values.dailyVolumeLoading) {+ actions.loadDailyVolume()+ }+ },+ startTrainingSuccess: () => {+ posthog.capture('autoresearch model training started', { pipeline_id: props.id })+ actions.loadTrainingRuns()+ actions.loadPipeline()+ lemonToast.success('Training run started')+ },+ startTrainingFailure: () => {+ posthog.capture('autoresearch model action failed', { action: 'train', pipeline_id: props.id })+ lemonToast.error('Could not start training run')+ },+ pausePipelineSuccess: () => {+ posthog.capture('autoresearch model paused', { pipeline_id: props.id })+ lemonToast.success('Model paused. Scheduled scoring is on hold.')+ },+ pausePipelineFailure: () => {+ posthog.capture('autoresearch model action failed', { action: 'pause', pipeline_id: props.id })+ lemonToast.error('Could not pause the model')+ },+ resumePipelineSuccess: () => {+ posthog.capture('autoresearch model resumed', { pipeline_id: props.id })+ lemonToast.success('Model resumed')+ },+ resumePipelineFailure: () => {+ posthog.capture('autoresearch model action failed', { action: 'resume', pipeline_id: props.id })+ lemonToast.error('Could not resume the model')+ },+ scoreNowSuccess: ({ scoreResult }) => {+ posthog.capture('autoresearch model scored', { pipeline_id: props.id })+ actions.loadRuns()+ actions.loadPipeline()+ actions.loadProbabilityDistribution()+ actions.loadDailyVolume()+ const scored = scoreResult?.rows_scored+ lemonToast.success(scored != null ? `Scored ${scored.toLocaleString()} users` : 'Scoring run started')+ },+ scoreNowFailure: () => {+ posthog.capture('autoresearch model action failed', { action: 'score', pipeline_id: props.id })+ lemonToast.error('Could not score users. Train a champion model first.')+ },+ submitSuggestionSuccess: () => {+ posthog.capture('autoresearch model suggestion sent', { pipeline_id: props.id })+ actions.loadSuggestions()+ lemonToast.success('Suggestion sent. The agent will pick it up on its next run.')+ },+ submitSuggestionFailure: () => {+ posthog.capture('autoresearch model action failed', { action: 'suggest', pipeline_id: props.id })+ lemonToast.error('Could not submit the suggestion')+ },+ toggleRunArtifacts: ({ runId }) => {+ // Lazy-load a run's bundle and report the first time it's expanded.+ if (values.expandedRunId === runId) {+ if (!values.artifactsByRun[runId]) {+ actions.loadRunArtifacts({ runId })+ }+ if (values.reportByRun[runId] === undefined) {+ actions.loadRunReport({ runId })+ }+ }+ },+ })),+ actionToUrl(({ values }) => ({+ // Reflect the active tab in the URL (?tab=…) so each tab is deep-linkable.+ setActiveTab: ({ tab }) => {+ const searchParams = { ...router.values.searchParams }+ if (tab === 'overview') {+ delete searchParams.tab+ } else {+ searchParams.tab = tab+ }+ if ((router.values.searchParams.tab ?? 'overview') === (values.activeTab as string)) {+ return // no-op when the URL already matches (avoids a redundant history entry)+ }+ return [router.values.location.pathname, searchParams, router.values.hashParams]+ },+ })),+ urlToAction(({ actions, values }) => ({+ '/autoresearch/:id': (_, searchParams) => {+ const tab = isPipelineTab(searchParams.tab) ? searchParams.tab : 'overview'+ if (tab !== values.activeTab) {+ actions.setActiveTab(tab)+ }+ },+ })),+ afterMount(({ actions, values, props }) => {+ // With the flag off the scene shows NotFound, so there is nothing to record or load.+ if (values.featureFlags[FEATURE_FLAGS.AUTORESEARCH]) {+ posthog.capture('autoresearch model viewed', { pipeline_id: props.id })+ actions.loadDetail()+ }+ }),+])diff --git a/products/autoresearch/frontend/pipeline/ArtifactViewerModal.tsx b/products/autoresearch/frontend/pipeline/ArtifactViewerModal.tsxnew file mode 100644index 000000000000..3d8951e5a774--- /dev/null+++ b/products/autoresearch/frontend/pipeline/ArtifactViewerModal.tsx@@ -0,0 +1,55 @@+import { useActions, useValues } from 'kea'++import { LemonModal, Spinner } from '@posthog/lemon-ui'++import { CodeSnippet, Language } from 'lib/components/CodeSnippet'+import { humanizeBytes } from 'lib/utils/numbers'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'++function languageForArtifact(path: string): Language {+ const lower = path.toLowerCase()+ if (lower.endsWith('.py')) {+ return Language.Python+ }+ if (lower.endsWith('.sql')) {+ return Language.SQL+ }+ if (lower.endsWith('.yml') || lower.endsWith('.yaml')) {+ return Language.YAML+ }+ if (lower.endsWith('.json') || lower.endsWith('.ipynb')) {+ return Language.JSON+ }+ return Language.Text+}++export function ArtifactViewerModal(): JSX.Element {+ const { viewedArtifact, viewedArtifactLoading } = useValues(autoresearchPipelineLogic)+ const { closeArtifact } = useActions(autoresearchPipelineLogic)+ return (+ <LemonModal+ isOpen={viewedArtifactLoading || viewedArtifact !== null}+ onClose={closeArtifact}+ title={viewedArtifact?.path ?? 'Artifact'}+ description={+ viewedArtifact+ ? `${humanizeBytes(viewedArtifact.sizeBytes)} · run ${viewedArtifact.runId.slice(0, 8)}`+ : undefined+ }+ width={960}+ >+ {viewedArtifactLoading ? (+ <Spinner />+ ) : viewedArtifact?.text != null ? (+ <CodeSnippet language={languageForArtifact(viewedArtifact.path)} wrap maxLinesWithoutExpansion={40}>+ {viewedArtifact.text}+ </CodeSnippet>+ ) : (+ <div className="text-muted text-sm">+ Binary file ({viewedArtifact ? humanizeBytes(viewedArtifact.sizeBytes) : ''}). No preview available.+ </div>+ )}+ </LemonModal>+ )+}diff --git a/products/autoresearch/frontend/pipeline/EmptyTab.tsx b/products/autoresearch/frontend/pipeline/EmptyTab.tsxnew file mode 100644index 000000000000..ca2a1f651727--- /dev/null+++ b/products/autoresearch/frontend/pipeline/EmptyTab.tsx@@ -0,0 +1,21 @@+/** Shared empty-state block: an icon, a headline, supporting copy, and an optional CTA. */+export function EmptyTab({+ icon,+ title,+ children,+ cta,+}: {+ icon: JSX.Element+ title: string+ children: React.ReactNode+ cta?: JSX.Element+}): JSX.Element {+ return (+ <div className="flex flex-col items-center text-center gap-2 border border-dashed rounded p-8 text-muted">+ <span className="text-2xl text-secondary">{icon}</span>+ <div className="text-sm font-semibold text-default">{title}</div>+ <div className="text-sm max-w-prose">{children}</div>+ {cta}+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx b/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsxnew file mode 100644index 000000000000..2aface54b1f9--- /dev/null+++ b/products/autoresearch/frontend/pipeline/FeatureImportanceChart.tsx@@ -0,0 +1,109 @@+import { LemonCollapse, Tooltip } from '@posthog/lemon-ui'++interface FeatureImportance {+ name: string+ direction?: string+ importance?: number+ note?: string+}++/** Pull the typed top-features list + note out of the loosely-typed model_explanation JSON. */+function parseExplanation(explanation: unknown): { features: FeatureImportance[]; note: string | null } {+ if (!explanation || typeof explanation !== 'object') {+ return { features: [], note: null }+ }+ const obj = explanation as { top_features?: unknown; note?: unknown }+ const note = typeof obj.note === 'string' ? obj.note : null+ const raw = Array.isArray(obj.top_features) ? obj.top_features : []+ const features = raw+ .map((f): FeatureImportance | null => {+ if (!f || typeof f !== 'object') {+ return null+ }+ const { name, direction, importance, note: featureNote } = f as Record<string, unknown>+ if (typeof name !== 'string') {+ return null+ }+ return {+ name,+ direction: typeof direction === 'string' ? direction : undefined,+ importance: typeof importance === 'number' ? importance : undefined,+ note: typeof featureNote === 'string' ? featureNote : undefined,+ }+ })+ .filter((f): f is FeatureImportance => f !== null)+ // The agent already lists features strongest-first; only re-rank when it gave numbers.+ if (features.some((f) => f.importance != null)) {+ features.sort((a, b) => (b.importance ?? 0) - (a.importance ?? 0))+ }+ return { features, note }+}++/**+ * A model's top feature drivers: importance bars when the agent supplied numeric+ * importances, otherwise a ranked list with the agent's per-feature notes.+ */+export function FeatureImportanceChart({ explanation }: { explanation: unknown }): JSX.Element | null {+ const { features, note } = parseExplanation(explanation)+ if (features.length === 0) {+ return null+ }+ const hasImportances = features.some((f) => f.importance != null)+ // Gain has no fixed scale, so bars are relative to the strongest feature.+ const maxImportance = Math.max(0, ...features.map((f) => f.importance ?? 0))+ const content = (+ <div className="space-y-2">+ <div className="text-xs text-muted">+ <span style={{ color: 'var(--success)' }}>● raises</span>{' '}+ <span style={{ color: 'var(--danger)' }}>● lowers</span> the prediction+ {hasImportances ? ' · bars relative to the strongest feature' : ' · strongest first'}+ </div>+ <div className="space-y-1">+ {features.map((f) => {+ const isNegative = f.direction === 'negative'+ const isPositive = f.direction === 'positive'+ const color = isNegative ? 'var(--danger)' : isPositive ? 'var(--success)' : 'var(--muted)'+ const effect = isNegative ? 'Lowers' : isPositive ? 'Raises' : 'Unknown effect on'+ return (+ <div key={f.name} className="flex items-center gap-2 text-sm">+ <div className="w-48 shrink-0 truncate font-mono text-xs" title={f.name}>+ <span style={{ color }}>● </span>+ {f.name}+ </div>+ {hasImportances ? (+ <div+ className="flex-1 rounded h-4 overflow-hidden"+ style={{ backgroundColor: 'var(--border)' }}+ >+ <Tooltip+ title={`${effect} the prediction · importance ${(f.importance ?? 0).toFixed(3)}`}+ >+ <div+ className="h-full rounded"+ style={{+ width: `${maxImportance > 0 ? Math.max(2, ((f.importance ?? 0) / maxImportance) * 100) : 2}%`,+ backgroundColor: color,+ }}+ />+ </Tooltip>+ </div>+ ) : (+ <Tooltip title={f.note}>+ <div className="flex-1 min-w-0 truncate text-xs text-muted">{f.note}</div>+ </Tooltip>+ )}+ </div>+ )+ })}+ </div>+ {note && <div className="text-xs text-muted italic">{note}</div>}+ </div>+ )+ return (+ <LemonCollapse+ size="small"+ defaultActiveKey="features"+ panels={[{ key: 'features', header: 'Top feature drivers', content }]}+ />+ )+}diff --git a/products/autoresearch/frontend/pipeline/IterationTrail.tsx b/products/autoresearch/frontend/pipeline/IterationTrail.tsxnew file mode 100644index 000000000000..4b2631e480ff--- /dev/null+++ b/products/autoresearch/frontend/pipeline/IterationTrail.tsx@@ -0,0 +1,80 @@+import { LemonTag } from '@posthog/lemon-ui'++import { AutoresearchIterationStatusEnumApi, IterationTrailApi } from '../generated/api.schemas'++const ITERATION_STATUS: Record<+ AutoresearchIterationStatusEnumApi,+ { type: 'success' | 'default' | 'danger'; label: string }+> = {+ kept: { type: 'success', label: 'Kept' },+ discarded: { type: 'default', label: 'Discarded' },+ crashed: { type: 'danger', label: 'Crashed' },+}++/** Render the agent's model_spec (class + hyperparameters) compactly. random_state is noise — drop it. */+function formatModelSpec(spec: unknown): { className: string; params: string } | null {+ if (!spec || typeof spec !== 'object') {+ return null+ }+ const { model_class, model_params } = spec as { model_class?: string; model_params?: Record<string, unknown> }+ const className = (model_class ?? '').split('.').pop() ?? ''+ const params = model_params+ ? Object.entries(model_params)+ .filter(([key]) => key !== 'random_state')+ .map(([key, value]) => `${key}=${value}`)+ .join(', ')+ : ''+ return className || params ? { className, params } : null+}++/** The per-iteration breakdown for one training run: what the agent tried each step and whether it stuck. */+export function IterationTrail({ iterations }: { iterations: readonly IterationTrailApi[] }): JSX.Element {+ if (iterations.length === 0) {+ return <div className="text-muted text-sm">No iteration details were recorded for this run.</div>+ }+ const bestHoldout = Math.max(...iterations.map((it) => it.holdout_score ?? -Infinity))+ return (+ <div className="space-y-2">+ {iterations.map((it) => {+ const spec = formatModelSpec(it.model_spec)+ const tag = ITERATION_STATUS[it.status]+ const isBest = it.holdout_score != null && it.holdout_score === bestHoldout+ return (+ <div key={it.iteration_number} className="border rounded p-2">+ <div className="flex items-center justify-between gap-2 flex-wrap">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold">Iteration {it.iteration_number}</span>+ <LemonTag type={tag.type} size="small">+ {tag.label}+ </LemonTag>+ {isBest && (+ <LemonTag type="completion" size="small">+ Best+ </LemonTag>+ )}+ </div>+ <div className="text-xs text-muted flex items-center gap-3">+ <span>+ Holdout AUC{' '}+ <span className="font-semibold text-default">+ {it.holdout_score != null ? it.holdout_score.toFixed(4) : '—'}+ </span>+ </span>+ {it.train_score != null && <span>Train {it.train_score.toFixed(4)}</span>}+ </div>+ </div>+ {spec && (+ <div className="text-xs text-muted font-mono mt-1">+ {spec.className}+ {spec.params && ` · ${spec.params}`}+ </div>+ )}+ {it.agent_description && (+ <div className="text-sm text-default mt-1">{it.agent_description}</div>+ )}+ </div>+ )+ })}+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/MetricSparkline.tsx b/products/autoresearch/frontend/pipeline/MetricSparkline.tsxnew file mode 100644index 000000000000..1dcab3f5a7e0--- /dev/null+++ b/products/autoresearch/frontend/pipeline/MetricSparkline.tsx@@ -0,0 +1,37 @@+/** Tiny inline sparkline of a metric over prediction dates. No chart deps. */+export function MetricSparkline({+ points,+ color = 'var(--success)',+ floor,+ ceil,+}: {+ points: { date: string; value: number }[]+ color?: string+ floor?: number+ ceil?: number+}): JSX.Element | null {+ if (points.length < 2) {+ return null+ }+ const width = 280+ const height = 56+ const pad = 4+ const values = points.map((p) => p.value)+ const min = Math.min(...values, ...(floor != null ? [floor] : []))+ const max = Math.max(...values, ...(ceil != null ? [ceil] : []))+ const span = max - min || 1+ const stepX = (width - pad * 2) / (points.length - 1)+ const coords = points.map((p, i) => {+ const x = pad + i * stepX+ const y = pad + (1 - (p.value - min) / span) * (height - pad * 2)+ return [x, y] as const+ })+ const line = coords.map(([x, y]) => `${x.toFixed(1)},${y.toFixed(1)}`).join(' ')+ const last = coords[coords.length - 1]+ return (+ <svg width={width} height={height} className="overflow-visible">+ <polyline points={line} fill="none" stroke={color} strokeWidth={2} />+ <circle cx={last[0]} cy={last[1]} r={3} fill={color} />+ </svg>+ )+}diff --git a/products/autoresearch/frontend/pipeline/MetricTrendCard.tsx b/products/autoresearch/frontend/pipeline/MetricTrendCard.tsxnew file mode 100644index 000000000000..d2ada26b9df1--- /dev/null+++ b/products/autoresearch/frontend/pipeline/MetricTrendCard.tsx@@ -0,0 +1,33 @@+import { dayjs } from 'lib/dayjs'++import { MetricSparkline } from './MetricSparkline'++/** A labelled sparkline card showing one realized metric's trend over prediction dates. */+export function MetricTrendCard({+ title,+ points,+ color,+ floor,+ ceil,+}: {+ title: string+ points: { date: string; value: number }[]+ color?: string+ floor?: number+ ceil?: number+}): JSX.Element | null {+ if (points.length < 2) {+ return null+ }+ const latest = points[points.length - 1]+ return (+ <div className="border rounded p-3 space-y-1 inline-block">+ <div className="text-xs font-semibold text-muted uppercase tracking-wide">{title}</div>+ <div className="text-lg font-bold">{latest.value.toFixed(3)}</div>+ <MetricSparkline points={points} color={color} floor={floor} ceil={ceil} />+ <div className="text-xs text-muted">+ {dayjs(points[0].date).format('MMM D')} to {dayjs(latest.date).format('MMM D')}+ </div>+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx b/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsxnew file mode 100644index 000000000000..2441968653e2--- /dev/null+++ b/products/autoresearch/frontend/pipeline/OnlinePerformanceTab.tsx@@ -0,0 +1,117 @@+import { useActions, useValues } from 'kea'++import { IconGraph } from '@posthog/icons'+import { LemonBanner, LemonTable, LemonTag, Spinner } from '@posthog/lemon-ui'++import { OnlinePerformanceRow, autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { EmptyTab } from './EmptyTab'+import { MetricTrendCard } from './MetricTrendCard'++const MODEL_ROLE: Record<string, { type: 'success' | 'default' | 'highlight'; label: string }> = {+ champion: { type: 'success', label: 'Champion' },+ challenger: { type: 'highlight', label: 'Challenger' },+ archived: { type: 'default', label: 'Archived' },+}++function fmt(value: number | null, decimals = 3): string {+ return value != null ? value.toFixed(decimals) : '—'+}++export function OnlinePerformanceTab(): JSX.Element {+ const { onlinePerformanceRows, runsLoading, runsError } = useValues(autoresearchPipelineLogic)+ const { loadRuns } = useActions(autoresearchPipelineLogic)++ if (runsLoading) {+ return <Spinner />+ }++ if (runsError) {+ return (+ <LemonBanner+ type="error"+ action={{ children: 'Retry', onClick: () => loadRuns(), 'data-attr': 'autoresearch-model-runs-retry' }}+ >+ Couldn't load this model's scoring runs. Try again, and if it keeps happening contact support.+ </LemonBanner>+ )+ }++ if (onlinePerformanceRows.length === 0) {+ return (+ <EmptyTab icon={<IconGraph />} title="No realized performance yet">+ Realized metrics appear once prediction horizons elapse. For each prediction date, PostHog joins your{' '}+ <code>autoresearch_prediction</code> events to actual outcomes and computes AUC, Brier score, and lift.+ Trigger evaluation with the <code>autoresearch-validate-online</code> MCP tool or the{' '}+ <code>autoresearch_validate_online</code> management command.+ </EmptyTab>+ )+ }++ // Champion metric trends over time, oldest → newest, for the sparklines.+ const championRows = onlinePerformanceRows+ .filter((r) => r.emitted_role === 'champion')+ .sort((a, b) => a.prediction_date.localeCompare(b.prediction_date))+ const trend = (pick: (r: OnlinePerformanceRow) => number | null): { date: string; value: number }[] =>+ championRows.filter((r) => pick(r) != null).map((r) => ({ date: r.prediction_date, value: pick(r) as number }))+ const aucTrend = trend((r) => r.realized_auc)+ const brierTrend = trend((r) => r.brier_score)+ const eceTrend = trend((r) => r.calibration_error)++ return (+ <div className="space-y-4">+ <p className="text-sm text-muted">+ Realized performance measured after each prediction horizon elapses. AUC and lift here reflect actual+ user outcomes rather than holdout estimates.+ </p>+ <div className="flex flex-wrap gap-3">+ <MetricTrendCard+ title="Champion realized AUC"+ points={aucTrend}+ color="var(--success)"+ floor={0.5}+ ceil={1}+ />+ <MetricTrendCard title="Champion Brier score" points={brierTrend} color="var(--warning)" floor={0} />+ <MetricTrendCard+ title="Champion calibration error (ECE)"+ points={eceTrend}+ color="var(--warning)"+ floor={0}+ />+ </div>+ <LemonTable+ dataSource={onlinePerformanceRows}+ rowKey={(row) => `${row.run_id}-${row.model_id}`}+ columns={[+ {+ title: 'Prediction date',+ render: (_, row) => <span className="font-mono">{row.prediction_date}</span>,+ },+ {+ title: 'Model',+ tooltip: 'The role the model held when it made these predictions.',+ render: (_, row) => (+ <LemonTag type={MODEL_ROLE[row.emitted_role]?.type ?? 'default'}>+ {MODEL_ROLE[row.emitted_role]?.label ?? row.emitted_role}+ </LemonTag>+ ),+ },+ { title: 'Users scored', render: (_, row) => row.n_scored.toLocaleString() },+ {+ title: 'Realized AUC',+ render: (_, row) => <span className="font-semibold">{fmt(row.realized_auc)}</span>,+ },+ { title: 'Brier score', render: (_, row) => fmt(row.brier_score) },+ { title: 'Calibration error', render: (_, row) => fmt(row.calibration_error) },+ { title: 'Lift at 10%', render: (_, row) => `${fmt(row.lift_at_10, 2)}×` },+ { title: 'Lift at 20%', render: (_, row) => `${fmt(row.lift_at_20, 2)}×` },+ ]}+ />+ <p className="text-xs text-muted">+ Realized AUC: higher is better. Brier score and calibration error (ECE): lower is better. ECE measures+ how far predicted probabilities drift from observed rates. Lift at k%: ratio of positives in the top k%+ vs a random sample, so 2× means twice as many conversions as random.+ </p>+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/OverviewTab.tsx b/products/autoresearch/frontend/pipeline/OverviewTab.tsxnew file mode 100644index 000000000000..be42e76c9fe2--- /dev/null+++ b/products/autoresearch/frontend/pipeline/OverviewTab.tsx@@ -0,0 +1,120 @@+import { useValues } from 'kea'++import { LemonSkeleton, LemonTag, Tooltip } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { AutoresearchModelRoleEnumApi, AutoresearchPipelineApi } from '../generated/api.schemas'+import { PipelineStatusTag } from '../PipelineStatusTag'+import { FeatureImportanceChart } from './FeatureImportanceChart'++export function OverviewTab(): JSX.Element {+ const { pipeline, models } = useValues(autoresearchPipelineLogic)+ if (!pipeline) {+ return <LemonSkeleton className="h-40" />+ }+ const champion = models.find((m) => m.role === AutoresearchModelRoleEnumApi.Champion)+ return (+ <div className="space-y-4">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold text-muted">Status</span>+ <PipelineStatusTag status={pipeline.status} />+ </div>+ <div className="grid grid-cols-2 gap-4 md:grid-cols-4">+ <MetricCard label="Target event" value={pipeline.target_event} />+ <MetricCard label="Prediction horizon" value={`${pipeline.horizon_days ?? '—'}d`} />+ <MetricCard label="Training lookback" value={`${pipeline.training_lookback_days ?? '—'}d`} />+ <MetricCard+ label="Budget remaining"+ value={`${pipeline.iteration_budget_remaining} / ${pipeline.iteration_budget ?? '—'}`}+ />+ </div>+ {champion && (+ <div className="border rounded p-4 space-y-4">+ <div className="flex items-center gap-2">+ <span className="text-sm font-semibold text-muted">Champion model</span>+ {champion.is_preliminary && (+ <Tooltip title="Promoted on holdout AUC alone. Realized metrics confirm it once prediction horizons elapse.">+ <LemonTag type="warning">Preliminary</LemonTag>+ </Tooltip>+ )}+ </div>+ <div className="grid grid-cols-2 gap-4 md:grid-cols-3">+ <MetricCard+ label="Holdout AUC"+ value={champion.holdout_score?.toFixed(3) ?? '—'}+ tooltip="Offline AUC of the champion model, measured on held-out training data. Higher is better."+ />+ <MetricCard+ label="Realized AUC"+ value={champion.realized_score?.toFixed(3) ?? '—'}+ tooltip="AUC of the champion model measured against actual outcomes once predictions matured. Higher is better."+ />+ <MetricCard+ label="Calibration error"+ value={champion.calibration_error?.toFixed(3) ?? '—'}+ tooltip="Expected calibration error (ECE): how far predicted probabilities drift from observed rates. Lower is better."+ />+ </div>+ <FeatureImportanceChart explanation={champion.model_explanation} />+ {champion.agent_description && (+ <div className="text-sm text-muted italic">"{champion.agent_description}"</div>+ )}+ </div>+ )}+ <div className="border rounded p-4">+ <DetailRow label="Output person property">+ <code>{pipeline.output_person_property ?? '—'}</code>+ </DetailRow>+ <DetailRow label="Training population">+ <span className="font-mono text-xs">{populationSummary(pipeline.training_population)}</span>+ </DetailRow>+ <DetailRow label="Inference population">+ <span className="font-mono text-xs">{populationSummary(pipeline.inference_population)}</span>+ </DetailRow>+ <DetailRow label="Last scored">+ {pipeline.last_scored_at ? dayjs(pipeline.last_scored_at).fromNow() : 'Never'}+ </DetailRow>+ <DetailRow label="Created">+ {dayjs(pipeline.created_at).format('MMM D, YYYY')}+ {pipeline.created_by?.first_name ? ` by ${pipeline.created_by.first_name}` : ''}+ </DetailRow>+ </div>+ <p className="text-sm text-muted">+ Editing the target, populations, and budget in the UI is coming soon. For now, use the{' '}+ <code>autoresearch</code> API or MCP tools, or recreate the model.+ </p>+ </div>+ )+}++function DetailRow({ label, children }: { label: string; children: React.ReactNode }): JSX.Element {+ return (+ <div className="flex justify-between items-start gap-4 py-2 border-b last:border-0">+ <div className="text-sm font-semibold text-muted">{label}</div>+ <div className="text-sm text-right">{children}</div>+ </div>+ )+}++function populationSummary(population: AutoresearchPipelineApi['training_population']): string {+ if (!population || typeof population !== 'object' || Object.keys(population).length === 0) {+ return 'All users'+ }+ return JSON.stringify(population)+}++function MetricCard({ label, value, tooltip }: { label: string; value: string; tooltip?: string }): JSX.Element {+ const labelElement = (+ <div className={`text-xs font-semibold text-muted uppercase tracking-wide${tooltip ? ' cursor-help' : ''}`}>+ {label}+ </div>+ )+ return (+ <div className="border rounded p-3 space-y-1">+ {tooltip ? <Tooltip title={tooltip}>{labelElement}</Tooltip> : labelElement}+ <div className="text-lg font-bold truncate">{value}</div>+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/PipelineActions.tsx b/products/autoresearch/frontend/pipeline/PipelineActions.tsxnew file mode 100644index 000000000000..93d7b5720ccb--- /dev/null+++ b/products/autoresearch/frontend/pipeline/PipelineActions.tsx@@ -0,0 +1,41 @@+import { useActions, useValues } from 'kea'++import { IconPause, IconPlay } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'++export function PipelineActions(): JSX.Element | null {+ const { pipeline, pipelineLoading } = useValues(autoresearchPipelineLogic)+ const { pausePipeline, resumePipeline } = useActions(autoresearchPipelineLogic)+ if (!pipeline) {+ return null+ }+ return (+ <>+ {pipeline.status === 'paused' ? (+ <LemonButton+ type="secondary"+ icon={<IconPlay />}+ size="small"+ onClick={() => resumePipeline()}+ data-attr="autoresearch-model-resume"+ loading={pipelineLoading}+ >+ Resume+ </LemonButton>+ ) : pipeline.status === 'running' ? (+ <LemonButton+ type="secondary"+ icon={<IconPause />}+ size="small"+ onClick={() => pausePipeline()}+ data-attr="autoresearch-model-pause"+ loading={pipelineLoading}+ >+ Pause+ </LemonButton>+ ) : null}+ </>+ )+}diff --git a/products/autoresearch/frontend/pipeline/PredictionsTab.tsx b/products/autoresearch/frontend/pipeline/PredictionsTab.tsxnew file mode 100644index 000000000000..6224301641c9--- /dev/null+++ b/products/autoresearch/frontend/pipeline/PredictionsTab.tsx@@ -0,0 +1,107 @@+import { useValues } from 'kea'++import { IconGraph } from '@posthog/icons'+import { LemonCollapse, LemonSkeleton } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { DailyVolumeChart } from '../DailyVolumeChart'+import { ProbabilityHistogram } from '../ProbabilityHistogram'+import { EmptyTab } from './EmptyTab'+import { ProbabilityUsersTable } from './ProbabilityUsersTable'+import { ScoreNowButton } from './ScoreNowButton'++function DailyVolumePanel(): JSX.Element {+ const { dailyVolume, dailyVolumeError } = useValues(autoresearchPipelineLogic)++ if (dailyVolumeError) {+ return (+ <p className="text-sm text-muted mb-0">Couldn't load the scoring volume. Refresh the page to try again.</p>+ )+ }+ if (dailyVolume == null) {+ return <LemonSkeleton className="h-44" />+ }+ if (dailyVolume.length === 0) {+ return (+ <p className="text-sm text-muted mb-0">No prediction events found. Score now to emit fresh predictions.</p>+ )+ }+ return <DailyVolumeChart points={dailyVolume} />+}++function ProbabilityDistributionPanel(): JSX.Element {+ const { probabilityHistogram, probabilityDistributionError } = useValues(autoresearchPipelineLogic)++ if (probabilityDistributionError) {+ return (+ <p className="text-sm text-muted mb-0">+ Couldn't load the probability distribution. Refresh the page to try again.+ </p>+ )+ }+ if (probabilityHistogram == null) {+ return <LemonSkeleton className="h-52" />+ }+ if (probabilityHistogram.every((bucket) => bucket.users === 0)) {+ return (+ <p className="text-sm text-muted mb-0">+ No prediction events found for the latest scoring run. Score now to emit fresh predictions.+ </p>+ )+ }+ return <ProbabilityHistogram buckets={probabilityHistogram} />+}++export function PredictionsTab(): JSX.Element {+ const { pipeline } = useValues(autoresearchPipelineLogic)+ if (!pipeline) {+ return <LemonSkeleton className="h-40" />+ }++ if (!pipeline.last_scored_at) {+ return (+ <EmptyTab icon={<IconGraph />} title="No predictions yet" cta={<ScoreNowButton />}>+ Once the champion scores your inference population, each user's predicted probability lands on the{' '}+ <code>{pipeline.output_person_property}</code> person property and an{' '}+ <code>autoresearch_prediction</code> event is emitted. Score now to populate this tab.+ </EmptyTab>+ )+ }++ return (+ <div className="space-y-6">+ <p className="text-sm text-muted">+ Each scoring run writes the champion's predicted probability to the{' '}+ <code>{pipeline.output_person_property}</code> person property and emits an{' '}+ <code>autoresearch_prediction</code> event. These views read straight from those events.+ </p>++ <LemonCollapse+ multiple+ defaultActiveKeys={['distribution', 'highest']}+ panels={[+ {+ key: 'distribution',+ header: 'Probability distribution (latest scoring run)',+ content: <ProbabilityDistributionPanel />,+ },+ {+ key: 'highest',+ header: 'Highest-probability users (latest scoring run)',+ content: <ProbabilityUsersTable pipelineId={pipeline.id} direction="DESC" />,+ },+ {+ key: 'lowest',+ header: 'Lowest-probability users (latest scoring run)',+ content: <ProbabilityUsersTable pipelineId={pipeline.id} direction="ASC" />,+ },+ {+ key: 'volume',+ header: 'Daily scoring volume',+ content: <DailyVolumePanel />,+ },+ ]}+ />+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsx b/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsxnew file mode 100644index 000000000000..997be317b936--- /dev/null+++ b/products/autoresearch/frontend/pipeline/ProbabilityUsersTable.tsx@@ -0,0 +1,86 @@+import { Link } from '@posthog/lemon-ui'++import { urls } from 'scenes/urls'++import { Query } from '~/queries/Query/Query'+import { NodeKind } from '~/queries/schema/schema-general'++import { LATEST_BATCH_LOOKBACK_DAYS } from '../autoresearchPipelineLogic'++/** Links to the person's page. The value is a (person UUID, display name) tuple; the display name falls back to the UUID. */+function PersonCell({ value }: { value: unknown }): JSX.Element {+ const [id, name] = Array.isArray(value) ? value : [value, null]+ const personId = id == null ? '' : String(id)+ if (!personId) {+ return <>—</>+ }+ const display = typeof name === 'string' && name ? name : personId+ return <Link to={urls.personByUUID(personId)}>{display}</Link>+}++function PercentCell({ value }: { value: unknown }): JSX.Element {+ return value == null ? <>—</> : <>{String(value)}%</>+}++/** Top/bottom-N users by predicted probability for a pipeline, grouped by person. */+export function ProbabilityUsersTable({+ pipelineId,+ direction,+}: {+ pipelineId: string+ direction: 'DESC' | 'ASC'+}): JSX.Element {+ return (+ <Query+ readOnly+ context={{+ columns: {+ person: { title: 'Person', render: PersonCell },+ probability: { title: 'Probability', render: PercentCell },+ last_scored: { title: 'Last scored' },+ },+ }}+ query={{+ kind: NodeKind.DataTableNode,+ source: {+ kind: NodeKind.HogQLQuery,+ query: `+ -- A scoring run stamps its whole batch with one timestamp, so the latest batch is its exact timestamp.+ WITH latest AS (+ SELECT max(timestamp) AS t+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = {pipeline_id}+ AND timestamp >= now() - INTERVAL ${LATEST_BATCH_LOOKBACK_DAYS} DAY+ ),+ scored AS (+ SELECT+ coalesce(nullIf(properties.$autoresearch_person_id, ''), distinct_id) AS person_id,+ round(100 * argMax(toFloat(properties.$autoresearch_p_y), timestamp), 1) AS probability,+ max(timestamp) AS last_scored+ FROM events+ WHERE event = 'autoresearch_prediction'+ AND properties.$autoresearch_pipeline_id = {pipeline_id}+ AND timestamp = (SELECT t FROM latest)+ GROUP BY person_id+ )+ -- LEFT JOIN persons directly on the person UUID: the implicit person join goes via+ -- distinct_id, which drops scored people whose prediction events aren't person-mapped.+ SELECT+ tuple(s.person_id, coalesce(+ nullIf(toString(p.properties.email), ''),+ nullIf(toString(p.properties.name), '')+ )) AS person,+ s.probability AS probability,+ s.last_scored AS last_scored+ FROM scored s+ LEFT JOIN persons p ON toString(p.id) = s.person_id+ ORDER BY probability ${direction}+ LIMIT 50+ `,+ values: { pipeline_id: pipelineId },+ },+ }}+ />+ )+}diff --git a/products/autoresearch/frontend/pipeline/ScoreNowButton.tsx b/products/autoresearch/frontend/pipeline/ScoreNowButton.tsxnew file mode 100644index 000000000000..2dd98818d9ed--- /dev/null+++ b/products/autoresearch/frontend/pipeline/ScoreNowButton.tsx@@ -0,0 +1,36 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import { LemonButton } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { AutoresearchModelRoleEnumApi } from '../generated/api.schemas'++/** Score-now action, gated on a champion existing. Reused in the title bar and empty states. */+export function ScoreNowButton(): JSX.Element | null {+ const { pipeline, models, scoreResultLoading } = useValues(autoresearchPipelineLogic)+ const { scoreNow } = useActions(autoresearchPipelineLogic)+ const hasChampion = models.some((m) => m.role === AutoresearchModelRoleEnumApi.Champion)+ if (!pipeline || pipeline.status === 'archived') {+ return null+ }+ return (+ <LemonButton+ type="secondary"+ size="small"+ icon={<IconRefresh />}+ onClick={() => scoreNow()}+ data-attr="autoresearch-model-score"+ loading={scoreResultLoading}+ disabledReason={+ pipeline.status === 'paused'+ ? 'Resume the model to score it'+ : hasChampion+ ? undefined+ : 'Train a champion model first'+ }+ >+ Score now+ </LemonButton>+ )+}diff --git a/products/autoresearch/frontend/pipeline/SuggestionForm.tsx b/products/autoresearch/frontend/pipeline/SuggestionForm.tsxnew file mode 100644index 000000000000..33fc90105dc0--- /dev/null+++ b/products/autoresearch/frontend/pipeline/SuggestionForm.tsx@@ -0,0 +1,49 @@+import { useActions, useValues } from 'kea'++import { LemonButton, LemonSelect, LemonTextArea } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { CreateSuggestionPriorityEnumApi } from '../generated/api.schemas'++export function SuggestionForm(): JSX.Element {+ const { suggestionDraft, suggestionPriority, suggestionSubmitResultLoading } = useValues(autoresearchPipelineLogic)+ const { setSuggestionDraft, setSuggestionPriority, submitSuggestion } = useActions(autoresearchPipelineLogic)+ return (+ <div className="border rounded p-3 space-y-2">+ <div className="text-sm font-semibold">Steer the agent</div>+ <LemonTextArea+ value={suggestionDraft}+ maxLength={2000}+ onChange={setSuggestionDraft}+ placeholder="e.g. Try a momentum feature: downloads in the last 7 days over the last 30 days."+ minRows={2}+ maxRows={6}+ data-attr="autoresearch-suggestion-input"+ />+ <div className="flex items-center gap-2">+ <LemonSelect+ size="small"+ value={suggestionPriority}+ onChange={(v) => v && setSuggestionPriority(v)}+ options={[+ { value: CreateSuggestionPriorityEnumApi.Consider, label: 'Consider (advisory)' },+ {+ value: CreateSuggestionPriorityEnumApi.TryNext,+ label: 'Try next (before autonomous iterations)',+ },+ ]}+ />+ <LemonButton+ type="primary"+ size="small"+ onClick={() => submitSuggestion()}+ data-attr="autoresearch-model-suggest"+ loading={suggestionSubmitResultLoading}+ disabledReason={!suggestionDraft.trim() ? 'Write a suggestion first' : undefined}+ >+ Send suggestion+ </LemonButton>+ </div>+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/SuggestionsTab.tsx b/products/autoresearch/frontend/pipeline/SuggestionsTab.tsxnew file mode 100644index 000000000000..92a0edaf4127--- /dev/null+++ b/products/autoresearch/frontend/pipeline/SuggestionsTab.tsx@@ -0,0 +1,78 @@+import { useActions, useValues } from 'kea'++import { LemonBanner, LemonTag, Spinner } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import {+ AutoresearchSuggestionApi,+ AutoresearchSuggestionPriorityEnumApi,+ AutoresearchSuggestionStatusEnumApi,+} from '../generated/api.schemas'+import { SuggestionForm } from './SuggestionForm'++const SUGGESTION_STATUS: Record<+ AutoresearchSuggestionStatusEnumApi,+ { type: 'success' | 'default' | 'danger' | 'highlight'; label: string }+> = {+ queued: { type: 'default', label: 'Queued' },+ picked_up: { type: 'highlight', label: 'Picked up' },+ acted_on: { type: 'success', label: 'Acted on' },+ dismissed: { type: 'danger', label: 'Dismissed' },+}++const SUGGESTION_PRIORITY: Record<AutoresearchSuggestionPriorityEnumApi, string> = {+ consider: 'Consider',+ try_next: 'Try next',+}++export function SuggestionsTab(): JSX.Element {+ const { suggestions, suggestionsLoading, suggestionsError } = useValues(autoresearchPipelineLogic)+ const { loadSuggestions } = useActions(autoresearchPipelineLogic)+ return (+ <div className="space-y-4">+ <p className="text-sm text-muted">+ Inject a free-text hypothesis into the training loop. The agent reads queued suggestions at the start of+ each iteration batch and decides whether to act on, apply, or dismiss each one.+ </p>+ <SuggestionForm />+ {suggestionsLoading ? (+ <Spinner />+ ) : suggestionsError ? (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: () => loadSuggestions(),+ 'data-attr': 'autoresearch-model-suggestions-retry',+ }}+ >+ Couldn't load the suggestions. Try again, and if it keeps happening contact support.+ </LemonBanner>+ ) : suggestions.length === 0 ? (+ <div className="text-muted text-sm">No suggestions yet. Send one above to steer the next run.</div>+ ) : (+ <div className="space-y-2">+ {suggestions.map((s: AutoresearchSuggestionApi) => (+ <div key={s.id} className="border rounded p-3 space-y-1">+ <div className="flex items-center gap-2">+ <LemonTag type={SUGGESTION_STATUS[s.status].type}>+ {SUGGESTION_STATUS[s.status].label}+ </LemonTag>+ <span className="text-xs text-muted">+ {s.priority ? SUGGESTION_PRIORITY[s.priority] : ''}+ </span>+ <span className="text-xs text-muted">{dayjs(s.created_at).fromNow()}</span>+ </div>+ <div className="text-sm">{s.prompt}</div>+ {s.agent_response && (+ <div className="text-sm text-muted italic">Agent: {s.agent_response}</div>+ )}+ </div>+ ))}+ </div>+ )}+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsxnew file mode 100644index 000000000000..cbab732635c3--- /dev/null+++ b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx@@ -0,0 +1,154 @@+import { useActions, useValues } from 'kea'++import { IconChevronRight, IconExternal } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonCollapse, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'++import { dayjs } from 'lib/dayjs'+import { LemonMarkdownWithMermaid } from 'lib/lemon-ui/LemonMarkdown/LemonMarkdownWithMermaid'++import { autoresearchPipelineLogic, trainingRunProgress } from '../autoresearchPipelineLogic'+import { type AutoresearchRunApi, AutoresearchTrainingRunApi } from '../generated/api.schemas'+import { IterationTrail } from './IterationTrail'++// Derived from the field rather than the standalone enum: this pending/running/completed/failed+// set is shared with another product, so the generated enum does not carry an autoresearch name.+type AutoresearchRunStatus = NonNullable<AutoresearchRunApi['status']>++const RUN_STATUS: Record<+ AutoresearchRunStatus,+ { type: 'success' | 'default' | 'danger' | 'highlight'; label: string }+> = {+ pending: { type: 'default', label: 'Pending' },+ running: { type: 'highlight', label: 'Running' },+ completed: { type: 'success', label: 'Completed' },+ failed: { type: 'danger', label: 'Failed' },+}++/** The agent-authored report.md for a run, rendered as markdown (with mermaid charts). */+function RunReport({ runId }: { runId: string }): JSX.Element | null {+ const { reportByRun, reportByRunLoading } = useValues(autoresearchPipelineLogic)+ const report = reportByRun[runId]+ if (report === undefined) {+ return reportByRunLoading ? <Spinner /> : null+ }+ if (!report) {+ // Loaded, but the agent uploaded no report.md — show nothing; iterations/bundle still render.+ return null+ }+ return (+ <LemonCollapse+ panels={[+ {+ key: 'report',+ header: 'Report',+ // The agent writes this report, so a remote image in it would make the viewer's browser call that host.+ content: <LemonMarkdownWithMermaid disableImages="all">{report}</LemonMarkdownWithMermaid>,+ },+ ]}+ />+ )+}++export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JSX.Element {+ const { expandedRunId, artifactsByRun, artifactsByRunLoading } = useValues(autoresearchPipelineLogic)+ const { toggleRunArtifacts, viewArtifact } = useActions(autoresearchPipelineLogic)+ const isExpanded = expandedRunId === run.id+ const paths = artifactsByRun[run.id]+ const progress = trainingRunProgress(run)+ const startedAt = run.started_at ?? run.created_at+ const duration =+ run.started_at && run.completed_at ? dayjs(run.completed_at).from(dayjs(run.started_at), true) : null+ const runStatus = RUN_STATUS[run.status]+ const progressSummary =+ run.status === 'failed' && progress.iterationCount === 0+ ? 'Failed before any iterations'+ : `${progress.iterationCount} iterations · ${+ progress.bestHoldoutScore != null+ ? `best AUC ${progress.bestHoldoutScore.toFixed(3)}`+ : 'no score yet'+ }`++ return (+ <div className="border rounded">+ <div className="p-3 flex justify-between items-center">+ <div className="flex items-center gap-2">+ <LemonButton+ size="small"+ icon={<IconChevronRight className={`transition-transform ${isExpanded ? 'rotate-90' : ''}`} />}+ onClick={() => toggleRunArtifacts(run.id)}+ tooltip={isExpanded ? 'Hide details' : 'Show iterations & bundle'}+ />+ <div className="space-y-0.5">+ <div className="text-sm font-semibold flex items-center gap-1">+ <Tooltip title={dayjs(startedAt).format('MMM D, YYYY HH:mm')}>+ <span>+ Training run · <span translate="no">{dayjs(startedAt).fromNow()}</span>+ </span>+ </Tooltip>+ {run.task_url && (+ <Link+ to={run.task_url}+ target="_blank"+ className="text-muted hover:text-primary"+ title="Open sandbox task"+ >+ <IconExternal className="text-sm" />+ </Link>+ )}+ {run.status === 'running' && <Spinner className="ml-2 inline" />}+ </div>+ <div className="text-xs text-muted">+ <span className="font-mono">{run.id.slice(0, 8)}</span> · {progressSummary}+ {duration ? ` · took ${duration}` : ''}+ </div>+ </div>+ </div>+ <LemonTag type={runStatus.type}>{runStatus.label}</LemonTag>+ </div>+ {isExpanded && (+ <div className="border-t p-3 space-y-3">+ {run.status === 'failed' && run.error && <LemonBanner type="error">{run.error}</LemonBanner>}+ <RunReport runId={run.id} />+ <div className="space-y-2">+ <div className="text-xs font-semibold text-muted uppercase tracking-wide">Iterations</div>+ <IterationTrail iterations={run.iterations} />+ </div>+ {run.summary && (+ <div className="space-y-1">+ <div className="text-xs font-semibold text-muted uppercase tracking-wide">+ What the agent learned+ </div>+ {run.summary.distillation && (+ <div className="text-sm text-default italic">"{run.summary.distillation}"</div>+ )}+ {run.summary.recommended_next && (+ <div className="text-xs text-muted">Next: {run.summary.recommended_next}</div>+ )}+ </div>+ )}+ <div className="space-y-2">+ <div className="text-xs font-semibold text-muted uppercase tracking-wide">Artifact bundle</div>+ {paths === undefined && artifactsByRunLoading ? (+ <Spinner />+ ) : paths && paths.length > 0 ? (+ <div className="flex flex-wrap gap-2">+ {paths.map((path) => (+ <LemonButton+ key={path}+ type="secondary"+ size="small"+ onClick={() => viewArtifact({ runId: run.id, path })}+ >+ {path}+ </LemonButton>+ ))}+ </div>+ ) : (+ <div className="text-muted text-sm">No artifacts uploaded for this run.</div>+ )}+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/products/autoresearch/frontend/pipeline/TrainingTab.tsx b/products/autoresearch/frontend/pipeline/TrainingTab.tsxnew file mode 100644index 000000000000..34347c0b3918--- /dev/null+++ b/products/autoresearch/frontend/pipeline/TrainingTab.tsx@@ -0,0 +1,66 @@+import { useActions, useValues } from 'kea'++import { IconRefresh } from '@posthog/icons'+import { LemonBanner, LemonButton, Spinner } from '@posthog/lemon-ui'++import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'+import { AutoresearchTrainingRunApi } from '../generated/api.schemas'+import { ArtifactViewerModal } from './ArtifactViewerModal'+import { EmptyTab } from './EmptyTab'+import { TrainingRunRow } from './TrainingRunRow'++export function TrainingTab(): JSX.Element {+ const { pipeline, trainingRuns, trainingRunsLoading, trainingRunsError, startTrainingResultLoading } =+ useValues(autoresearchPipelineLogic)+ const { startTraining, loadTrainingRuns } = useActions(autoresearchPipelineLogic)+ const hasLiveRun = trainingRuns.some((run) => run.status === 'pending' || run.status === 'running')+ const trainDisabledReason = startTrainingResultLoading+ ? 'Starting…'+ : pipeline?.status === 'paused'+ ? 'Resume the model to train it'+ : hasLiveRun+ ? 'A training run is already in progress'+ : undefined++ return (+ <div className="space-y-4">+ <div className="flex items-center gap-2">+ <LemonButton+ type="primary"+ onClick={() => void startTraining()}+ data-attr="autoresearch-model-train"+ loading={startTrainingResultLoading}+ disabledReason={trainDisabledReason}+ >+ Run training+ </LemonButton>+ </div>+ {trainingRunsLoading ? (+ <Spinner />+ ) : trainingRunsError ? (+ <LemonBanner+ type="error"+ action={{+ children: 'Retry',+ onClick: () => loadTrainingRuns(),+ 'data-attr': 'autoresearch-model-training-runs-retry',+ }}+ >+ Couldn't load this model's training runs. Try again, and if it keeps happening contact support.+ </LemonBanner>+ ) : trainingRuns.length === 0 ? (+ <EmptyTab icon={<IconRefresh />} title="No training runs yet">+ Run training to kick off the autoresearch loop. The agent iterates on feature recipes, keeping only+ the changes that improve holdout AUC.+ </EmptyTab>+ ) : (+ <div className="space-y-2">+ {trainingRuns.map((run: AutoresearchTrainingRunApi) => (+ <TrainingRunRow key={run.id} run={run} />+ ))}+ </div>+ )}+ <ArtifactViewerModal />+ </div>+ )+}diff --git a/products/autoresearch/manifest.tsx b/products/autoresearch/manifest.tsxindex d953ae18ec6d..2be85b61ecfc 100644--- a/products/autoresearch/manifest.tsx+++ b/products/autoresearch/manifest.tsx@@ -20,10 +20,16 @@ export const manifest: ProductManifest = {import: () => import('./frontend/AutoresearchNewScene'),projectBased: true,},+ AutoresearchPipeline: {+ name: 'Autoresearch model',+ import: () => import('./frontend/AutoresearchPipelineScene'),+ projectBased: true,+ },},routes: {'/autoresearch': ['Autoresearch', 'autoresearch'],'/autoresearch/new': ['AutoresearchNew', 'autoresearchNew'],+ '/autoresearch/:id': ['AutoresearchPipeline', 'autoresearchPipeline'],},urls: {autoresearch: (): string => '/autoresearch',diff --git a/products/autoresearch/mcp/tools.yaml b/products/autoresearch/mcp/tools.yamlindex 8c5d10bbd537..89556b66754e 100644--- a/products/autoresearch/mcp/tools.yaml+++ b/products/autoresearch/mcp/tools.yaml@@ -33,6 +33,7 @@ tools:readOnly: falsedestructive: falseidempotent: false+ enrich_url: '{id}'title: Create a pipelinedescription: >Create a new autoresearch prediction pipeline. Always call autoresearch-validate-create first — this@@ -219,6 +220,7 @@ tools:readOnly: truedestructive: falseidempotent: true+ enrich_url: '{id}'title: Get pipelinedescription: >Get full details for a specific autoresearch pipeline by ID, including population definitions, trainingdiff --git a/services/mcp/src/tools/generated/autoresearch.ts b/services/mcp/src/tools/generated/autoresearch.tsindex 89b4b132513c..c9f189a9494c 100644--- a/services/mcp/src/tools/generated/autoresearch.ts+++ b/services/mcp/src/tools/generated/autoresearch.ts@@ -11,7 +11,10 @@ const AutoresearchCreateSchema = () => {return AutoresearchCreateBody}-const autoresearchCreate = (): ToolBase<ReturnType<typeof AutoresearchCreateSchema>, Schemas.AutoresearchPipeline> => ({+const autoresearchCreate = (): ToolBase<+ ReturnType<typeof AutoresearchCreateSchema>,+ WithPostHogUrl<Schemas.AutoresearchPipeline>+> => ({name: 'autoresearch-create',schema: AutoresearchCreateSchema(),handler: async (context: Context, params: z.infer<ReturnType<typeof AutoresearchCreateSchema>>) => {@@ -61,7 +64,7 @@ const autoresearchCreate = (): ToolBase<ReturnType<typeof AutoresearchCreateSchepath: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/`,body,})- return result+ return await withPostHogUrl(context, result, `/autoresearch/${result.id}`)},})@@ -244,7 +247,7 @@ const AutoresearchRetrieveSchema = () => {const autoresearchRetrieve = (): ToolBase<ReturnType<typeof AutoresearchRetrieveSchema>,- Schemas.AutoresearchPipeline+ WithPostHogUrl<Schemas.AutoresearchPipeline>> => ({name: 'autoresearch-retrieve',schema: AutoresearchRetrieveSchema(),@@ -255,7 +258,7 @@ const autoresearchRetrieve = (): ToolBase<path: `/api/projects/${encodeURIComponent(String(projectId))}/autoresearch/${encodeURIComponent(String(params.id))}/`,})const filtered = omitResponseFields(result, ['created_by']) as typeof result- return filtered+ return await withPostHogUrl(context, filtered, `/autoresearch/${filtered.id}`)},})