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): show the model list as question cards (#113141)

posthog[bot]4c088baaf795
diff --git a/products/autoresearch/backend/evaluation/history.py b/products/autoresearch/backend/evaluation/history.py
index bb2a6dca991b..ae92b90514ba 100644
--- a/products/autoresearch/backend/evaluation/history.py
+++ b/products/autoresearch/backend/evaluation/history.py
@@ -1,7 +1,11 @@
"""The realized history of a pipeline: its completed validation runs, one per validated group."""
-from django.db.models import F
+from datetime import date
+from uuid import UUID
+
+from django.db.models import F, Window
from django.db.models.fields.json import KT
+from django.db.models.functions import DenseRank
from products.autoresearch.backend.models import AutoresearchPipeline, AutoresearchRun
@@ -26,3 +30,46 @@ def latest_validation_runs(team_id: int, pipeline: AutoresearchPipeline, *, limi
.order_by("-prediction_date", "horizon", F("completed_at").desc(nulls_last=True), "-id")
.distinct("prediction_date", "horizon")[:limit]
)
+
+
+def realized_auc_trends(
+ team_id: int, model_ids_by_pipeline: dict[UUID, UUID], *, dates: int
+) -> dict[UUID, list[tuple[date, float]]]:
+ """
+ Realized AUC of one model per pipeline on its newest ``dates`` validated prediction dates, oldest first.
+
+ One query for any number of pipelines. A date with no AUC for the model, for example a
+ single-class date, is left out. When a date was validated more than once, the newest
+ completed run wins.
+ """
+ if not model_ids_by_pipeline:
+ return {}
+ runs = (
+ AutoresearchRun.objects.for_team(team_id)
+ .filter(
+ pipeline_id__in=list(model_ids_by_pipeline),
+ run_type=AutoresearchRun.RunType.VALIDATION,
+ status=AutoresearchRun.Status.COMPLETED,
+ metrics__has_key="prediction_date",
+ )
+ .annotate(
+ prediction_date=KT("metrics__prediction_date"),
+ date_rank=Window(DenseRank(), partition_by=[F("pipeline_id")], order_by=F("prediction_date").desc()),
+ )
+ .filter(date_rank__lte=dates)
+ .order_by("pipeline_id", "prediction_date", F("completed_at").desc(nulls_last=True), "-id")
+ .only("pipeline_id", "metrics", "completed_at")
+ )
+ seen: set[tuple[UUID, date]] = set()
+ trends: dict[UUID, dict[date, float]] = {}
+ for run in runs:
+ points = trends.setdefault(run.pipeline_id, {})
+ prediction_date = date.fromisoformat(run.metrics["prediction_date"])
+ if (run.pipeline_id, prediction_date) in seen:
+ continue
+ seen.add((run.pipeline_id, prediction_date))
+ model_metrics = (run.metrics.get("per_model") or {}).get(str(model_ids_by_pipeline[run.pipeline_id])) or {}
+ auc = model_metrics.get("realized_auc")
+ if isinstance(auc, int | float):
+ points[prediction_date] = float(auc)
+ return {pipeline_id: sorted(points.items()) for pipeline_id, points in trends.items()}
diff --git a/products/autoresearch/backend/facade/api.py b/products/autoresearch/backend/facade/api.py
index 4457295c4305..64ed0fe3a971 100644
--- a/products/autoresearch/backend/facade/api.py
+++ b/products/autoresearch/backend/facade/api.py
@@ -19,9 +19,10 @@ from uuid import UUID, uuid4
from django.conf import settings
from django.db import transaction
-from django.db.models import F, Prefetch, Q
+from django.db.models import Count, F, Prefetch, Q
from django.utils import timezone as django_timezone
+from posthog.dataclasses import frozen
from posthog.models.team import Team
from posthog.models.user import User
from posthog.storage.object_storage import ObjectStorageError
@@ -38,7 +39,7 @@ from ..dataset.validation import (
ValidationWarningCode as _ValidationWarningCode,
validate_pipeline_definition as _validate_pipeline_definition,
)
-from ..evaluation.history import latest_validation_runs
+from ..evaluation.history import latest_validation_runs, realized_auc_trends
from ..models import (
AutoresearchIteration,
AutoresearchModel,
@@ -68,6 +69,7 @@ from .contracts import (
InvalidTarget,
Iteration,
IterationTrailEntry,
+ LiveTrainingRun,
MaterializedFeatures,
Model,
OnlinePerformance,
@@ -76,6 +78,7 @@ from .contracts import (
PipelineNotFound,
PipelineValidation,
PipelineWrite,
+ RealizedAucPoint,
ResolvedTemplate,
Run,
StoredArtifact,
@@ -106,6 +109,8 @@ MAX_BUNDLE_FILES = 32
HISTORY_LIMIT_MAX = 20
+REALIZED_AUC_TREND_DATES = 14
+
ONLINE_PERFORMANCE_DATES_DEFAULT = 60
ONLINE_PERFORMANCE_DATES_MAX = 180
@@ -142,10 +147,105 @@ def _champion_lift_at_10(champion: AutoresearchModel | None) -> float | None:
return float(lift) if isinstance(lift, int | float) else None
+@frozen
+class _PipelineActivity:
+ champion_realized_auc_trend: list[RealizedAucPoint]
+ people_scored: int | None
+ training_run_count: int
+ experiment_count: int
+ live_training_run: LiveTrainingRun | None
+
+
+def _live_training_run(run: AutoresearchTrainingRun, iterations: list[AutoresearchIteration]) -> LiveTrainingRun:
+ # The run's own counters land only at completion, so progress comes from the live iteration rows.
+ scores = [i.holdout_score for i in iterations if i.holdout_score is not None]
+ return LiveTrainingRun(
+ id=run.id,
+ iteration_budget=run.iteration_budget,
+ experiment_count=len(iterations),
+ best_holdout_score=max(scores) if scores else None,
+ latest_agent_description=iterations[-1].agent_description if iterations else "",
+ )
+
+
+def _pipeline_activity(
+ team_id: int, pipeline_ids: list[UUID], champions: dict[UUID, AutoresearchModel]
+) -> dict[UUID, _PipelineActivity]:
+ """Counts, live training progress and realized AUC trend per pipeline, in a fixed number of queries."""
+ if not pipeline_ids:
+ return {}
+ training_run_counts = dict(
+ AutoresearchTrainingRun.objects.for_team(team_id)
+ .filter(pipeline_id__in=pipeline_ids)
+ .values("pipeline_id")
+ .annotate(n=Count("id"))
+ .values_list("pipeline_id", "n")
+ )
+ experiment_counts = dict(
+ AutoresearchIteration.objects.for_team(team_id)
+ .filter(pipeline_id__in=pipeline_ids)
+ .values("pipeline_id")
+ .annotate(n=Count("id"))
+ .values_list("pipeline_id", "n")
+ )
+ people_scored = dict(
+ AutoresearchRun.objects.for_team(team_id)
+ .filter(
+ pipeline_id__in=pipeline_ids,
+ run_type=AutoresearchRun.RunType.INFERENCE,
+ status=AutoresearchRun.Status.COMPLETED,
+ rows_scored__isnull=False,
+ )
+ .order_by("pipeline_id", F("completed_at").desc(nulls_last=True), "-created_at")
+ .distinct("pipeline_id")
+ .values_list("pipeline_id", "rows_scored")
+ )
+ live_runs = {
+ run.pipeline_id: run
+ for run in AutoresearchTrainingRun.objects.for_team(team_id)
+ .filter(
+ pipeline_id__in=pipeline_ids,
+ status__in=[AutoresearchTrainingRun.Status.PENDING, AutoresearchTrainingRun.Status.RUNNING],
+ )
+ .order_by("pipeline_id", "-created_at")
+ .distinct("pipeline_id")
+ }
+ live_iterations: dict[UUID, list[AutoresearchIteration]] = {}
+ for iteration in (
+ AutoresearchIteration.objects.for_team(team_id)
+ .filter(training_run_id__in=[run.id for run in live_runs.values()])
+ .only("training_run_id", "holdout_score", "agent_description")
+ .order_by("training_run_id", "iteration_number")
+ ):
+ live_iterations.setdefault(iteration.training_run_id, []).append(iteration)
+ trends = realized_auc_trends(
+ team_id,
+ {pipeline_id: champion.id for pipeline_id, champion in champions.items()},
+ dates=REALIZED_AUC_TREND_DATES,
+ )
+ return {
+ pipeline_id: _PipelineActivity(
+ champion_realized_auc_trend=[
+ RealizedAucPoint(prediction_date=d, realized_auc=auc) for d, auc in trends.get(pipeline_id, [])
+ ],
+ people_scored=people_scored.get(pipeline_id),
+ training_run_count=training_run_counts.get(pipeline_id, 0),
+ experiment_count=experiment_counts.get(pipeline_id, 0),
+ live_training_run=(
+ _live_training_run(live_runs[pipeline_id], live_iterations.get(live_runs[pipeline_id].id, []))
+ if pipeline_id in live_runs
+ else None
+ ),
+ )
+ for pipeline_id in pipeline_ids
+ }
+
+
def _pipeline_to_contract(
row: AutoresearchPipeline,
*,
champion: AutoresearchModel | None = None,
+ activity: _PipelineActivity,
) -> Pipeline:
return Pipeline(
id=row.id,
@@ -176,12 +276,18 @@ def _pipeline_to_contract(
champion_realized_auc=champion.realized_score if champion else None,
champion_lift_at_10=_champion_lift_at_10(champion),
champion_is_preliminary=champion.is_preliminary if champion else None,
+ champion_realized_auc_trend=activity.champion_realized_auc_trend,
+ people_scored=activity.people_scored,
+ training_run_count=activity.training_run_count,
+ experiment_count=activity.experiment_count,
+ live_training_run=activity.live_training_run,
)
def _pipeline_with_champion(row: AutoresearchPipeline) -> Pipeline:
champion = row.models.filter(role=AutoresearchModel.Role.CHAMPION).order_by("-created_at").first()
- return _pipeline_to_contract(row, champion=champion)
+ activity = _pipeline_activity(row.team_id, [row.id], {row.id: champion} if champion else {})
+ return _pipeline_to_contract(row, champion=champion, activity=activity[row.id])
def _model_to_contract(row: AutoresearchModel, *, in_shadow_set: bool) -> Model:
@@ -355,19 +461,22 @@ def list_pipelines(team_id: int, *, offset: int, limit: int) -> tuple[list[Pipel
.order_by("-created_at")
)
count = qs.count()
- rows = qs[offset : offset + limit].prefetch_related(
- Prefetch(
- "models",
- queryset=AutoresearchModel.objects.for_team(team_id)
- .filter(role=AutoresearchModel.Role.CHAMPION)
- .order_by("-created_at"),
- to_attr="prefetched_champions",
+ rows = list(
+ qs[offset : offset + limit].prefetch_related(
+ Prefetch(
+ "models",
+ queryset=AutoresearchModel.objects.for_team(team_id)
+ .filter(role=AutoresearchModel.Role.CHAMPION)
+ .order_by("-created_at"),
+ to_attr="prefetched_champions",
+ )
)
)
- pipelines = []
- for row in rows:
- champions: list[AutoresearchModel] = row.prefetched_champions
- pipelines.append(_pipeline_to_contract(row, champion=champions[0] if champions else None))
+ champions: dict[UUID, AutoresearchModel] = {
+ row.id: row.prefetched_champions[0] for row in rows if row.prefetched_champions
+ }
+ activity = _pipeline_activity(team_id, [row.id for row in rows], champions)
+ pipelines = [_pipeline_to_contract(row, champion=champions.get(row.id), activity=activity[row.id]) for row in rows]
return pipelines, count
diff --git a/products/autoresearch/backend/facade/contracts.py b/products/autoresearch/backend/facade/contracts.py
index 8df14aba5bd8..55ab66c3bfec 100644
--- a/products/autoresearch/backend/facade/contracts.py
+++ b/products/autoresearch/backend/facade/contracts.py
@@ -71,6 +71,23 @@ class ArtifactStorageUnavailable(RuntimeError):
# ── Model-backed read contracts ────────────────────────────────────────────
+@dataclass(frozen=True)
+class LiveTrainingRun:
+ """Progress of the pipeline's pending or running training run, read from its live iteration rows."""
+
+ id: UUID
+ iteration_budget: int
+ experiment_count: int
+ best_holdout_score: float | None
+ latest_agent_description: str
+
+
+@dataclass(frozen=True)
+class RealizedAucPoint:
+ prediction_date: date
+ realized_auc: float
+
+
@dataclass(frozen=True, config={"arbitrary_types_allowed": True})
class Pipeline:
"""One prediction pipeline: a target, a population, and a horizon.
@@ -104,6 +121,11 @@ class Pipeline:
champion_realized_auc: float | None
champion_lift_at_10: float | None
champion_is_preliminary: bool | None
+ champion_realized_auc_trend: list[RealizedAucPoint]
+ people_scored: int | None
+ training_run_count: int
+ experiment_count: int
+ live_training_run: LiveTrainingRun | None
@dataclass(frozen=True)
diff --git a/products/autoresearch/backend/presentation/views/serializers.py b/products/autoresearch/backend/presentation/views/serializers.py
index 2cf4fb753052..f73d1228c539 100644
--- a/products/autoresearch/backend/presentation/views/serializers.py
+++ b/products/autoresearch/backend/presentation/views/serializers.py
@@ -18,9 +18,11 @@ from products.autoresearch.backend.facade.contracts import (
AutoresearchConflict,
Iteration,
IterationTrailEntry,
+ LiveTrainingRun,
Model,
Pipeline,
PipelineWrite,
+ RealizedAucPoint,
Run,
Suggestion,
TrainingRun,
@@ -485,6 +487,35 @@ class MetricsBundleField(serializers.JSONField):
# ── Core serializers ------------------------------------------------------
+@extend_schema_serializer(component_name="AutoresearchLiveTrainingRun")
+class LiveTrainingRunSerializer(DataclassSerializer):
+ id = serializers.UUIDField(read_only=True, help_text="Unique UUID of the live training run.")
+ iteration_budget = serializers.IntegerField(read_only=True, help_text="Maximum experiments allowed for this run.")
+ experiment_count = serializers.IntegerField(
+ read_only=True, help_text="Experiments the agent has recorded so far in this run."
+ )
+ best_holdout_score = serializers.FloatField(
+ read_only=True, allow_null=True, help_text="Best holdout AUC so far in this run. Null before any is recorded."
+ )
+ latest_agent_description = serializers.CharField(
+ read_only=True, allow_blank=True, help_text="The agent's rationale for its newest experiment."
+ )
+
+ class Meta:
+ dataclass = LiveTrainingRun
+ fields = ["id", "iteration_budget", "experiment_count", "best_holdout_score", "latest_agent_description"]
+
+
+@extend_schema_serializer(component_name="AutoresearchRealizedAucPoint")
+class RealizedAucPointSerializer(DataclassSerializer):
+ prediction_date = serializers.DateField(read_only=True, help_text="Validated prediction date.")
+ realized_auc = serializers.FloatField(read_only=True, help_text="Realized AUC on that date.")
+
+ class Meta:
+ dataclass = RealizedAucPoint
+ fields = ["prediction_date", "realized_auc"]
+
+
@extend_schema_serializer(component_name="AutoresearchPipeline")
# Read representation of a pipeline. Every field is declared explicitly so the generated
# AutoresearchPipeline component keeps the shape it had when this was a ModelSerializer.
@@ -579,6 +610,25 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
allow_null=True,
help_text="True while the current champion model has no realized AUC yet. Null when the pipeline has no champion.",
)
+ champion_realized_auc_trend = RealizedAucPointSerializer(
+ many=True,
+ read_only=True,
+ help_text="Realized AUC of the current champion on its newest 14 validated prediction dates, oldest first.",
+ )
+ people_scored = serializers.IntegerField(
+ read_only=True,
+ allow_null=True,
+ help_text="People scored by the most recent completed inference run. Null before the first scoring run.",
+ )
+ training_run_count = serializers.IntegerField(read_only=True, help_text="Training runs started for this pipeline.")
+ experiment_count = serializers.IntegerField(
+ read_only=True, help_text="Experiments (iterations) recorded across every training run."
+ )
+ live_training_run = LiveTrainingRunSerializer(
+ read_only=True,
+ allow_null=True,
+ help_text="Progress of the pending or running training run. Null when no run is live.",
+ )
class Meta:
dataclass = Pipeline
@@ -607,6 +657,11 @@ class AutoresearchPipelineSerializer(DataclassSerializer):
"champion_realized_auc",
"champion_lift_at_10",
"champion_is_preliminary",
+ "champion_realized_auc_trend",
+ "people_scored",
+ "training_run_count",
+ "experiment_count",
+ "live_training_run",
]
diff --git a/products/autoresearch/backend/tests/test_api.py b/products/autoresearch/backend/tests/test_api.py
index 5d9a19234a13..5440d0143bc2 100644
--- a/products/autoresearch/backend/tests/test_api.py
+++ b/products/autoresearch/backend/tests/test_api.py
@@ -213,6 +213,49 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
metrics={"realized": {"n_positive": n_positive, "lift_at_10": 0.0, "prediction_date": "2026-01-02"}},
)
self._make_pipeline(name="Untrained")
+ champion = AutoresearchModel.objects.get(pipeline=validated, role=AutoresearchModel.Role.CHAMPION)
+ finished = AutoresearchTrainingRun.objects.create(pipeline=validated, status="completed", iteration_budget=5)
+ AutoresearchIteration.objects.create(
+ pipeline=validated,
+ training_run=finished,
+ iteration_number=0,
+ recipe_hash="a",
+ recipe_snapshot={},
+ status="kept",
+ )
+ now = django_timezone.now()
+ for rows_scored, minutes_ago in [(100, 60), (250, 5)]:
+ AutoresearchRun.objects.create(
+ pipeline=validated,
+ run_type=AutoresearchRun.RunType.INFERENCE,
+ status="completed",
+ rows_scored=rows_scored,
+ completed_at=now - timedelta(minutes=minutes_ago),
+ )
+ for prediction_date, auc, minutes_ago in [
+ ("2026-01-02", 0.7, 30),
+ ("2026-01-01", 0.6, 20),
+ ("2026-01-02", 0.75, 10),
+ ]:
+ AutoresearchRun.objects.create(
+ pipeline=validated,
+ run_type=AutoresearchRun.RunType.VALIDATION,
+ status="completed",
+ completed_at=now - timedelta(minutes=minutes_ago),
+ metrics={"prediction_date": prediction_date, "per_model": {str(champion.pk): {"realized_auc": auc}}},
+ )
+ live = AutoresearchTrainingRun.objects.create(pipeline=preliminary, status="running", iteration_budget=8)
+ for number, holdout, description in [(0, 0.72, "baseline"), (1, 0.69, "try fewer features")]:
+ AutoresearchIteration.objects.create(
+ pipeline=preliminary,
+ training_run=live,
+ iteration_number=number,
+ recipe_hash=f"r{number}",
+ recipe_snapshot={},
+ holdout_score=holdout,
+ status="kept" if number == 0 else "discarded",
+ agent_description=description,
+ )
with CaptureQueriesContext(connection) as queries:
resp = self.client.get(f"{self.base_url}/")
@@ -220,6 +263,55 @@ class TestAutoresearchPipelineAPI(TeamScopedTestMixin, APIBaseTest):
assert resp.status_code == status.HTTP_200_OK
assert sum("autoresearchmodel" in q["sql"].lower() for q in queries.captured_queries) == 1
by_name = {row["name"]: row for row in resp.json()["results"]}
+ assert {
+ name: (
+ row["people_scored"],
+ row["training_run_count"],
+ row["experiment_count"],
+ row["champion_realized_auc_trend"],
+ row["live_training_run"] and {k: v for k, v in row["live_training_run"].items() if k != "id"},
+ )
+ for name, row in by_name.items()
+ } == {
+ "Validated": (
+ 250,
+ 1,
+ 1,
+ [
+ {"prediction_date": "2026-01-01", "realized_auc": 0.6},
+ {"prediction_date": "2026-01-02", "realized_auc": 0.75},
+ ],
+ None,
+ ),
+ "Preliminary": (
+ None,
+ 1,
+ 2,
+ [],
+ {
+ "iteration_budget": 8,
+ "experiment_count": 2,
+ "best_holdout_score": 0.72,
+ "latest_agent_description": "try fewer features",
+ },
+ ),
+ "No positives": (None, 0, 0, [], None),
+ "Zero lift": (None, 0, 0, [], None),
+ "Untrained": (None, 0, 0, [], None),
+ }
+
+ busy = self._make_pipeline(name="Busy")
+ busy_run = AutoresearchTrainingRun.objects.create(pipeline=busy, status="running", iteration_budget=3)
+ AutoresearchIteration.objects.create(
+ pipeline=busy, training_run=busy_run, iteration_number=0, recipe_hash="b", recipe_snapshot={}, status="kept"
+ )
+ with CaptureQueriesContext(connection) as more_queries:
+ self.client.get(f"{self.base_url}/")
+
+ def autoresearch_queries(captured: CaptureQueriesContext) -> int:
+ return sum('"autoresearch_' in q["sql"] for q in captured.captured_queries)
+
+ assert autoresearch_queries(more_queries) == autoresearch_queries(queries)
assert {
name: (
row["champion_holdout_auc"],
diff --git a/products/autoresearch/frontend/AGENTS.md b/products/autoresearch/frontend/AGENTS.md
index 22a56c5110bd..6f157565e4fa 100644
--- a/products/autoresearch/frontend/AGENTS.md
+++ b/products/autoresearch/frontend/AGENTS.md
@@ -6,20 +6,22 @@ The product is mostly a backend, and the UI is deliberately thin — it reads st
## What lives here
-| 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`. |
+| File | Scene / role |
+| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
+| `AutoresearchScene.tsx` | `/autoresearch` — the model list: a container-query grid of model cards and the "New model" entry point. |
+| `AutoresearchModelCard.tsx` | One model card: the question as title, a state body (scored, training, draft), and counts. `ModelCardMenu.tsx` holds pause, resume, delete. |
+| `pipelineQuestion.ts` | The model's question in plain words ("Who will do X in the next N days?"), shared by the list cards and the detail header. |
+| `AutoresearchNewScene.tsx` | `/autoresearch/new` — the create form. |
+| `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`.
@@ -44,7 +46,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`, and `autoresearch model action failed` (with `action`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
+- Usage events are part of the API: renaming one breaks every insight built on it. The list logic captures `autoresearch model list viewed`, `autoresearch model list load failed`, `autoresearch model deleted` / `paused` / `resumed`, `autoresearch model training started` (with `source: 'list'` from a card), `autoresearch model card clicked`, and `autoresearch model action failed` (with `action`); buttons carry a `data-attr` for autocapture. Extend the same names when you add a scene.
## Copy
diff --git a/products/autoresearch/frontend/AutoresearchModelCard.tsx b/products/autoresearch/frontend/AutoresearchModelCard.tsx
new file mode 100644
index 000000000000..5e4a9181e098
--- /dev/null
+++ b/products/autoresearch/frontend/AutoresearchModelCard.tsx
@@ -0,0 +1,160 @@
+import { useActions, useValues } from 'kea'
+
+import { LemonButton, LemonCard, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { dayjs } from 'lib/dayjs'
+import { LemonProgress } from 'lib/lemon-ui/LemonProgress'
+import { humanFriendlyNumber } from 'lib/utils/numbers'
+import { pluralize } from 'lib/utils/strings'
+import { urls } from 'scenes/urls'
+
+import { autoresearchLogic } from './autoresearchLogic'
+import { AutoresearchLiveTrainingRunApi, AutoresearchPipelineApi } from './generated/api.schemas'
+import { ModelCardMenu } from './ModelCardMenu'
+import { modelCardState } from './modelCardState'
+import { modelQuality } from './modelQuality'
+import { ModelQualityTag } from './ModelQualityTag'
+import { MetricSparkline } from './pipeline/MetricSparkline'
+import { pipelineQuestion } from './pipelineQuestion'
+import { PipelineStatusTag } from './PipelineStatusTag'
+
+function ScoredBody({ pipeline }: { pipeline: AutoresearchPipelineApi }): JSX.Element {
+ const quality = modelQuality({
+ holdoutAuc: pipeline.champion_holdout_auc,
+ realizedAuc: pipeline.champion_realized_auc,
+ liftAt10: pipeline.champion_lift_at_10,
+ isPreliminary: pipeline.champion_is_preliminary,
+ target: pipeline.target_event,
+ })
+ if (!quality) {
+ return <span className="text-secondary">No quality measured yet</span>
+ }
+ const trend = pipeline.champion_realized_auc_trend.map((point) => ({
+ date: point.prediction_date,
+ value: point.realized_auc,
+ }))
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <div className="flex flex-col gap-1 min-w-0">
+ <div className="flex items-center gap-1">
+ <ModelQualityTag
+ quality={quality}
+ holdoutAuc={pipeline.champion_holdout_auc}
+ realizedAuc={pipeline.champion_realized_auc}
+ />
+ <span className="text-xs text-secondary">{quality.basis}</span>
+ </div>
+ <span className="text-xs text-secondary break-words">{quality.sentence}</span>
+ </div>
+ {trend.length > 1 && (
+ <Tooltip title="Realized AUC on recent checked dates">
+ <span className="shrink-0">
+ <MetricSparkline points={trend} width={96} height={32} />
+ </span>
+ </Tooltip>
+ )}
+ </div>
+ )
+}
+
+function TrainingBody({ liveRun }: { liveRun: AutoresearchLiveTrainingRunApi | null }): JSX.Element {
+ if (!liveRun) {
+ return <span className="text-secondary">Starting the first training run…</span>
+ }
+ return (
+ <div className="flex flex-col gap-1">
+ <div className="flex items-center justify-between gap-2 text-xs">
+ <span className="font-semibold">
+ {`Experiment ${liveRun.experiment_count} of ${liveRun.iteration_budget}`}
+ </span>
+ {liveRun.best_holdout_score != null && (
+ <span className="text-secondary">{`Best AUC so far ${liveRun.best_holdout_score.toFixed(2)}`}</span>
+ )}
+ </div>
+ <LemonProgress percent={(liveRun.experiment_count / liveRun.iteration_budget) * 100} />
+ {liveRun.latest_agent_description && (
+ <span className="text-xs text-secondary truncate" title={liveRun.latest_agent_description}>
+ {liveRun.latest_agent_description}
+ </span>
+ )}
+ </div>
+ )
+}
+
+function DraftBody({ pipeline }: { pipeline: AutoresearchPipelineApi }): JSX.Element {
+ const { mutatingPipelineIds } = useValues(autoresearchLogic)
+ const { startTraining } = useActions(autoresearchLogic)
+ const mutating = !!mutatingPipelineIds[pipeline.id]
+ return (
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-secondary">Not trained yet</span>
+ <LemonButton
+ type="primary"
+ size="small"
+ loading={mutating}
+ disabledReason={mutating ? 'Another change is still saving' : undefined}
+ onClick={() => startTraining(pipeline)}
+ data-attr="autoresearch-model-card-train"
+ >
+ Start training
+ </LemonButton>
+ </div>
+ )
+}
+
+export function AutoresearchModelCard({ pipeline }: { pipeline: AutoresearchPipelineApi }): JSX.Element {
+ const { modelCardOpened } = useActions(autoresearchLogic)
+ const state = modelCardState(pipeline)
+ return (
+ <LemonCard hoverEffect={false} className="flex flex-col gap-3 p-4 min-w-0">
+ <div className="flex items-center justify-between gap-2">
+ <PipelineStatusTag status={pipeline.status} />
+ <div className="flex items-center gap-1">
+ {pipeline.cadence_days != null && (
+ <span className="text-xs text-secondary">
+ {pipeline.cadence_days === 1
+ ? 'Scores daily'
+ : `Scores every ${pipeline.cadence_days} days`}
+ </span>
+ )}
+ <ModelCardMenu pipeline={pipeline} />
+ </div>
+ </div>
+ <div className="flex flex-col gap-0.5 min-w-0">
+ <Link
+ to={urls.autoresearchPipeline(pipeline.id)}
+ onClick={() => modelCardOpened(pipeline.id)}
+ className="font-semibold text-base break-words"
+ data-attr="autoresearch-model-card"
+ >
+ {pipelineQuestion(pipeline)}
+ </Link>
+ <span className="text-xs text-secondary truncate">
+ {pipeline.name} · {pipeline.target_event}
+ </span>
+ </div>
+ <div className="rounded border bg-surface-secondary p-3">
+ {state === 'training' ? (
+ <TrainingBody liveRun={pipeline.live_training_run} />
+ ) : state === 'draft' ? (
+ <DraftBody pipeline={pipeline} />
+ ) : (
+ <ScoredBody pipeline={pipeline} />
+ )}
+ </div>
+ <div className="flex flex-wrap items-center justify-between gap-x-3 gap-y-1 text-xs text-secondary mt-auto">
+ <span>
+ {[
+ pipeline.people_scored != null
+ ? `${humanFriendlyNumber(pipeline.people_scored)} people scored`
+ : 'Not scored yet',
+ pipeline.last_scored_at ? dayjs(pipeline.last_scored_at).fromNow() : null,
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </span>
+ <span>{`${pluralize(pipeline.training_run_count, 'run')} · ${pluralize(pipeline.experiment_count, 'experiment')}`}</span>
+ </div>
+ </LemonCard>
+ )
+}
diff --git a/products/autoresearch/frontend/AutoresearchScene.tsx b/products/autoresearch/frontend/AutoresearchScene.tsx
index 033a1da3b79b..707ee9a6ae64 100644
--- a/products/autoresearch/frontend/AutoresearchScene.tsx
+++ b/products/autoresearch/frontend/AutoresearchScene.tsx
@@ -1,14 +1,10 @@
import { useActions, useValues } from 'kea'
-import { IconPause, IconPlay, IconPlus, IconTrash } from '@posthog/icons'
-import { LemonBanner, LemonButton, LemonDialog, LemonTable, LemonTableColumn } from '@posthog/lemon-ui'
+import { IconPlus } from '@posthog/icons'
+import { LemonBanner, LemonButton, LemonSkeleton } from '@posthog/lemon-ui'
import { NotFound } from 'lib/components/NotFound'
-import { dayjs } from 'lib/dayjs'
import { useFeatureFlag } from 'lib/hooks/useFeatureFlag'
-import { More } from 'lib/lemon-ui/LemonButton/More'
-import { createdByColumn } from 'lib/lemon-ui/LemonTable/columnUtils'
-import { LemonTableLink } from 'lib/lemon-ui/LemonTable/LemonTableLink'
import { sceneConfigurations } from 'scenes/scenes'
import { Scene, SceneExport } from 'scenes/sceneTypes'
import { urls } from 'scenes/urls'
@@ -18,11 +14,8 @@ import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'
import { ProductKey } from '~/queries/schema/schema-general'
import { autoresearchLogic } from './autoresearchLogic'
+import { AutoresearchModelCard } from './AutoresearchModelCard'
import { autoresearchEmptyState } from './emptyState/autoresearchEmptyState'
-import { AutoresearchPipelineApi } from './generated/api.schemas'
-import { MODEL_QUALITY_THRESHOLDS, modelQuality } from './modelQuality'
-import { ModelQualityTag } from './ModelQualityTag'
-import { PipelineStatusTag } from './PipelineStatusTag'
export const scene: SceneExport = {
component: AutoresearchScene,
@@ -33,148 +26,13 @@ export const scene: SceneExport = {
export function AutoresearchScene(): JSX.Element {
const isEnabled = useFeatureFlag('AUTORESEARCH')
- const { pipelines, pipelinesLoading, pipelinesLoadFailed, mutatingPipelineIds } = useValues(autoresearchLogic)
- const { deletePipeline, pausePipeline, resumePipeline, loadPipelines } = useActions(autoresearchLogic)
+ const { pipelines, pipelinesLoading, pipelinesLoadFailed } = useValues(autoresearchLogic)
+ const { loadPipelines } = useActions(autoresearchLogic)
if (!isEnabled) {
return <NotFound object="Autoresearch" caption="This feature is not enabled for your project." />
}
- const columns: LemonTableColumn<AutoresearchPipelineApi, keyof AutoresearchPipelineApi | undefined>[] = [
- {
- title: 'Name',
- sticky: true,
- render: (_: unknown, record: AutoresearchPipelineApi) => (
- <LemonTableLink
- to={urls.autoresearchPipeline(record.id)}
- title={record.name}
- description={record.description}
- />
- ),
- },
- {
- title: 'Target',
- dataIndex: 'target_event',
- },
- {
- title: 'Prediction horizon',
- dataIndex: 'horizon_days',
- render: (_, record: AutoresearchPipelineApi) => (record.horizon_days ? `${record.horizon_days}d` : '—'),
- },
- {
- title: 'Status',
- dataIndex: 'status',
- render: (_, record: AutoresearchPipelineApi) => <PipelineStatusTag status={record.status} />,
- },
- createdByColumn() as unknown as LemonTableColumn<
- AutoresearchPipelineApi,
- keyof AutoresearchPipelineApi | undefined
- >,
- {
- title: 'Quality',
- tooltip: `How well the current champion model ranks people. Strong is an AUC of ${MODEL_QUALITY_THRESHOLDS.strong.toFixed(2)} or more, Fair is ${MODEL_QUALITY_THRESHOLDS.fair.toFixed(2)} to ${MODEL_QUALITY_THRESHOLDS.strong.toFixed(2)}, and Weak is below ${MODEL_QUALITY_THRESHOLDS.fair.toFixed(2)}. Realized AUC from real outcomes is used when it exists, otherwise holdout AUC from test data.`,
- render: (_, record: AutoresearchPipelineApi) => {
- const quality = modelQuality({
- holdoutAuc: record.champion_holdout_auc,
- realizedAuc: record.champion_realized_auc,
- liftAt10: record.champion_lift_at_10,
- isPreliminary: record.champion_is_preliminary,
- target: record.target_event,
- })
- if (!quality) {
- return <span className="text-secondary">—</span>
- }
- return (
- <div className="flex flex-col gap-0.5">
- <div className="flex items-center gap-1">
- <ModelQualityTag
- quality={quality}
- holdoutAuc={record.champion_holdout_auc}
- realizedAuc={record.champion_realized_auc}
- />
- <span className="text-xs text-secondary">{quality.basis}</span>
- </div>
- <span className="text-xs text-secondary">{quality.sentence}</span>
- </div>
- )
- },
- },
- {
- title: 'Last scored',
- dataIndex: 'last_scored_at',
- render: (_, record: AutoresearchPipelineApi) =>
- record.last_scored_at ? dayjs(record.last_scored_at).fromNow() : 'Never',
- },
- {
- title: '',
- width: 0,
- render: (_: unknown, record: AutoresearchPipelineApi) => {
- const canPause = record.status === 'running'
- const canResume = record.status === 'paused'
- const mutating = !!mutatingPipelineIds[record.id]
- return (
- <More
- data-attr="autoresearch-model-more"
- overlay={
- <>
- {canPause && (
- <LemonButton
- fullWidth
- icon={<IconPause />}
- loading={mutating}
- disabledReason={mutating ? 'Another change is still saving' : undefined}
- onClick={() => pausePipeline(record)}
- >
- Pause scheduled scoring
- </LemonButton>
- )}
- {canResume && (
- <LemonButton
- fullWidth
- icon={<IconPlay />}
- loading={mutating}
- disabledReason={mutating ? 'Another change is still saving' : undefined}
- onClick={() => resumePipeline(record)}
- >
- Resume scheduled scoring
- </LemonButton>
- )}
- <LemonButton
- fullWidth
- icon={<IconTrash />}
- status="danger"
- loading={mutating}
- disabledReason={
- mutating
- ? 'Another change is still saving'
- : record.status === 'bootstrapping'
- ? 'Wait for the first training run to finish'
- : undefined
- }
- onClick={() => {
- LemonDialog.open({
- title: `Delete "${record.name}"?`,
- description:
- 'The model, its training runs, and prediction metadata will be removed. Emitted autoresearch_prediction events stay in the events stream, and the prediction person property stays on each scored person.',
- primaryButton: {
- children: 'Delete',
- status: 'danger',
- onClick: () => deletePipeline(record.id, record.name),
- },
- secondaryButton: { children: 'Cancel' },
- })
- }}
- >
- Delete model
- </LemonButton>
- </>
- }
- />
- )
- },
- },
- ]
-
return (
<SceneContent>
<SceneTitleSection
@@ -209,7 +67,18 @@ export function AutoresearchScene(): JSX.Element {
</LemonBanner>
)}
{!(pipelinesLoadFailed && pipelines.length === 0) && (
- <LemonTable loading={pipelinesLoading} columns={columns} dataSource={pipelines} rowKey="id" />
+ <div className="@container">
+ <div className="grid grid-cols-1 @2xl:grid-cols-2 @5xl:grid-cols-3 gap-4">
+ {pipelinesLoading && pipelines.length === 0
+ ? Array.from({ length: 3 }, (_, i) => <LemonSkeleton key={i} className="h-48" />)
+ : pipelines.map((pipeline) => (
+ <AutoresearchModelCard key={pipeline.id} pipeline={pipeline} />
+ ))}
+ </div>
+ {!pipelinesLoading && pipelines.length === 0 && (
+ <p className="text-secondary">No models yet. Create one to start predicting.</p>
+ )}
+ </div>
)}
</SceneContent>
)
diff --git a/products/autoresearch/frontend/ModelCardMenu.tsx b/products/autoresearch/frontend/ModelCardMenu.tsx
new file mode 100644
index 000000000000..bcc0e2aeea92
--- /dev/null
+++ b/products/autoresearch/frontend/ModelCardMenu.tsx
@@ -0,0 +1,75 @@
+import { useActions, useValues } from 'kea'
+
+import { IconPause, IconPlay, IconTrash } from '@posthog/icons'
+import { LemonButton, LemonDialog } from '@posthog/lemon-ui'
+
+import { More } from 'lib/lemon-ui/LemonButton/More'
+
+import { autoresearchLogic } from './autoresearchLogic'
+import { AutoresearchPipelineApi } from './generated/api.schemas'
+
+export function ModelCardMenu({ pipeline }: { pipeline: AutoresearchPipelineApi }): JSX.Element {
+ const { mutatingPipelineIds } = useValues(autoresearchLogic)
+ const { deletePipeline, pausePipeline, resumePipeline } = useActions(autoresearchLogic)
+ const mutating = !!mutatingPipelineIds[pipeline.id]
+ return (
+ <More
+ size="xsmall"
+ data-attr="autoresearch-model-more"
+ overlay={
+ <>
+ {pipeline.status === 'running' && (
+ <LemonButton
+ fullWidth
+ icon={<IconPause />}
+ loading={mutating}
+ disabledReason={mutating ? 'Another change is still saving' : undefined}
+ onClick={() => pausePipeline(pipeline)}
+ >
+ Pause scheduled scoring
+ </LemonButton>
+ )}
+ {pipeline.status === 'paused' && (
+ <LemonButton
+ fullWidth
+ icon={<IconPlay />}
+ loading={mutating}
+ disabledReason={mutating ? 'Another change is still saving' : undefined}
+ onClick={() => resumePipeline(pipeline)}
+ >
+ Resume scheduled scoring
+ </LemonButton>
+ )}
+ <LemonButton
+ fullWidth
+ icon={<IconTrash />}
+ status="danger"
+ loading={mutating}
+ disabledReason={
+ mutating
+ ? 'Another change is still saving'
+ : pipeline.live_training_run || pipeline.status === 'bootstrapping'
+ ? 'Wait for the training run to finish'
+ : undefined
+ }
+ onClick={() => {
+ LemonDialog.open({
+ title: `Delete "${pipeline.name}"?`,
+ description:
+ 'The model, its training runs, and prediction metadata will be removed. Emitted autoresearch_prediction events stay in the events stream, and the prediction person property stays on each scored person.',
+ primaryButton: {
+ children: 'Delete',
+ status: 'danger',
+ onClick: () => deletePipeline(pipeline.id, pipeline.name),
+ },
+ secondaryButton: { children: 'Cancel' },
+ })
+ }}
+ >
+ Delete model
+ </LemonButton>
+ </>
+ }
+ />
+ )
+}
diff --git a/products/autoresearch/frontend/ModelQualityTag.tsx b/products/autoresearch/frontend/ModelQualityTag.tsx
index b2f3b15a15c5..4ff4b402f662 100644
--- a/products/autoresearch/frontend/ModelQualityTag.tsx
+++ b/products/autoresearch/frontend/ModelQualityTag.tsx
@@ -1,6 +1,6 @@
import { LemonTag, LemonTagType, Tooltip } from '@posthog/lemon-ui'
-import { ModelQuality, ModelQualityVerdict } from './modelQuality'
+import { MODEL_QUALITY_THRESHOLDS, ModelQuality, ModelQualityVerdict } from './modelQuality'
const VERDICT_TAG_TYPE: Record<ModelQualityVerdict, LemonTagType> = {
Strong: 'success',
@@ -34,6 +34,11 @@ export function ModelQualityTag({
AUC shows how well the model ranks people who do the target above people who don't. 0.5 is
random and 1.0 is perfect.
</div>
+ <div>
+ Strong is {MODEL_QUALITY_THRESHOLDS.strong.toFixed(2)} or more, Fair is{' '}
+ {MODEL_QUALITY_THRESHOLDS.fair.toFixed(2)} to {MODEL_QUALITY_THRESHOLDS.strong.toFixed(2)}, and
+ Weak is below {MODEL_QUALITY_THRESHOLDS.fair.toFixed(2)}.
+ </div>
<div className="text-xs">
Holdout AUC: {formatAuc(holdoutAuc)}. Realized AUC: {formatAuc(realizedAuc)}.
</div>
diff --git a/products/autoresearch/frontend/autoresearchLogic.test.ts b/products/autoresearch/frontend/autoresearchLogic.test.ts
index af0ff1553a48..b96e0bec4d25 100644
--- a/products/autoresearch/frontend/autoresearchLogic.test.ts
+++ b/products/autoresearch/frontend/autoresearchLogic.test.ts
@@ -15,6 +15,7 @@ import {
autoresearchList,
autoresearchPauseCreate,
autoresearchResumeCreate,
+ autoresearchTrainCreate,
} from './generated/api'
import { AutoresearchPipelineApi } from './generated/api.schemas'
@@ -23,6 +24,7 @@ jest.mock('./generated/api', () => ({
autoresearchDestroy: jest.fn(),
autoresearchPauseCreate: jest.fn(),
autoresearchResumeCreate: jest.fn(),
+ autoresearchTrainCreate: jest.fn(),
}))
const mockList = autoresearchList as jest.Mock
@@ -103,6 +105,7 @@ describe('autoresearchLogic', () => {
['deletePipeline', autoresearchDestroy],
['pausePipeline', autoresearchPauseCreate],
['resumePipeline', autoresearchResumeCreate],
+ ['startTraining', autoresearchTrainCreate],
] as const)('sends one %s request while the first is in flight', async (action, apiCall) => {
mockList.mockResolvedValue({ results: [] })
;(apiCall as jest.Mock).mockReturnValue(new Promise(() => {}))
diff --git a/products/autoresearch/frontend/autoresearchLogic.ts b/products/autoresearch/frontend/autoresearchLogic.ts
index 290beeac3a08..eafeca34bda0 100644
--- a/products/autoresearch/frontend/autoresearchLogic.ts
+++ b/products/autoresearch/frontend/autoresearchLogic.ts
@@ -19,6 +19,7 @@ import {
autoresearchList,
autoresearchPauseCreate,
autoresearchResumeCreate,
+ autoresearchTrainCreate,
} from './generated/api'
import { AutoresearchPipelineApi } from './generated/api.schemas'
@@ -74,6 +75,9 @@ export interface autoresearchLogicActions {
pipelines: AutoresearchPipelineApi[]
payload?: void
}
+ modelCardOpened: (id: string) => {
+ id: string
+ }
pausePipeline: (pipeline: AutoresearchPipelineApi) => {
pipeline: AutoresearchPipelineApi
}
@@ -93,6 +97,9 @@ export interface autoresearchLogicActions {
id: string
mutating: boolean
}
+ startTraining: (pipeline: AutoresearchPipelineApi) => {
+ pipeline: AutoresearchPipelineApi
+ }
}
export type autoresearchLogicType = MakeLogicType<autoresearchLogicValues, autoresearchLogicActions>
@@ -121,6 +128,8 @@ export const autoresearchLogic = kea<autoresearchLogicType>([
deletePipeline: (id: string, name: string) => ({ id, name }),
pausePipeline: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
resumePipeline: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
+ startTraining: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
+ modelCardOpened: (id: string) => ({ id }),
setPipelineMutating: (id: string, mutating: boolean) => ({ id, mutating }),
pipelineUpdated: (pipeline: AutoresearchPipelineApi) => ({ pipeline }),
pipelineRemoved: (id: string) => ({ id }),
@@ -266,6 +275,26 @@ export const autoresearchLogic = kea<autoresearchLogicType>([
actions.setPipelineMutating(pipeline.id, false)
}
},
+ startTraining: async ({ pipeline }: { pipeline: AutoresearchPipelineApi }) => {
+ if (!values.currentTeamId || values.mutatingPipelineIds[pipeline.id]) {
+ return
+ }
+ actions.setPipelineMutating(pipeline.id, true)
+ try {
+ await autoresearchTrainCreate(String(values.currentTeamId), pipeline.id)
+ posthog.capture('autoresearch model training started', { pipeline_id: pipeline.id, source: 'list' })
+ lemonToast.success(`Started training "${pipeline.name}"`)
+ actions.loadPipelines()
+ } catch (error: any) {
+ posthog.capture('autoresearch model action failed', { action: 'train', pipeline_id: pipeline.id })
+ lemonToast.error(error?.detail ?? error?.data?.detail ?? 'Failed to start training')
+ } finally {
+ actions.setPipelineMutating(pipeline.id, false)
+ }
+ },
+ modelCardOpened: ({ id }: { id: string }) => {
+ posthog.capture('autoresearch model card clicked', { pipeline_id: id })
+ },
})),
urlToAction(({ actions, values }) => ({
// Reload whenever the list route is entered — the scene logic can stay mounted across
diff --git a/products/autoresearch/frontend/generated/api.schemas.ts b/products/autoresearch/frontend/generated/api.schemas.ts
index 890906a52d25..795307688ec1 100644
--- a/products/autoresearch/frontend/generated/api.schemas.ts
+++ b/products/autoresearch/frontend/generated/api.schemas.ts
@@ -84,6 +84,29 @@ export interface UserBasicApi {
role_at_organization?: RoleAtOrganizationEnumApi | BlankEnumApi | null
}
+export interface AutoresearchRealizedAucPointApi {
+ /** Validated prediction date. */
+ readonly prediction_date: string
+ /** Realized AUC on that date. */
+ readonly realized_auc: number
+}
+
+export interface AutoresearchLiveTrainingRunApi {
+ /** Unique UUID of the live training run. */
+ readonly id: string
+ /** Maximum experiments allowed for this run. */
+ readonly iteration_budget: number
+ /** Experiments the agent has recorded so far in this run. */
+ readonly experiment_count: number
+ /**
+ * Best holdout AUC so far in this run. Null before any is recorded.
+ * @nullable
+ */
+ readonly best_holdout_score: number | null
+ /** The agent's rationale for its newest experiment. */
+ readonly latest_agent_description: string
+}
+
/**
* Resolved target definition: {"type": "event"} or {"type": "action", "action_id": N}.
*/
@@ -210,6 +233,19 @@ export interface AutoresearchPipelineApi {
* @nullable
*/
readonly champion_is_preliminary: boolean | null
+ /** Realized AUC of the current champion on its newest 14 validated prediction dates, oldest first. */
+ readonly champion_realized_auc_trend: readonly AutoresearchRealizedAucPointApi[]
+ /**
+ * People scored by the most recent completed inference run. Null before the first scoring run.
+ * @nullable
+ */
+ readonly people_scored: number | null
+ /** Training runs started for this pipeline. */
+ readonly training_run_count: number
+ /** Experiments (iterations) recorded across every training run. */
+ readonly experiment_count: number
+ /** Progress of the pending or running training run. Null when no run is live. */
+ readonly live_training_run: AutoresearchLiveTrainingRunApi | null
}
export interface PaginatedAutoresearchPipelineListApi {
diff --git a/products/autoresearch/frontend/modelCardState.test.ts b/products/autoresearch/frontend/modelCardState.test.ts
new file mode 100644
index 000000000000..ed643d0461f7
--- /dev/null
+++ b/products/autoresearch/frontend/modelCardState.test.ts
@@ -0,0 +1,23 @@
+import { AutoresearchPipelineApi } from './generated/api.schemas'
+import { modelCardState } from './modelCardState'
+
+describe('modelCardState', () => {
+ const liveRun: AutoresearchPipelineApi['live_training_run'] = {
+ id: 'run-1',
+ iteration_budget: 8,
+ experiment_count: 2,
+ best_holdout_score: 0.72,
+ latest_agent_description: 'baseline',
+ }
+
+ test.each([
+ { status: 'draft' as const, live: false, expected: 'draft' },
+ { status: 'draft' as const, live: true, expected: 'training' },
+ { status: 'bootstrapping' as const, live: false, expected: 'training' },
+ { status: 'running' as const, live: true, expected: 'training' },
+ { status: 'running' as const, live: false, expected: 'scored' },
+ { status: 'paused' as const, live: false, expected: 'scored' },
+ ])('$status with a live run: $live is $expected', ({ status, live, expected }) => {
+ expect(modelCardState({ status, live_training_run: live ? liveRun : null })).toEqual(expected)
+ })
+})
diff --git a/products/autoresearch/frontend/modelCardState.ts b/products/autoresearch/frontend/modelCardState.ts
new file mode 100644
index 000000000000..5c364ed1a9b9
--- /dev/null
+++ b/products/autoresearch/frontend/modelCardState.ts
@@ -0,0 +1,14 @@
+import { AutoresearchPipelineApi } from './generated/api.schemas'
+
+export type ModelCardState = 'training' | 'draft' | 'scored'
+
+/** A live training run wins over the status, so a retrain of a live model shows its progress. */
+export function modelCardState({
+ status,
+ live_training_run,
+}: Pick<AutoresearchPipelineApi, 'status' | 'live_training_run'>): ModelCardState {
+ if (live_training_run || status === 'bootstrapping') {
+ return 'training'
+ }
+ return status === 'draft' ? 'draft' : 'scored'
+}
diff --git a/products/autoresearch/frontend/pipeline/MetricSparkline.tsx b/products/autoresearch/frontend/pipeline/MetricSparkline.tsx
index 1dcab3f5a7e0..d983084d9f71 100644
--- a/products/autoresearch/frontend/pipeline/MetricSparkline.tsx
+++ b/products/autoresearch/frontend/pipeline/MetricSparkline.tsx
@@ -4,17 +4,19 @@ export function MetricSparkline({
color = 'var(--success)',
floor,
ceil,
+ width = 280,
+ height = 56,
}: {
points: { date: string; value: number }[]
color?: string
floor?: number
ceil?: number
+ width?: number
+ height?: 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] : []))
diff --git a/products/autoresearch/frontend/pipelineQuestion.test.ts b/products/autoresearch/frontend/pipelineQuestion.test.ts
new file mode 100644
index 000000000000..ae3ac487873f
--- /dev/null
+++ b/products/autoresearch/frontend/pipelineQuestion.test.ts
@@ -0,0 +1,11 @@
+import { pipelineQuestion } from './pipelineQuestion'
+
+describe('pipelineQuestion', () => {
+ test.each([
+ { horizon_days: 30, expected: 'Who will do file_shared in the next 30 days?' },
+ { horizon_days: 1, expected: 'Who will do file_shared in the next day?' },
+ { horizon_days: undefined, expected: 'Who will do file_shared?' },
+ ])('horizon $horizon_days', ({ horizon_days, expected }) => {
+ expect(pipelineQuestion({ target_event: 'file_shared', horizon_days })).toEqual(expected)
+ })
+})
diff --git a/products/autoresearch/frontend/pipelineQuestion.ts b/products/autoresearch/frontend/pipelineQuestion.ts
new file mode 100644
index 000000000000..ff92ee564e8d
--- /dev/null
+++ b/products/autoresearch/frontend/pipelineQuestion.ts
@@ -0,0 +1,14 @@
+import { AutoresearchPipelineApi } from './generated/api.schemas'
+
+/** The question a model answers, in plain words. The model list cards and the detail header both show it. */
+export function pipelineQuestion({
+ target_event,
+ horizon_days,
+}: Pick<AutoresearchPipelineApi, 'target_event' | 'horizon_days'>): string {
+ if (!horizon_days) {
+ return `Who will do ${target_event}?`
+ }
+ return horizon_days === 1
+ ? `Who will do ${target_event} in the next day?`
+ : `Who will do ${target_event} in the next ${horizon_days} days?`
+}
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 0c9d079e0af2..ef3c8b5793a0 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -13537,6 +13537,22 @@ export namespace Schemas {
readonly created_at: string;
}
+ export interface AutoresearchLiveTrainingRun {
+ /** Unique UUID of the live training run. */
+ readonly id: string;
+ /** Maximum experiments allowed for this run. */
+ readonly iteration_budget: number;
+ /** Experiments the agent has recorded so far in this run. */
+ readonly experiment_count: number;
+ /**
+ * Best holdout AUC so far in this run. Null before any is recorded.
+ * @nullable
+ */
+ readonly best_holdout_score: number | null;
+ /** The agent's rationale for its newest experiment. */
+ readonly latest_agent_description: string;
+ }
+
/**
* Portable recipe artifact. Feature SQL, transforms, model class, params, and metadata.
*/
@@ -13725,6 +13741,13 @@ export namespace Schemas {
Archived: 'archived',
} as const;
+ export interface AutoresearchRealizedAucPoint {
+ /** Validated prediction date. */
+ readonly prediction_date: string;
+ /** Realized AUC on that date. */
+ readonly realized_auc: number;
+ }
+
export interface AutoresearchPipeline {
/** Unique UUID of this pipeline. */
readonly id: string;
@@ -13825,6 +13848,19 @@ export namespace Schemas {
* @nullable
*/
readonly champion_is_preliminary: boolean | null;
+ /** Realized AUC of the current champion on its newest 14 validated prediction dates, oldest first. */
+ readonly champion_realized_auc_trend: readonly AutoresearchRealizedAucPoint[];
+ /**
+ * People scored by the most recent completed inference run. Null before the first scoring run.
+ * @nullable
+ */
+ readonly people_scored: number | null;
+ /** Training runs started for this pipeline. */
+ readonly training_run_count: number;
+ /** Experiments (iterations) recorded across every training run. */
+ readonly experiment_count: number;
+ /** Progress of the pending or running training run. Null when no run is live. */
+ readonly live_training_run: AutoresearchLiveTrainingRun | null;
}
/**