Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(autoresearch): chart the agent's search in the agent research tab (#113161)

posthog[bot]44ade7814691
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index e9cdb067ff21..c6775017c710 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6504,6 +6504,14 @@ snapshots:
hash: v1.k794b7964.ec5636bb061b046741a42c6ce3faa30704b2b4203947e956c5d7966bada33fd5.pMIwCFfVjMdfrr_RckXkoewH1hbCy3Veditgtv4hx_k
products-autoresearch-lifecycle-strip--validated-champion--light:
hash: v1.k794b7964.131ecc736b38defef5b8ba34fa9836f1d2d5132e1d109e4b995b9591a5d9255c.759giT71A_8sdMCqx-FasPgdZzZWHgRvaoUmqVtYYKw
+ products-autoresearch-model-detail-scene--agent-research-narrow--narrow--dark:
+ hash: v1.k794b7964.052f6d0dba654432d5f12d65bc0f91bc3e2de64334dac07e62d6cf730f154820.7cPMLn00EY67HPH6ikgGBUlULYPQSAMVKLyE_cR3uTs
+ products-autoresearch-model-detail-scene--agent-research-narrow--narrow--light:
+ hash: v1.k794b7964.5aac6ed053655f482abe449b7a10cfe15b86bc95dcd448258131d9025c6ec9d0.uggKZoeOrAifOn_YNcltodKu3SDvLDj2svOMa0BlMts
+ products-autoresearch-model-detail-scene--agent-research-wide--wide--dark:
+ hash: v1.k794b7964.5861f881393ab1dba59cb0330fd1704b278a76ac0748086f446d650e1ee88f80.GWFbkjd1OxgM33wYBC4Gncb_3jIWx1RIU5FGZ7ABzKU
+ products-autoresearch-model-detail-scene--agent-research-wide--wide--light:
+ hash: v1.k794b7964.61a18ed53831b16b23b3f5c5bf5db2311a2a67c3237d339a9559de7dd488432c.jsOveKxB0FdFA8m-z9oDOUxV_z4mbAXK9Lra6HxBrr0
products-autoresearch-model-detail-scene--narrow--narrow--dark:
hash: v1.k794b7964.a8261167fe190a6da69fd2bc07cd0b45b9d69ddb6c502e6a76ab6545c9e043d6.3ScvmJEDOvl0AC3sWgI9d6tawFXTfq2B8p-pvUn2htw
products-autoresearch-model-detail-scene--narrow--narrow--light:
@@ -6521,21 +6529,21 @@ snapshots:
products-autoresearch-probability-histogram--single-bucket--light:
hash: v1.k794b7964.7087a0c145f21f4ad346356f61768cfe3c158fcaf680e2bfd46135bcb39985a5.DRfvEC1xadIFDKaZCGZtNj1jj7vYSW_jF1U97K7QrBI
products-autoresearch-training-run-row--compared-with-champion-narrow--dark:
- hash: v1.k794b7964.9830e6048bce43800723ca6bee037bb1a91ec500aec423893be9b3c55659df14.fmdX0m_Qvg0f3TJFplwoR0u44C8RtyPj1NgmVoqP9Fk
+ hash: v1.k794b7964.0eebd4644aca0bdaad27698de96e1af7454b4485048ed1caf5c6ba2534272a9d.5PuFFiQauCsoWf9oYGeO71GHeONCyyqjOnsgQ10yCCI
products-autoresearch-training-run-row--compared-with-champion-narrow--light:
- hash: v1.k794b7964.105ee396b96f519507dd4e49a1731864e80370fe5d92081c6480553cfd1eb594.0eAOak4fZGoUCLn2SknMQ6dhtAJ4rJnjDagKbXMVNIk
+ hash: v1.k794b7964.d30e2e4b79f3b1eaf8be0d8e9dc59172cd8af92a4f469f73b327baddb8671585.rS9RxSedb-zdnGWKns5hcB5mjf-2_WxagtKbGoUMrJA
products-autoresearch-training-run-row--compared-with-champion-wide--dark:
- hash: v1.k794b7964.54401cab59097a4aa36bdd135c4a3207f42cad57e0cb6ae1be20504c7104623e.lvwUB3xG2CnVO2Voq1d0XuSaKxSI0XPhMkGrlsB4dzo
+ hash: v1.k794b7964.a09884d9f8f1ce8732c820d9fe4163206135881c0ee41f1e8ece387abfe1e911.12zsP58eb1jPPxOUie-Pg0bDcG-Xfhv-dLpUSDSsCcU
products-autoresearch-training-run-row--compared-with-champion-wide--light:
- hash: v1.k794b7964.d076be958a4e3ca0f41838084bc83584a4560ed551a67236b784e31d505b226a.kYRHbvr8-lCpBD4Rn-q6lyaFqbclQsJ8Wz4RG6NGdds
+ hash: v1.k794b7964.caad28934086782e2238d4ce64312c34c1b1ae4ff43750afe0da0f593dfd7af0.KtwVBrzOfXtwAddyoaweoemgq3gahhQA5hcqvMT-K5Y
products-autoresearch-training-run-row--run-model-without-importances--dark:
- hash: v1.k794b7964.cecb833bc7bd8ca42db243e0a6cbf6917167529efff3de02d4976129e31c9d15.NzRkSMaMOSdVxHG39_qyUpjM5mfV7z4xD6NJHWKMgnI
+ hash: v1.k794b7964.d0b99336acc896e44e81c463c199e6ca4d809a855ac34a187c8988dc59f881e9.ya4kSU56XHFa7kteijdymLayjBXtUIESVSBZ5B4ZDtg
products-autoresearch-training-run-row--run-model-without-importances--light:
- hash: v1.k794b7964.97de8a577ec7f77873b33b8cf56f7cd13ff7722032a055b0f6cca8f7a788ce7c.5fDSgGcP7hTthZ4U6pihNquI9e5ai8sTN6Dp6zqDDH4
+ hash: v1.k794b7964.1bb932c756681f759a5031f9c9e7f747044d3cefa80d8a14b92c25cbb0fd8828.s8famIWRN8ko6fTPDLQy3OLdKeZqsiQ5kip9DTSmH08
products-autoresearch-training-run-row--run-produced-the-champion--dark:
- hash: v1.k794b7964.a9de84c1f27dab319f1c8144f25dcb2ee86f24e4a8a81e3e4f1af8772691a853.-8abFqmvKqn68PvlPf_7mXyGfyzzVGlhwqMEIRLT1VQ
+ hash: v1.k794b7964.d95774bf57e55a6cb2d2f6d72567bc092333ab1bbc874817d7040e402fc4f553.jTR764Ke1KM2eR2cwVBTTyhKa5BVekhtT2O6UOUaZwQ
products-autoresearch-training-run-row--run-produced-the-champion--light:
- hash: v1.k794b7964.99a7492e480121211d7b1bdcc80551dd1237c844db39f3e125a3419fcea07392.vVadWxwzVkcx_5Rs8NM_JR-rgQ1Mddc8LADMSDGJ5qA
+ hash: v1.k794b7964.ef5ea55d4cef1220e6ee85a4ff4dc063fd2ee3ee2b5307ad6e2a125dc08a4ce5.14G_y4eRw8fBjzaJghsehdZxUy-zcVsBDrV1T5iVCM0
products-business-intelligence-chart-years--partial-years--dark:
hash: v1.k794b7964.2a6374590be64f7a06a222b2c702f194a05289115c618d7ec8864a6b62f85631.wJMlvq8tZxD3TVKI8Lt9pHxK7YwHkdHS2QDRpZaqRJo
products-business-intelligence-chart-years--partial-years--light:
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 7658e2e648ff..58a9ee7e205f 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2626,6 +2626,9 @@ importers:
'@posthog/lemon-ui':
specifier: '*'
version: 0.0.0([email protected]([email protected])([email protected])([email protected])([email protected]([email protected]))([email protected]))([email protected]([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])))([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))([email protected]([email protected]))([email protected])
+ '@posthog/quill-charts':
+ specifier: workspace:*
+ version: link:../../packages/quill/packages/charts
'@types/react':
specifier: 18.3.27
version: 18.3.27
diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.md
index e274ceb2576f..1a5189781d1d 100644
--- a/products/autoresearch/frontend/AGENTS.md
+++ b/products/autoresearch/frontend/AGENTS.md
@@ -18,6 +18,7 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st
| `newModel/` | Create-form parts: template chips, definition sentence, Advanced section, readiness checklist, "What happens next". |
| `autoresearchPipelineLogic.ts` | Detail logic. Also maps the old `?tab=` keys to the four tabs, so saved links still open. |
| `pipelineLifecycle.ts` | The five lifecycle steps (question set to checked against reality) and which one is current. |
+| `agentSearch.ts` | The agent's search across training runs: chart points, best score so far, AUC change per experiment, log groups and the latest agent notes. |
| `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. |
@@ -48,7 +49,7 @@ Follow `frontend/src/AGENTS.md` — it applies to product frontends too.
- TypeScript with explicit return types; Tailwind utilities rather than inline styles.
- Reuse Lemon / quill components instead of hand-rolling tables, badges, or tags.
- Any button that fires a request must guard against double-submission — `loading` / `disabledReason` on `LemonButton`, reset on both success and error paths. The lifecycle actions here (train, score, archive, pause, resume) are all network calls, and several are expensive: firing `train` twice starts two sandbox agent runs and spends the budget twice.
-- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. The detail logic captures `autoresearch model tab changed` (with `tab`) when a person picks a tab; buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
+- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`). The create logic captures `autoresearch model template selected` (with `template_key`), `autoresearch model custom chosen`, `autoresearch model advanced opened`, `autoresearch model created` (with `action`: `start_training` or `save_draft`), and `autoresearch model training started` / `training start failed`. The detail logic captures `autoresearch model tab changed` (with `tab`) when a person picks a tab, `autoresearch model experiment log filter changed` (with `filter`), `autoresearch model search point clicked` (with `run_id`, `iteration_number`, `status`) and `autoresearch model suggestion sent` (with `priority`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
## Copy
diff --git a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
index d214a2de9794..5d530d0b4487 100644
--- a/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
+++ b/products/autoresearch/frontend/AutoresearchPipelineScene.stories.tsx
@@ -49,8 +49,8 @@ const pipeline = {
champion_is_preliminary: false,
champion_realized_auc_trend: [],
people_scored: 48210,
- training_run_count: 2,
- experiment_count: 14,
+ training_run_count: 3,
+ experiment_count: 11,
live_training_run: null,
} as unknown as AutoresearchPipelineApi
@@ -71,7 +71,7 @@ const champion = {
realized_score: 0.81,
calibration_error: 0.04,
metrics: {},
- source_training_run: null,
+ source_training_run: 'training-2',
agent_description: 'Gradient boosting on recent sharing and upload activity.',
is_preliminary: false,
promoted_at: '2026-01-10T00:00:00Z',
@@ -104,16 +104,77 @@ const runs = [
},
] as unknown as AutoresearchRunApi[]
+function iteration(
+ iteration_number: number,
+ status: 'kept' | 'discarded' | 'crashed',
+ holdout_score: number | null,
+ agent_description: string
+): Record<string, unknown> {
+ return {
+ iteration_number,
+ status,
+ holdout_score,
+ train_score: null,
+ agent_description,
+ model_spec: { model_class: 'sklearn.ensemble.HistGradientBoostingClassifier', model_params: { max_depth: 4 } },
+ }
+}
+
const trainingRuns = [
{
- id: 'training-1',
+ id: 'training-3',
+ pipeline: PIPELINE_ID,
+ task_url: null,
+ status: 'failed',
+ iteration_count: 0,
+ best_holdout_score: null,
+ summary: null,
+ iterations: [
+ iteration(0, 'discarded', 0.81, 'Add the day of week of the last share.'),
+ iteration(1, 'crashed', null, 'Join folder metadata. The feature query timed out.'),
+ ],
+ error: 'The sandbox stopped before the run finished.',
+ started_at: '2026-02-20T09:00:00Z',
+ completed_at: '2026-02-20T10:00:00Z',
+ created_at: '2026-02-20T09:00:00Z',
+ },
+ {
+ id: 'training-2',
pipeline: PIPELINE_ID,
task_url: null,
status: 'completed',
- iteration_count: 14,
+ iteration_count: 5,
best_holdout_score: 0.83,
+ summary: {
+ distillation: 'Recent upload counts carry most of the signal. Log scaling them helps.',
+ recommended_next: 'Try a ratio of shares in the last 7 days to the last 30 days.',
+ },
+ iterations: [
+ iteration(0, 'kept', 0.79, 'Start from the current champion.'),
+ iteration(1, 'discarded', 0.78, 'Drop the team size feature.'),
+ iteration(2, 'kept', 0.81, 'Log scale the upload counts.'),
+ iteration(3, 'discarded', 0.8, 'Deeper trees.'),
+ iteration(4, 'kept', 0.83, 'Add uploads in the last 7 days.'),
+ ],
+ error: '',
+ started_at: '2026-01-20T09:00:00Z',
+ completed_at: '2026-01-20T11:00:00Z',
+ created_at: '2026-01-20T09:00:00Z',
+ },
+ {
+ id: 'training-1',
+ pipeline: PIPELINE_ID,
+ task_url: null,
+ status: 'completed',
+ iteration_count: 4,
+ best_holdout_score: 0.79,
summary: null,
- iterations: [],
+ iterations: [
+ iteration(0, 'kept', 0.68, 'Baseline: event counts in the last 30 days.'),
+ iteration(1, 'kept', 0.74, 'Add days since the last share.'),
+ iteration(2, 'discarded', 0.72, 'Logistic regression instead of boosting.'),
+ iteration(3, 'kept', 0.79, 'Add the number of files uploaded.'),
+ ],
error: '',
started_at: '2026-01-09T09:00:00Z',
completed_at: '2026-01-10T00:00:00Z',
@@ -154,3 +215,17 @@ export const Wide: Story = {
export const Narrow: Story = {
parameters: { testOptions: { viewportWidths: ['narrow'] } },
}
+
+export const AgentResearchWide: Story = {
+ parameters: {
+ pageUrl: `${urls.autoresearchPipeline(PIPELINE_ID)}?tab=agent_research`,
+ testOptions: { viewportWidths: ['wide'] },
+ },
+}
+
+export const AgentResearchNarrow: Story = {
+ parameters: {
+ pageUrl: `${urls.autoresearchPipeline(PIPELINE_ID)}?tab=agent_research`,
+ testOptions: { viewportWidths: ['narrow'] },
+ },
+}
diff --git a/products/autoresearch/frontend/agentSearch.test.ts b/products/autoresearch/frontend/agentSearch.test.ts
new file mode 100644
index 000000000000..ae28cfc75908
--- /dev/null
+++ b/products/autoresearch/frontend/agentSearch.test.ts
@@ -0,0 +1,93 @@
+import { buildAgentSearch, experimentLogGroups, latestAgentNotes } from './agentSearch'
+import { AutoresearchModelApi, AutoresearchTrainingRunApi, IterationTrailApi } from './generated/api.schemas'
+
+function iteration(
+ iteration_number: number,
+ status: IterationTrailApi['status'],
+ holdout_score: number | null
+): IterationTrailApi {
+ return { iteration_number, status, holdout_score, model_spec: { model_class: 'x' } } as IterationTrailApi
+}
+
+function run(
+ id: string,
+ created_at: string,
+ iterations: IterationTrailApi[],
+ overrides: Partial<AutoresearchTrainingRunApi> = {}
+): AutoresearchTrainingRunApi {
+ return {
+ id,
+ created_at,
+ status: 'completed',
+ iterations,
+ summary: null,
+ ...overrides,
+ } as AutoresearchTrainingRunApi
+}
+
+// Listed newest first, as the API returns them, to check the helpers order runs by time themselves.
+const RUNS = [
+ run('run-2', '2026-01-02T00:00:00Z', [
+ iteration(1, 'discarded', 0.78),
+ iteration(0, 'kept', 0.75),
+ iteration(2, 'crashed', null),
+ iteration(3, 'kept', 0.82),
+ ]),
+ run('run-1', '2026-01-01T00:00:00Z', [iteration(0, 'kept', 0.7), iteration(1, 'kept', 0.8)]),
+]
+
+describe('buildAgentSearch', () => {
+ it('measures each experiment against the best kept score before it, across runs', () => {
+ const { points } = buildAgentSearch(RUNS, null)
+ expect(
+ points.map((p) => [p.runNumber, p.iterationNumber, p.status, p.delta?.toFixed(2) ?? null, p.bestSoFar])
+ ).toEqual([
+ [1, 0, 'kept', null, 0.7],
+ [1, 1, 'kept', '0.10', 0.8],
+ // The first experiment of a later run compares against the best of the runs before it.
+ [2, 0, 'kept', '-0.05', 0.8],
+ // A discarded experiment with a higher score than a kept one does not raise the best.
+ [2, 1, 'discarded', '-0.02', 0.8],
+ [2, 2, 'crashed', null, 0.8],
+ [2, 3, 'kept', '0.02', 0.82],
+ ])
+ })
+
+ it('marks the kept experiment nearest the champion score in its source run as the live model', () => {
+ const champion = { source_training_run: 'run-2', holdout_score: 0.75 } as AutoresearchModelApi
+ const { points, runs } = buildAgentSearch(RUNS, champion)
+ expect(points.filter((p) => p.isLiveModel).map((p) => [p.runId, p.iterationNumber])).toEqual([['run-2', 0]])
+ expect(runs.map((r) => [r.runNumber, r.firstSeq, r.lastSeq])).toEqual([
+ [1, 1, 2],
+ [2, 3, 6],
+ ])
+ })
+})
+
+describe('experimentLogGroups', () => {
+ it('groups by run newest first, with entries newest first and the filter applied', () => {
+ const search = buildAgentSearch(RUNS, null)
+ expect(
+ experimentLogGroups(RUNS, search, 'kept').map((g) => [g.runNumber, g.entries.map((e) => e.iterationNumber)])
+ ).toEqual([
+ [2, [3, 0]],
+ [1, [1, 0]],
+ ])
+ })
+})
+
+describe('latestAgentNotes', () => {
+ it('reads the newest completed run that left notes', () => {
+ const notes = { distillation: 'Recency wins', recommended_next: 'Try sessions' }
+ const runs = [
+ run('run-3', '2026-01-03T00:00:00Z', [], { status: 'running' }),
+ run('run-2', '2026-01-02T00:00:00Z', [], { summary: { distillation: '', recommended_next: '' } as any }),
+ run('run-1', '2026-01-01T00:00:00Z', [], { summary: notes as any }),
+ ]
+ expect(latestAgentNotes(runs)).toEqual({
+ runNumber: 1,
+ distillation: 'Recency wins',
+ recommendedNext: 'Try sessions',
+ })
+ })
+})
diff --git a/products/autoresearch/frontend/agentSearch.ts b/products/autoresearch/frontend/agentSearch.ts
new file mode 100644
index 000000000000..8280baaf46a9
--- /dev/null
+++ b/products/autoresearch/frontend/agentSearch.ts
@@ -0,0 +1,201 @@
+import type {
+ AutoresearchIterationStatusEnumApi,
+ AutoresearchModelApi,
+ AutoresearchTrainingRunApi,
+ IterationTrailApiModelSpec,
+} from './generated/api.schemas'
+
+/** One experiment the agent ran, placed on the search across every training run. */
+export interface SearchPoint {
+ /** 1-based position across all runs, oldest first. The chart's x value. */
+ seq: number
+ runId: string
+ /** 1-based run number, oldest first. */
+ runNumber: number
+ iterationNumber: number
+ status: AutoresearchIterationStatusEnumApi
+ holdoutScore: number | null
+ agentDescription: string
+ modelSpec: IterationTrailApiModelSpec
+ /** Best kept holdout AUC before this experiment, across all earlier runs too. */
+ bestBefore: number | null
+ /** Holdout AUC minus `bestBefore`. Null for a crashed or unscored experiment, or when nothing came before. */
+ delta: number | null
+ /** Best kept holdout AUC after this experiment. Never goes down. */
+ bestSoFar: number | null
+ isLiveModel: boolean
+}
+
+/** The span of one training run on the chart's x axis. */
+export interface SearchRunBand {
+ runId: string
+ runNumber: number
+ startedAt: string
+ firstSeq: number
+ lastSeq: number
+}
+
+export interface AgentSearch {
+ points: SearchPoint[]
+ runs: SearchRunBand[]
+}
+
+export type ExperimentLogFilter = 'all' | 'kept' | 'discarded' | 'crashed'
+
+export interface ExperimentLogGroup {
+ run: AutoresearchTrainingRunApi
+ runNumber: number
+ /** Newest first, after the filter. */
+ entries: SearchPoint[]
+}
+
+export interface AgentNotes {
+ runNumber: number
+ distillation: string
+ recommendedNext: string
+}
+
+function oldestFirst(runs: AutoresearchTrainingRunApi[]): AutoresearchTrainingRunApi[] {
+ return [...runs].sort((a, b) => a.created_at.localeCompare(b.created_at))
+}
+
+/** The kept experiment that produced the champion: in its source run, the kept score nearest the champion's holdout AUC. */
+function liveModelIteration(run: AutoresearchTrainingRunApi, champion: AutoresearchModelApi | null): number | null {
+ if (!champion || champion.source_training_run !== run.id) {
+ return null
+ }
+ const target = champion.holdout_score ?? Infinity
+ let best: { iterationNumber: number; distance: number; score: number } | null = null
+ for (const it of run.iterations) {
+ if (it.status !== 'kept' || it.holdout_score == null) {
+ continue
+ }
+ const distance = Math.abs(it.holdout_score - target)
+ if (!best || distance < best.distance || (distance === best.distance && it.holdout_score > best.score)) {
+ best = { iterationNumber: it.iteration_number, distance, score: it.holdout_score }
+ }
+ }
+ return best?.iterationNumber ?? null
+}
+
+export function buildAgentSearch(
+ trainingRuns: AutoresearchTrainingRunApi[],
+ champion: AutoresearchModelApi | null
+): AgentSearch {
+ const points: SearchPoint[] = []
+ const runs: SearchRunBand[] = []
+ let best: number | null = null
+ oldestFirst(trainingRuns).forEach((run, runIndex) => {
+ const runNumber = runIndex + 1
+ const liveIteration = liveModelIteration(run, champion)
+ const iterations = [...run.iterations].sort((a, b) => a.iteration_number - b.iteration_number)
+ const firstSeq = points.length + 1
+ for (const it of iterations) {
+ const score = it.status === 'crashed' ? null : (it.holdout_score ?? null)
+ const bestBefore = best
+ if (it.status === 'kept' && score != null && (best == null || score > best)) {
+ best = score
+ }
+ points.push({
+ seq: points.length + 1,
+ runId: run.id,
+ runNumber,
+ iterationNumber: it.iteration_number,
+ status: it.status,
+ holdoutScore: score,
+ agentDescription: it.agent_description ?? '',
+ modelSpec: it.model_spec,
+ bestBefore,
+ delta: score != null && bestBefore != null ? score - bestBefore : null,
+ bestSoFar: best,
+ isLiveModel: it.iteration_number === liveIteration,
+ })
+ }
+ if (points.length >= firstSeq) {
+ runs.push({
+ runId: run.id,
+ runNumber,
+ startedAt: run.started_at ?? run.created_at,
+ firstSeq,
+ lastSeq: points.length,
+ })
+ }
+ })
+ return { points, runs }
+}
+
+/** The y range of the chart: the scored points with some room, inside [0, 1]. Crashed points sit on its floor. */
+export function searchYDomain(points: SearchPoint[]): [number, number] {
+ const scores = points.map((p) => p.holdoutScore).filter((s): s is number => s != null)
+ if (scores.length === 0) {
+ return [0, 1]
+ }
+ const low = Math.min(...scores)
+ const high = Math.max(...scores)
+ const pad = Math.max((high - low) * 0.1, 0.01)
+ return [Math.max(0, low - pad), Math.min(1, high + pad)]
+}
+
+export function experimentLogGroups(
+ trainingRuns: AutoresearchTrainingRunApi[],
+ search: AgentSearch,
+ filter: ExperimentLogFilter
+): ExperimentLogGroup[] {
+ const pointsByRun = new Map<string, SearchPoint[]>()
+ for (const point of search.points) {
+ if (filter === 'all' || point.status === filter) {
+ pointsByRun.set(point.runId, [...(pointsByRun.get(point.runId) ?? []), point])
+ }
+ }
+ return oldestFirst(trainingRuns)
+ .map((run, index) => ({
+ run,
+ runNumber: index + 1,
+ entries: [...(pointsByRun.get(run.id) ?? [])].reverse(),
+ }))
+ .reverse()
+}
+
+/** The newest completed run's notes. Null when no completed run left any. */
+export function latestAgentNotes(trainingRuns: AutoresearchTrainingRunApi[]): AgentNotes | null {
+ const ordered = oldestFirst(trainingRuns)
+ for (let i = ordered.length - 1; i >= 0; i--) {
+ const summary = ordered[i].summary
+ if (ordered[i].status === 'completed' && (summary?.distillation || summary?.recommended_next)) {
+ return {
+ runNumber: i + 1,
+ distillation: summary.distillation,
+ recommendedNext: summary.recommended_next,
+ }
+ }
+ }
+ return null
+}
+
+/** The agent's model spec (class and hyperparameters), compact. random_state is noise, so it is dropped. */
+export 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
+}
+
+/** "+0.021 vs best" style label for an experiment's change against the best score before it. */
+export function formatDelta(delta: number | null): string | null {
+ if (delta == null) {
+ return null
+ }
+ const rounded = Math.round(delta * 1000) / 1000
+ if (rounded === 0) {
+ return 'Same as best'
+ }
+ return `${rounded > 0 ? '+' : '−'}${Math.abs(rounded).toFixed(3)} vs best`
+}
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
index 6a766e3f4d19..0ca1543a7c46 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.test.ts
@@ -9,6 +9,7 @@ import { initKeaTests } from '~/test/init'
import {
SCORE_RUN_POLL_INTERVAL_MS,
+ TRAINING_RUN_POLL_INTERVAL_MS,
autoresearchPipelineLogic,
featureChanges,
scoringCoverage,
@@ -20,6 +21,7 @@ import {
autoresearchRunsList,
autoresearchRunsRetrieve,
autoresearchScoreCreate,
+ autoresearchTrainingRunsList,
} from './generated/api'
import {
AutoresearchRunApi,
@@ -44,6 +46,7 @@ const mockModelsList = autoresearchModelsList as jest.Mock
const mockRunsList = autoresearchRunsList as jest.Mock
const mockRunsRetrieve = autoresearchRunsRetrieve as jest.Mock
const mockScoreCreate = autoresearchScoreCreate as jest.Mock
+const mockTrainingRunsList = autoresearchTrainingRunsList as jest.Mock
function makeScoreRun(overrides: Partial<AutoresearchRunApi>): AutoresearchRunApi {
const now = new Date().toISOString()
@@ -175,6 +178,38 @@ describe('autoresearchPipelineLogic', () => {
}
})
+ it('reloads training runs while one is live, then reloads the champion once it finishes', async () => {
+ jest.clearAllMocks()
+ jest.useFakeTimers()
+ initKeaTests()
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.AUTORESEARCH], { [FEATURE_FLAGS.AUTORESEARCH]: true })
+ mockRetrieve.mockResolvedValue({ id: 'pipeline-1', name: 'Model' })
+ mockModelsList.mockResolvedValue({ results: [], next: null })
+ mockRunsList.mockResolvedValue({ results: [], next: null })
+ mockTrainingRunsList
+ .mockResolvedValueOnce({ results: [makeRun({ status: 'running' })], next: null })
+ .mockResolvedValueOnce({ results: [makeRun({ status: 'completed' })], next: null })
+ const logic = autoresearchPipelineLogic({ id: 'pipeline-1' })
+ try {
+ logic.mount()
+ await expectLogic(logic).toDispatchActions(['loadTrainingRunsSuccess'])
+ expect(logic.cache.disposables.registry.has('trainingPoll')).toBe(true)
+ const modelLoads = mockModelsList.mock.calls.length
+
+ await expectLogic(logic, () => jest.advanceTimersByTime(TRAINING_RUN_POLL_INTERVAL_MS)).toDispatchActions([
+ 'pollTrainingRuns',
+ 'loadTrainingRunsSuccess',
+ 'loadModels',
+ ])
+ expect(logic.cache.disposables.registry.has('trainingPoll')).toBe(false)
+ expect(mockModelsList.mock.calls.length).toBeGreaterThan(modelLoads)
+ } finally {
+ logic.unmount()
+ jest.useRealTimers()
+ }
+ })
+
it.each([
['resumes a run started a minute ago', 60 * 1000, 'score-run-1'],
['ignores a run that has been running past the stale cutoff', 6 * 60 * 60 * 1000, null],
diff --git a/products/autoresearch/frontend/autoresearchPipelineLogic.ts b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
index 3cf508d7e437..c490ba616a4e 100644
--- a/products/autoresearch/frontend/autoresearchPipelineLogic.ts
+++ b/products/autoresearch/frontend/autoresearchPipelineLogic.ts
@@ -19,6 +19,16 @@ import { Breadcrumb } from '~/types'
import { cohortsCreate } from 'products/cohorts/frontend/generated/api'
import type { FeatureFlagsSet } from '../../../frontend/src/lib/logic/featureFlagLogic'
+import {
+ AgentNotes,
+ AgentSearch,
+ ExperimentLogFilter,
+ ExperimentLogGroup,
+ SearchPoint,
+ buildAgentSearch,
+ experimentLogGroups,
+ latestAgentNotes,
+} from './agentSearch'
import {
autoresearchModelsList,
autoresearchPauseCreate,
@@ -85,6 +95,13 @@ export function pipelineTabFromUrl(value: unknown): AutoresearchPipelineTab | nu
/** How often the Score now button checks a running scoring run. */
export const SCORE_RUN_POLL_INTERVAL_MS = 5000
+/** How often the Agent research tab reloads training runs while one is pending or running. */
+export const TRAINING_RUN_POLL_INTERVAL_MS = 10000
+
+function isTrainingRunLive(run: AutoresearchTrainingRunApi): boolean {
+ return run.status === 'pending' || run.status === 'running'
+}
+
/** Matches the backend cutoff: a run still running after the workflow timeout lost its worker. */
export const SCORE_RUN_STALE_AFTER_MS = 5 * 60 * 60 * 1000
@@ -281,6 +298,8 @@ export interface autoresearchPipelineLogicValues {
currentTeamId: number | null // teamLogic
activeScoreRun: AutoresearchRunApi | null
activeTab: AutoresearchPipelineTab
+ agentNotes: AgentNotes | null
+ agentSearch: AgentSearch
artifactsByRun: Record<string, string[]>
artifactsByRunLoading: boolean
breadcrumbs: Breadcrumb[]
@@ -290,7 +309,11 @@ export interface autoresearchPipelineLogicValues {
dailyVolumeLoading: boolean
defaultTab: AutoresearchPipelineTab
detailRequested: boolean
+ expandedLogRunIds: string[]
expandedRunId: string | null
+ experimentLogFilter: ExperimentLogFilter
+ experimentLogGroups: ExperimentLogGroup[]
+ hasLiveTrainingRun: boolean
lifecycleSteps: LifecycleStep[] | null
modelByTrainingRun: Record<string, AutoresearchModelApi>
models: AutoresearchModelApi[]
@@ -565,6 +588,9 @@ export interface autoresearchPipelineLogicActions {
pollScoreRun: () => {
value: true
}
+ pollTrainingRuns: () => {
+ value: true
+ }
reportNotebookOpened: (runId: string) => {
runId: string
}
@@ -610,12 +636,18 @@ export interface autoresearchPipelineLogicActions {
scoreRunFinished: (run: AutoresearchRunApi) => {
run: AutoresearchRunApi
}
+ searchPointClicked: (point: SearchPoint) => {
+ point: SearchPoint
+ }
setActiveScoreRun: (run: AutoresearchRunApi | null) => {
run: AutoresearchRunApi | null
}
setActiveTab: (tab: AutoresearchPipelineTab) => {
tab: AutoresearchPipelineTab
}
+ setExperimentLogFilter: (filter: ExperimentLogFilter) => {
+ filter: ExperimentLogFilter
+ }
setPredictionsPeopleView: (view: PredictionsPeopleView) => {
view: PredictionsPeopleView
}
@@ -639,6 +671,9 @@ export interface autoresearchPipelineLogicActions {
error: string
errorObject?: any
}
+ startTrainingPolling: () => {
+ value: true
+ }
startTrainingSuccess: (
startTrainingResult: AutoresearchTrainingRunApi | null,
payload?: any
@@ -661,6 +696,9 @@ export interface autoresearchPipelineLogicActions {
suggestionSubmitResult: AutoresearchSuggestionApi | null
payload?: any
}
+ toggleLogRun: (runId: string) => {
+ runId: string
+ }
toggleRunArtifacts: (runId: string) => {
runId: string
}
@@ -714,6 +752,14 @@ export interface autoresearchPipelineLogicMeta {
) => ScoringCoverage | null
onlinePerformanceRows: (validationRuns: AutoresearchRunApi[]) => OnlinePerformanceRow[]
probabilityHistogram: (probabilityDistribution: ProbabilityBucket[] | null) => ProbabilityBucket[] | null
+ hasLiveTrainingRun: (trainingRuns: AutoresearchTrainingRunApi[]) => boolean
+ agentSearch: (trainingRuns: AutoresearchTrainingRunApi[], champion: AutoresearchModelApi | null) => AgentSearch
+ experimentLogGroups: (
+ trainingRuns: AutoresearchTrainingRunApi[],
+ agentSearch: AgentSearch,
+ experimentLogFilter: ExperimentLogFilter
+ ) => ExperimentLogGroup[]
+ agentNotes: (trainingRuns: AutoresearchTrainingRunApi[]) => AgentNotes | null
defaultTab: (pipeline: AutoresearchPipelineApi | null) => AutoresearchPipelineTab
activeTab: (
selectedTab: AutoresearchPipelineTab | null,
@@ -759,6 +805,11 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
startScorePolling: true,
pollScoreRun: true,
scoreRunFinished: (run: AutoresearchRunApi) => ({ run }),
+ startTrainingPolling: true,
+ pollTrainingRuns: true,
+ setExperimentLogFilter: (filter: ExperimentLogFilter) => ({ filter }),
+ toggleLogRun: (runId: string) => ({ runId }),
+ searchPointClicked: (point: SearchPoint) => ({ point }),
saveSegmentCohort: (segment: PredictionSegmentKey) => ({ segment }),
saveSegmentCohortFinished: true,
}),
@@ -797,6 +848,21 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
toggleRunArtifacts: (current, { runId }) => (current === runId ? null : runId),
},
],
+ experimentLogFilter: [
+ 'all' as ExperimentLogFilter,
+ {
+ setExperimentLogFilter: (_, { filter }) => filter,
+ },
+ ],
+ expandedLogRunIds: [
+ [] as string[],
+ {
+ toggleLogRun: (current, { runId }) =>
+ current.includes(runId) ? current.filter((id) => id !== runId) : [...current, runId],
+ searchPointClicked: (current, { point }) =>
+ current.includes(point.runId) ? current : [...current, point.runId],
+ },
+ ],
suggestionDraft: [
'',
{
@@ -1261,6 +1327,27 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
}))
},
],
+ hasLiveTrainingRun: [
+ (s) => [s.trainingRuns],
+ (trainingRuns: AutoresearchTrainingRunApi[]): boolean => trainingRuns.some(isTrainingRunLive),
+ ],
+ agentSearch: [
+ (s) => [s.trainingRuns, s.champion],
+ (trainingRuns: AutoresearchTrainingRunApi[], champion: AutoresearchModelApi | null): AgentSearch =>
+ buildAgentSearch(trainingRuns, champion),
+ ],
+ experimentLogGroups: [
+ (s) => [s.trainingRuns, s.agentSearch, s.experimentLogFilter],
+ (
+ trainingRuns: AutoresearchTrainingRunApi[],
+ agentSearch: AgentSearch,
+ experimentLogFilter: ExperimentLogFilter
+ ): ExperimentLogGroup[] => experimentLogGroups(trainingRuns, agentSearch, experimentLogFilter),
+ ],
+ agentNotes: [
+ (s) => [s.trainingRuns],
+ (trainingRuns: AutoresearchTrainingRunApi[]): AgentNotes | null => latestAgentNotes(trainingRuns),
+ ],
defaultTab: [
(s) => [s.pipeline],
(pipeline: AutoresearchPipelineApi | null): AutoresearchPipelineTab =>
@@ -1434,8 +1521,48 @@ export const autoresearchPipelineLogic = kea<autoresearchPipelineLogicType>([
)
}
},
- submitSuggestionSuccess: () => {
- posthog.capture('autoresearch model suggestion sent', { pipeline_id: props.id })
+ loadTrainingRunsSuccess: ({ trainingRuns }) => {
+ if (trainingRuns.some(isTrainingRunLive)) {
+ actions.startTrainingPolling()
+ } else if (cache.disposables.registry.has('trainingPoll')) {
+ // The run finished, so the champion and the pipeline counters may have changed.
+ cache.disposables.dispose('trainingPoll')
+ actions.loadModels()
+ actions.loadPipeline()
+ }
+ },
+ startTrainingPolling: () => {
+ if (cache.disposables.registry.has('trainingPoll')) {
+ return
+ }
+ cache.disposables.add(() => {
+ const timer = window.setInterval(() => actions.pollTrainingRuns(), TRAINING_RUN_POLL_INTERVAL_MS)
+ return () => clearInterval(timer)
+ }, 'trainingPoll')
+ },
+ pollTrainingRuns: () => {
+ if (!values.trainingRunsLoading) {
+ actions.loadTrainingRuns()
+ }
+ },
+ setExperimentLogFilter: ({ filter }) => {
+ // pinned: analytics event name and properties. Renaming breaks insights built on them.
+ posthog.capture('autoresearch model experiment log filter changed', { pipeline_id: props.id, filter })
+ },
+ searchPointClicked: ({ point }) => {
+ // pinned: analytics event name and properties. Renaming breaks insights built on them.
+ posthog.capture('autoresearch model search point clicked', {
+ pipeline_id: props.id,
+ run_id: point.runId,
+ iteration_number: point.iterationNumber,
+ status: point.status,
+ })
+ },
+ submitSuggestionSuccess: ({ suggestionSubmitResult }) => {
+ posthog.capture('autoresearch model suggestion sent', {
+ pipeline_id: props.id,
+ priority: suggestionSubmitResult?.priority ?? values.suggestionPriority,
+ })
actions.loadSuggestions()
lemonToast.success('Suggestion sent. The agent will pick it up on its next run.')
},
diff --git a/products/autoresearch/frontend/pipeline/AgentNotes.tsx b/products/autoresearch/frontend/pipeline/AgentNotes.tsx
new file mode 100644
index 000000000000..5852ec6ef8d9
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/AgentNotes.tsx
@@ -0,0 +1,21 @@
+import { useValues } from 'kea'
+
+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+
+/** What the newest completed run learned, and what the agent plans to try next. Renders nothing before any notes exist. */
+export function AgentNotes(): JSX.Element | null {
+ const { agentNotes } = useValues(autoresearchPipelineLogic)
+ if (!agentNotes) {
+ return null
+ }
+ return (
+ <div className="border rounded p-3 space-y-2">
+ <div className="text-sm font-semibold">Agent notes</div>
+ {agentNotes.distillation && <div className="text-sm">{agentNotes.distillation}</div>}
+ {agentNotes.recommendedNext && (
+ <div className="text-sm text-muted">Next it plans to: {agentNotes.recommendedNext}</div>
+ )}
+ <div className="text-xs text-muted">From run {agentNotes.runNumber}</div>
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/AgentResearchTab.tsx b/products/autoresearch/frontend/pipeline/AgentResearchTab.tsx
index 291ef7dc9e04..a0639cb43391 100644
--- a/products/autoresearch/frontend/pipeline/AgentResearchTab.tsx
+++ b/products/autoresearch/frontend/pipeline/AgentResearchTab.tsx
@@ -1,15 +1,17 @@
+import { AgentNotes } from './AgentNotes'
import { LiveModelCard } from './LiveModelCard'
import { SuggestionsTab } from './SuggestionsTab'
import { TrainingTab } from './TrainingTab'
-/** What the agent did (live model, training runs) next to how to steer it (suggestions). */
+/** What the agent did (search chart, experiment log) next to the live model, its notes, and how to steer it. */
export function AgentResearchTab(): JSX.Element {
return (
- <div className="space-y-4">
- <LiveModelCard />
- <div className="@container">
- <div className="grid grid-cols-1 @3xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] gap-4 items-start">
- <TrainingTab />
+ <div className="@container">
+ <div className="grid grid-cols-1 @3xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)] gap-4 items-start">
+ <TrainingTab />
+ <div className="space-y-4 min-w-0">
+ <LiveModelCard />
+ <AgentNotes />
<SuggestionsTab />
</div>
</div>
diff --git a/products/autoresearch/frontend/pipeline/AgentSearchChart.tsx b/products/autoresearch/frontend/pipeline/AgentSearchChart.tsx
new file mode 100644
index 000000000000..fca4ba72a801
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/AgentSearchChart.tsx
@@ -0,0 +1,121 @@
+import { useActions, useValues } from 'kea'
+import { useMemo } from 'react'
+
+import { ScatterChart, TooltipFooter, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'
+import type { ScatterChartConfig, ScatterPoint, ScatterSeries } from '@posthog/quill-charts'
+
+import { useChartTheme } from 'lib/charts/hooks'
+
+import { type SearchPoint, formatDelta, searchYDomain } from '../agentSearch'
+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+import { AgentSearchOverlay } from './AgentSearchOverlay'
+
+const STATUS_LABEL: Record<SearchPoint['status'], string> = {
+ kept: 'Kept',
+ discarded: 'Discarded',
+ crashed: 'Crashed',
+}
+
+// Room above the plot for the run band labels.
+const CHART_MARGINS = { top: 24 }
+
+/** Every experiment across runs: holdout AUC by status, the best score so far, run bands and the live model. */
+export function AgentSearchChart(): JSX.Element | null {
+ const { agentSearch } = useValues(autoresearchPipelineLogic)
+ const { searchPointClicked } = useActions(autoresearchPipelineLogic)
+ const theme = useChartTheme()
+
+ const { series, config } = useMemo(() => {
+ const points = agentSearch.points
+ const yDomain = searchYDomain(points)
+ const toPoint = (p: SearchPoint): ScatterPoint<SearchPoint> => ({
+ x: p.seq,
+ y: p.holdoutScore ?? yDomain[0],
+ label: `Run ${p.runNumber} · experiment ${p.iterationNumber}`,
+ meta: p,
+ })
+ const series: ScatterSeries<SearchPoint>[] = [
+ {
+ key: 'kept',
+ label: 'Kept',
+ color: 'var(--success)',
+ points: points.filter((p) => p.status === 'kept' && p.holdoutScore != null).map(toPoint),
+ },
+ {
+ key: 'discarded',
+ label: 'Discarded',
+ color: 'var(--color-text-secondary)',
+ pointRadius: 3,
+ points: points.filter((p) => p.status === 'discarded' && p.holdoutScore != null).map(toPoint),
+ },
+ {
+ key: 'crashed',
+ label: 'Crashed',
+ color: 'var(--danger)',
+ shape: 'cross',
+ points: points.filter((p) => p.status === 'crashed' || p.holdoutScore == null).map(toPoint),
+ },
+ ]
+ const config: ScatterChartConfig<SearchPoint> = {
+ xAxis: {
+ domain: [0.5, points.length + 0.5],
+ label: 'Experiment',
+ tickFormatter: (value) => (Number.isInteger(value) ? String(value) : ''),
+ },
+ yAxis: { domain: yDomain, label: 'Holdout AUC', tickFormatter: (value) => value.toFixed(2) },
+ legend: { show: true },
+ margins: CHART_MARGINS,
+ }
+ return { series, config }
+ }, [agentSearch])
+
+ if (agentSearch.points.length === 0) {
+ return null
+ }
+
+ return (
+ <div className="border rounded p-3 space-y-2">
+ <div>
+ <div className="text-sm font-semibold">How the agent found it</div>
+ <div className="text-xs text-muted">
+ Each dot is one experiment. The agent keeps a change only when it beats the best score so far.
+ </div>
+ </div>
+ <div className="h-64 min-w-0 flex flex-col">
+ <ScatterChart
+ series={series}
+ theme={theme}
+ config={config}
+ dataAttr="autoresearch-search-chart"
+ onPointClick={(point) => point.meta && searchPointClicked(point.meta)}
+ tooltip={({ point }) => {
+ const p = point.meta
+ if (!p) {
+ return null
+ }
+ const delta = formatDelta(p.delta)
+ return (
+ <TooltipSurface data-attr="autoresearch-search-chart-tooltip">
+ <div className="font-semibold text-sm">{`Run ${p.runNumber} · experiment ${p.iterationNumber}`}</div>
+ <div className="flex items-center gap-2 mt-1">
+ <TooltipSwatch color={point.color} />
+ <span>{STATUS_LABEL[p.status]}</span>
+ {p.holdoutScore != null && (
+ <strong className="tabular-nums">{`AUC ${p.holdoutScore.toFixed(3)}`}</strong>
+ )}
+ {delta && <span className="opacity-70">{delta}</span>}
+ </div>
+ {p.agentDescription && (
+ <div className="mt-1 max-w-80 break-words opacity-80">{p.agentDescription}</div>
+ )}
+ <TooltipFooter>Click to open this run in the log</TooltipFooter>
+ </TooltipSurface>
+ )
+ }}
+ >
+ <AgentSearchOverlay search={agentSearch} />
+ </ScatterChart>
+ </div>
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/AgentSearchOverlay.tsx b/products/autoresearch/frontend/pipeline/AgentSearchOverlay.tsx
new file mode 100644
index 000000000000..65546173d96a
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/AgentSearchOverlay.tsx
@@ -0,0 +1,105 @@
+import { useId } from 'react'
+
+import { useChartLayout } from '@posthog/quill-charts'
+
+import { dayjs } from 'lib/dayjs'
+
+import type { AgentSearch } from '../agentSearch'
+
+/**
+ * Run bands, the best-so-far step line and the live model marker, drawn over the scatter.
+ * The parent pins the x domain to [0.5, N + 0.5], so x maps linearly from `seq`.
+ */
+export function AgentSearchOverlay({ search }: { search: AgentSearch }): JSX.Element {
+ const clipId = useId()
+ const { dimensions, scales } = useChartLayout()
+ const { plotLeft, plotTop, plotWidth, plotHeight } = dimensions
+ const count = search.points.length
+ const xOf = (seq: number): number => plotLeft + ((seq - 0.5) / count) * plotWidth
+
+ const segments: string[] = []
+ let previous: number | null = null
+ for (const point of search.points) {
+ if (point.bestSoFar == null) {
+ continue
+ }
+ const y = scales.y(point.bestSoFar)
+ const left = xOf(point.seq - 0.5)
+ const right = xOf(point.seq + 0.5)
+ segments.push(previous == null ? `M${left},${y}` : `V${y}`, `H${right}`)
+ previous = y
+ }
+ const stepPath = segments.join(' ')
+
+ const live = search.points.find((p) => p.isLiveModel && p.holdoutScore != null)
+ const liveX = live ? xOf(live.seq) : null
+ const liveY = live?.holdoutScore != null ? scales.y(live.holdoutScore) : null
+
+ return (
+ <svg
+ className="absolute inset-0 w-full h-full pointer-events-none"
+ aria-hidden
+ data-attr="autoresearch-search-overlay"
+ >
+ <defs>
+ <clipPath id={clipId}>
+ <rect x={plotLeft} y={plotTop - 16} width={plotWidth} height={plotHeight + 16} />
+ </clipPath>
+ </defs>
+ <g clipPath={`url(#${clipId})`}>
+ {search.runs.map((run) => {
+ const left = xOf(run.firstSeq - 0.5)
+ const right = xOf(run.lastSeq + 0.5)
+ return (
+ <g key={run.runId}>
+ {run.runNumber % 2 === 0 && (
+ <rect
+ x={left}
+ y={plotTop}
+ width={right - left}
+ height={plotHeight}
+ fill="var(--color-bg-fill-highlight-50)"
+ />
+ )}
+ {run.runNumber > 1 && (
+ <line
+ x1={left}
+ x2={left}
+ y1={plotTop}
+ y2={plotTop + plotHeight}
+ stroke="var(--color-border-primary)"
+ strokeDasharray="2 3"
+ />
+ )}
+ {right - left >= 56 && (
+ <text x={left + 4} y={plotTop - 4} fontSize={10} fill="var(--color-text-secondary)">
+ {`Run ${run.runNumber} · ${dayjs(run.startedAt).format('MMM D')}`}
+ </text>
+ )}
+ </g>
+ )
+ })}
+ <path d={stepPath} fill="none" stroke="var(--success)" strokeWidth={1.5} strokeOpacity={0.8} />
+ {liveX != null && liveY != null && (
+ <g>
+ <circle cx={liveX} cy={liveY} r={8} fill="none" stroke="var(--success)" strokeWidth={2} />
+ <text
+ x={liveX}
+ // Near the top, the run band labels take the space above the marker.
+ y={liveY - 12 < plotTop + 14 ? liveY + 20 : liveY - 12}
+ fontSize={11}
+ fontWeight={600}
+ textAnchor={liveX > plotLeft + plotWidth - 40 ? 'end' : 'middle'}
+ fill="var(--color-text-primary)"
+ stroke="var(--color-bg-surface-primary)"
+ strokeWidth={3}
+ paintOrder="stroke"
+ >
+ Live model
+ </text>
+ </g>
+ )}
+ </g>
+ </svg>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/ExperimentLog.tsx b/products/autoresearch/frontend/pipeline/ExperimentLog.tsx
new file mode 100644
index 000000000000..fd460f2cff0c
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/ExperimentLog.tsx
@@ -0,0 +1,65 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonSegmentedButton } from '@posthog/lemon-ui'
+
+import type { ExperimentLogFilter } from '../agentSearch'
+import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
+import { ExperimentLogEntry } from './ExperimentLogEntry'
+import { TrainingRunRow } from './TrainingRunRow'
+
+const FILTER_OPTIONS: { value: ExperimentLogFilter; label: string }[] = [
+ { value: 'all', label: 'All' },
+ { value: 'kept', label: 'Kept' },
+ { value: 'discarded', label: 'Discarded' },
+ { value: 'crashed', label: 'Crashed' },
+]
+
+/** Every experiment, grouped by training run, newest first. Only the latest run shows its experiments by default. */
+export function ExperimentLog(): JSX.Element {
+ const { experimentLogGroups, experimentLogFilter, expandedLogRunIds } = useValues(autoresearchPipelineLogic)
+ const { setExperimentLogFilter, toggleLogRun } = useActions(autoresearchPipelineLogic)
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between gap-2 flex-wrap">
+ <div className="text-sm font-semibold">Experiment log</div>
+ <LemonSegmentedButton
+ size="xsmall"
+ value={experimentLogFilter}
+ onChange={setExperimentLogFilter}
+ options={FILTER_OPTIONS}
+ data-attr="autoresearch-experiment-log-filter"
+ />
+ </div>
+ {experimentLogGroups.map((group, index) => {
+ const showEntries = index === 0 || expandedLogRunIds.includes(group.run.id)
+ return (
+ <TrainingRunRow key={group.run.id} run={group.run} runNumber={group.runNumber}>
+ {group.entries.length === 0 ? (
+ group.run.iterations.length > 0 && (
+ <div className="border-t px-3 py-2 text-xs text-muted">
+ No experiments match this filter.
+ </div>
+ )
+ ) : showEntries ? (
+ <div className="border-t">
+ {group.entries.map((entry) => (
+ <ExperimentLogEntry key={entry.seq} entry={entry} />
+ ))}
+ </div>
+ ) : (
+ <div className="border-t px-1 py-1">
+ <LemonButton
+ size="small"
+ onClick={() => toggleLogRun(group.run.id)}
+ data-attr="autoresearch-experiment-log-show-run"
+ >
+ {`Show ${group.entries.length} earlier ${group.entries.length === 1 ? 'experiment' : 'experiments'}`}
+ </LemonButton>
+ </div>
+ )}
+ </TrainingRunRow>
+ )
+ })}
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/ExperimentLogEntry.tsx b/products/autoresearch/frontend/pipeline/ExperimentLogEntry.tsx
new file mode 100644
index 000000000000..f81866c77a51
--- /dev/null
+++ b/products/autoresearch/frontend/pipeline/ExperimentLogEntry.tsx
@@ -0,0 +1,46 @@
+import { LemonTag } from '@posthog/lemon-ui'
+
+import { type SearchPoint, formatDelta, formatModelSpec } from '../agentSearch'
+
+const STATUS_TAG: Record<SearchPoint['status'], { type: 'success' | 'default' | 'danger'; label: string }> = {
+ kept: { type: 'success', label: 'Kept' },
+ discarded: { type: 'default', label: 'Discarded' },
+ crashed: { type: 'danger', label: 'Crashed' },
+}
+
+/** One experiment in the log: its status, its change against the best score before it, and what the agent tried. */
+export function ExperimentLogEntry({ entry }: { entry: SearchPoint }): JSX.Element {
+ const tag = STATUS_TAG[entry.status]
+ const spec = formatModelSpec(entry.modelSpec)
+ const delta = formatDelta(entry.delta)
+ return (
+ <div className="border-t first:border-t-0 px-3 py-2 space-y-1">
+ <div className="flex items-center gap-2 flex-wrap">
+ <span className="text-sm font-semibold">Experiment {entry.iterationNumber}</span>
+ <LemonTag type={tag.type} size="small">
+ {tag.label}
+ </LemonTag>
+ {entry.isLiveModel && (
+ <LemonTag type="completion" size="small">
+ Live model
+ </LemonTag>
+ )}
+ <span className="text-xs text-muted tabular-nums ml-auto">
+ {entry.holdoutScore != null ? `AUC ${entry.holdoutScore.toFixed(3)}` : 'No score'}
+ {delta && (
+ <span className={entry.delta != null && entry.delta > 0 ? 'text-success ml-2' : 'ml-2'}>
+ {delta}
+ </span>
+ )}
+ </span>
+ </div>
+ {entry.agentDescription && <div className="text-sm">{entry.agentDescription}</div>}
+ {spec && (
+ <div className="text-xs text-muted font-mono break-words">
+ {spec.className}
+ {spec.params && ` · ${spec.params}`}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/autoresearch/frontend/pipeline/IterationTrail.tsx b/products/autoresearch/frontend/pipeline/IterationTrail.tsx
deleted file mode 100644
index 4b2631e480ff..000000000000
--- a/products/autoresearch/frontend/pipeline/IterationTrail.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-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/LiveModelCard.tsx b/products/autoresearch/frontend/pipeline/LiveModelCard.tsx
index 23a96d2b87a8..610b8f1f3fac 100644
--- a/products/autoresearch/frontend/pipeline/LiveModelCard.tsx
+++ b/products/autoresearch/frontend/pipeline/LiveModelCard.tsx
@@ -22,7 +22,7 @@ export function LiveModelCard(): JSX.Element | null {
</Tooltip>
)}
</div>
- <div className="grid grid-cols-2 gap-4 md:grid-cols-3">
+ <div className="grid grid-cols-2 gap-3">
<MetricCard
label="Holdout AUC"
value={champion.holdout_score?.toFixed(3) ?? '—'}
diff --git a/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsx b/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsx
index bbc5fae5c7d8..f6a787a858e7 100644
--- a/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsx
+++ b/products/autoresearch/frontend/pipeline/TrainingRunRow.stories.tsx
@@ -102,7 +102,7 @@ function ExpandedRunRow({
return (
<BindLogic logic={autoresearchPipelineLogic} props={{ id: PIPELINE_ID }}>
<div className={WIDTH_CLASS[width]}>
- <TrainingRunRow run={RUN} />
+ <TrainingRunRow run={RUN} runNumber={1} />
</div>
</BindLogic>
)
diff --git a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx
index 42205818d470..6ddbf6a266b4 100644
--- a/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx
+++ b/products/autoresearch/frontend/pipeline/TrainingRunRow.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import type { ReactNode } from 'react'
import { IconChevronRight, IconExternal, IconNotebook } from '@posthog/icons'
import { LemonBanner, LemonButton, LemonCollapse, LemonTag, Link, Spinner, Tooltip } from '@posthog/lemon-ui'
@@ -10,7 +11,6 @@ import { urls } from 'scenes/urls'
import { autoresearchPipelineLogic, trainingRunProgress } from '../autoresearchPipelineLogic'
import { type AutoresearchRunApi, AutoresearchTrainingRunApi } from '../generated/api.schemas'
-import { IterationTrail } from './IterationTrail'
import { RunFeatureComparison } from './RunFeatureComparison'
// Derived from the field rather than the standalone enum: this pending/running/completed/failed
@@ -52,7 +52,16 @@ function RunReport({ runId }: { runId: string }): JSX.Element | null {
)
}
-export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JSX.Element {
+/** One training run in the experiment log: its header, the experiments passed as children, and its report and bundle on expand. */
+export function TrainingRunRow({
+ run,
+ runNumber,
+ children,
+}: {
+ run: AutoresearchTrainingRunApi
+ runNumber: number
+ children?: ReactNode
+}): JSX.Element {
const { expandedRunId, artifactsByRun, artifactsByRunLoading, featureFlags } = useValues(autoresearchPipelineLogic)
const { toggleRunArtifacts, viewArtifact, reportNotebookOpened } = useActions(autoresearchPipelineLogic)
const reportNotebookShortId = featureFlags[FEATURE_FLAGS.AUTORESEARCH_REPORT_NOTEBOOK]
@@ -68,7 +77,7 @@ export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JS
const progressSummary =
run.status === 'failed' && progress.iterationCount === 0
? 'Failed before any iterations'
- : `${progress.iterationCount} iterations · ${
+ : `${progress.iterationCount} ${progress.iterationCount === 1 ? 'experiment' : 'experiments'} · ${
progress.bestHoldoutScore != null
? `best AUC ${progress.bestHoldoutScore.toFixed(3)}`
: 'no score yet'
@@ -82,13 +91,13 @@ export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JS
size="small"
icon={<IconChevronRight className={`transition-transform ${isExpanded ? 'rotate-90' : ''}`} />}
onClick={() => toggleRunArtifacts(run.id)}
- tooltip={isExpanded ? 'Hide details' : 'Show iterations & bundle'}
+ tooltip={isExpanded ? 'Hide report and bundle' : 'Show report and 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>
+ Run {runNumber} · <span translate="no">{dayjs(startedAt).fromNow()}</span>
</span>
</Tooltip>
{run.task_url && (
@@ -127,10 +136,6 @@ export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JS
) : (
<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.status === 'completed' && (
<div className="space-y-2">
<div className="text-xs font-semibold text-muted uppercase tracking-wide">
@@ -175,6 +180,7 @@ export function TrainingRunRow({ run }: { run: AutoresearchTrainingRunApi }): JS
</div>
</div>
)}
+ {children}
</div>
)
}
diff --git a/products/autoresearch/frontend/pipeline/TrainingTab.tsx b/products/autoresearch/frontend/pipeline/TrainingTab.tsx
index 34347c0b3918..c07094bc375d 100644
--- a/products/autoresearch/frontend/pipeline/TrainingTab.tsx
+++ b/products/autoresearch/frontend/pipeline/TrainingTab.tsx
@@ -4,26 +4,31 @@ import { IconRefresh } from '@posthog/icons'
import { LemonBanner, LemonButton, Spinner } from '@posthog/lemon-ui'
import { autoresearchPipelineLogic } from '../autoresearchPipelineLogic'
-import { AutoresearchTrainingRunApi } from '../generated/api.schemas'
+import { AgentSearchChart } from './AgentSearchChart'
import { ArtifactViewerModal } from './ArtifactViewerModal'
import { EmptyTab } from './EmptyTab'
-import { TrainingRunRow } from './TrainingRunRow'
+import { ExperimentLog } from './ExperimentLog'
export function TrainingTab(): JSX.Element {
- const { pipeline, trainingRuns, trainingRunsLoading, trainingRunsError, startTrainingResultLoading } =
- useValues(autoresearchPipelineLogic)
+ const {
+ pipeline,
+ trainingRuns,
+ trainingRunsLoading,
+ trainingRunsError,
+ startTrainingResultLoading,
+ hasLiveTrainingRun,
+ } = 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
+ : hasLiveTrainingRun
? 'A training run is already in progress'
: undefined
return (
- <div className="space-y-4">
+ <div className="space-y-4 min-w-0">
<div className="flex items-center gap-2">
<LemonButton
type="primary"
@@ -35,9 +40,10 @@ export function TrainingTab(): JSX.Element {
Run training
</LemonButton>
</div>
- {trainingRunsLoading ? (
+ {/* Polling reloads the runs while one is live, so keep the loaded runs on screen during a reload. */}
+ {trainingRuns.length === 0 && trainingRunsLoading ? (
<Spinner />
- ) : trainingRunsError ? (
+ ) : trainingRuns.length === 0 && trainingRunsError ? (
<LemonBanner
type="error"
action={{
@@ -54,11 +60,10 @@ export function TrainingTab(): JSX.Element {
the changes that improve holdout AUC.
</EmptyTab>
) : (
- <div className="space-y-2">
- {trainingRuns.map((run: AutoresearchTrainingRunApi) => (
- <TrainingRunRow key={run.id} run={run} />
- ))}
- </div>
+ <>
+ <AgentSearchChart />
+ <ExperimentLog />
+ </>
)}
<ArtifactViewerModal />
</div>
diff --git a/products/autoresearch/package.json b/products/autoresearch/package.json
index 0c29f5101683..2acae448ef9a 100644
--- a/products/autoresearch/package.json
+++ b/products/autoresearch/package.json
@@ -5,6 +5,7 @@
"backend:test": "pytest -c ../../pytest.ini --rootdir ../.. backend/ -v --tb=short || test $? -eq 5"
},
"dependencies": {
+ "@posthog/quill-charts": "workspace:*",
"kea": "catalog:",
"kea-forms": "catalog:",
"kea-loaders": "catalog:",