The platform for continuously improving AI agents.
Stabilize agent activity, onboarding progress and dataset preparation (#270)
Freyam Mehta5a4c126c8067
diff --git a/.agents/skills/data-workshop/SKILL.md b/.agents/skills/data-workshop/SKILL.mdindex 83556e58..ec09b448 100644--- a/.agents/skills/data-workshop/SKILL.md+++ b/.agents/skills/data-workshop/SKILL.md@@ -9,7 +9,7 @@ The native coding agent owns interpretation, code and semantic work. The platfor## Preparation lifecycle-Before dataset preparation work, inspect_dataset_workbench and resume its preparation_workflow or call start_dataset_preparation with a stable request_key. Keep it preparing across local authoring, previews and publications. Use update_dataset_preparation with state=completed and verified published output cell UUIDs only when all requested agent work is finished; use paused when stopping temporarily or cancelled when abandoning. Individual job completion does not finish preparation.+`DatasetPreparation` (`services/datasets/preparation_workflow.py`) groups a coding agent's preparation work under one evolving notification. MCP `start_dataset_preparation` and `update_dataset_preparation` open and close it. The Console's End preparation (`POST /api/datasets/{id}/end-preparation/`) and the dataset reaper (24 h without activity) cancel it. An open preparation labels the dataset; it never locks editing.## Mapdiff --git a/.agents/skills/frontend-design/SKILL.md b/.agents/skills/frontend-design/SKILL.mdindex 26d1fca3..a4369a47 100644--- a/.agents/skills/frontend-design/SKILL.md+++ b/.agents/skills/frontend-design/SKILL.md@@ -13,7 +13,7 @@ The token spec is the root `DESIGN.md`; extend its values, don't restructure it.- Use no raw Tailwind palette utilities (`bg-green-500`) and no hex in class strings (`bg-[#1c1917]`).- **Status** uses a tint triplet, with no `dark:` variants: `border-success/40 bg-success/10 text-success`. The tones are `success` (passed, healthy, connected, completed), `warning` (review, degraded, stale), `info` (running, pending, queued, training), `error` (failed, cancelled; the `destructive` token) and `neutral` (draft, skipped, awaiting launch, unknown). Prefer `<Badge variant="success|warning|info|error|neutral">`; `variant="destructive"` is a solid fill, not the tint. For a domain state use `<StatusBadge status={state} fallback=…>`, which maps it through `domainStatus` itself (`lib/job-status.tsx`, `lib/colors.ts`).-- Active and queued job chips use `bg-foreground text-background` through the shared `StatusBadge`, not the blue info tint. Active chips pulse gently with reduced-motion support. Use the recorded coding-agent logo in place of the spinner when that task is attributed to a coding agent; never infer identity from connection presence.+- Active and queued job chips use the `info` tint through the shared `StatusBadge`; only `solidProgress` chips with a progress fill use `bg-foreground text-background`. Use the recorded coding-agent logo in place of the spinner when that task is attributed to a coding agent; never infer identity from connection presence.- **Categorical** entity types use `text-cat-1 … text-cat-6` and `bg-cat-1/10`, one stable slot per type.- **Login and onboarding** use the `--auth-*` tokens (`bg-auth-panel`, `border-auth-border`, `text-auth-accent`, …).- Neutrals: `bg-background`, `bg-card`, `bg-muted`, `text-foreground`, `text-muted-foreground`, `border-border`.@@ -36,7 +36,7 @@ The token spec is the root `DESIGN.md`; extend its values, don't restructure it.- Flat surfaces: `shadow-*` utilities are disabled. Depth is surface layering plus 1px borders. Shared confirmation dialogs alone use `shadow-confirmation`.- Radii: `rounded-sm` for interactive primitives, `rounded-md` for containers, `rounded-xs` only for elements smaller than about 8px. `rounded-lg` and larger are off-system.- Main page titles use `TITLE.page` (Mondwest); every other heading uses its `TITLE` role in Geist Pixel. `font-mono` also resolves to Geist Pixel.-- Icons come only from `import { Icon } from "@/components/ui/icons"` → `<Icon.name className="size-4" />`. The pixelarticons paths are vendored in `ui/icons/glyphs.ts`; app code never imports it or `lucide-react` (`check:design` fails). One concept, one glyph. Provider logos are the exception: `model-provider-chip.tsx` imports `@lobehub/icons`. To add a glyph, add `name: glyph("<svg-name>")` to `ui/icons/index.ts`, then run `bun run icons:vendor` with `PIXELARTICONS_LICENSE_KEY` set (or `--source <svg dir>`). Sizes: `size-4` in buttons, `size-[17px]` in nav, `size-3` in dense chips.+- Icons come only from `import { Icon } from "@/components/ui/icons"` → `<Icon.name className="size-4" />`. The pixelarticons paths are vendored in `ui/icons/glyphs.ts`; app code never imports it or `lucide-react` (`check:design` fails). One concept, one glyph. Provider and coding-agent logos are the exception: `model-provider-chip.tsx` and `coding-agent-icon.tsx` import `@lobehub/icons`. To add a glyph, add `name: glyph("<svg-name>")` to `ui/icons/index.ts`, then run `bun run icons:vendor` with `PIXELARTICONS_LICENSE_KEY` set (or `--source <svg dir>`). Sizes: `size-4` in buttons, `size-[17px]` in nav, `size-3` in dense chips.## Two table implementationsdiff --git a/.agents/skills/pr-etiquette/SKILL.md b/.agents/skills/pr-etiquette/SKILL.mdindex 15ad07b9..547788c4 100644--- a/.agents/skills/pr-etiquette/SKILL.md+++ b/.agents/skills/pr-etiquette/SKILL.md@@ -41,7 +41,9 @@ it is ready. Before pushing a model change:1. `make check-migrations` — the exact CI check, against `origin/main`.Never resolve a fork with `makemigrations --merge`. A `_merge_` file or a reused number fails-the `migrations` job; renumber instead.+the `migrations` job; renumber instead. The only exceptions are migrations already applied to a+shared database, pinned by checksum in `scripts/applied-migration-history.json`; never deploy an+unmerged branch with migrations to staging or production.## Completeness — the surfaces a PR must carry with itdiff --git a/DESIGN.md b/DESIGN.mdindex d943d1e7..b706f22e 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -935,9 +935,8 @@ indicator and chart navigation.### Loading and live updates-Active and queued job chips use a white surface with dark text. Active chips pulse-subtly, respecting reduced motion. Agent-attributed work uses the recorded coding-agent logo instead of a spinner; uncredited work retains its normal status icon.+Agent-attributed work uses the recorded coding agent logo instead of a spinner;+uncredited work retains its normal status icon.Initial page loads use the shared `LoadingState` spinner inside the page shell;keep the page header and navigation visible. Do not use a generic skeleton page.@@ -961,8 +960,9 @@ notice.Initial onboarding is embedded in the landing page, using a white retro frame,striped title bar and Figma pixel eye without window controls. It introduces MCPand keeps the Agent/Data toggle with the setup prompt and upload form. The empty-dataset inventory reuses the frame for data onboarding. Connected agents show-setup progress instead. Setup and connection evidence use the shared MCP workflow.+dataset inventory reuses the frame for data onboarding. A project without+capabilities shows setup progress once its agent reports; a project with+capabilities keeps its grid and shows a dismissible progress strip above it.### Motion (system-wide)diff --git a/frontend/public/setup.md b/frontend/public/setup.mdindex aa20354e..1191980a 100644--- a/frontend/public/setup.md+++ b/frontend/public/setup.md@@ -7,26 +7,16 @@ document wants you to do the setup and execute workflows, not to explain it backRun from the repository root. Every step is safe to repeat.1. Install the CLI (Python 3.10+): `python -m pip install --upgrade "overmind>=0.1.106"`.- On a conflict, report it and stop.+ If pip reports an externally managed environment, run+ `uv tool install --upgrade "overmind>=0.1.106"` (install `uv` first if it is missing) and use+ `overmind` wherever this guide says `python -m overmind`; if `overmind` is not on `PATH`, call it+ from the directory `uv tool dir --bin` prints. On any other conflict, report it and stop.1. Run `python -m overmind init --ide <claude|codex|cursor|opencode>` for the agent you run in.Add `--api-url URL` if the message names an API. It edits this agent's config; if yoursandbox blocks that, ask the user to approve running it outside the sandbox.1. Call `list_projects`. If it fails, have the user sign in, through the client's own prompt whenit offers one or else by following the `Next:` line `init` printed, then call it again.-## Report onboarding progress through MCP--Once the account and project are verified, read `overmind://activity?project_id=PROJECT_ID`.-For repository onboarding, generate one UUID `run_id` and retain it across reloads.-Call `report_onboarding_progress(project_id=PROJECT_ID, run_id=RUN_ID, completed_steps=N)`-with the verified consecutive completed count before starting the next stage and-after every completed stage. Resume by verifying retained work and reporting its-count with the same run ID. Await a successful receipt; retry failures with the-same values. Chat messages and local task lists do not update the Console.-Never invent completion, advance on a timer, or claim delivery after a failed call.-If reporting is unavailable, explicitly say Console progress is not updating.-This applies even when an older installed skill omits reporting instructions.-# USING OVERMINDOvermind can be used in 2 ways, onboarding from a codebase or onboarding using a dataset,diff --git a/frontend/src/components/capability-detail/flow/TrajectoryFlowTab.tsx b/frontend/src/components/capability-detail/flow/TrajectoryFlowTab.tsxindex 168a0910..4b7853a1 100644--- a/frontend/src/components/capability-detail/flow/TrajectoryFlowTab.tsx+++ b/frontend/src/components/capability-detail/flow/TrajectoryFlowTab.tsx@@ -187,6 +187,7 @@ function FlowCanvas({const measurementKey = nodes.map((node) => `${node.id}:${node.measured?.height}`).join("|");const hasInteracted = useRef(false);const framedRun = useRef<string | undefined>(undefined);+ const framedSearch = useRef<string | undefined>(undefined);const wrapperRef = useRef<HTMLDivElement>(null);const searchTargetRef = useRef(searchTarget);searchTargetRef.current = searchTarget;@@ -361,8 +362,8 @@ function FlowCanvas({next = preservePositions(next);setNodes(next);onGraphHeight(trajectoryBounds(next).height);- if (searchTarget) {- fitTarget(searchTarget, next);+ if (searchTarget && framedSearch.current !== searchTarget) {+ if (fitTarget(searchTarget, next)) framedSearch.current = searchTarget;} else if (run.highlighted &&displayedRunId &&@@ -413,6 +414,10 @@ function FlowCanvas({runPath,]);+ useEffect(() => {+ if (!searchTarget) framedSearch.current = undefined;+ }, [searchTarget]);+// Re-fit when the container resizes from hidden/zero-size to visible.useEffect(() => {const el = wrapperRef.current;diff --git a/frontend/src/components/datasets/datasets-table.tsx b/frontend/src/components/datasets/datasets-table.tsxindex d5c23200..842dc712 100644--- a/frontend/src/components/datasets/datasets-table.tsx+++ b/frontend/src/components/datasets/datasets-table.tsx@@ -163,7 +163,7 @@ const sortValue = (ds: Dataset, key: SortKey): string | number => {case "name":return datasetDisplayName(ds).toLowerCase();case "role":- return ds.roles.map((role) => DATASET_ROLES[role]).join(", ");+ return ds.roles.map((role) => DATASET_ROLES[role] ?? role).join(", ");case "rows":return ds.rows ?? 0;case "version":@@ -240,15 +240,15 @@ function getColumns(opts: {id: "name",meta: { label: "Name", orderingField: "name" },minSize: 160,- size: 260,+ size: 180,},{cell: ({ row }) => <DatasetStatus dataset={row.original} />,header: "Status",id: "status",meta: { label: "Status", noTruncate: true },- minSize: 140,- size: 190,+ minSize: 120,+ size: 120,},{accessorFn: (row) => row.roles.join(", "),@@ -257,7 +257,7 @@ function getColumns(opts: {<span className="inline-flex flex-nowrap gap-1">{row.original.roles.map((role) => (<Badge key={role} size="chip" variant="outline">- {DATASET_ROLES[role]}+ {DATASET_ROLES[role] ?? role}</Badge>))}</span>@@ -280,8 +280,8 @@ function getColumns(opts: {header: "Version",id: "version",meta: { label: "Version", orderingField: "version" },- minSize: 70,- size: 90,+ minSize: 100,+ size: 100,},{accessorFn: (row) => row.rows ?? 0,@@ -298,7 +298,7 @@ function getColumns(opts: {id: "rows",meta: { label: "Rows", orderingField: "rows" },minSize: 80,- size: 110,+ size: 80,},{accessorKey: "sourceKind",@@ -312,7 +312,7 @@ function getColumns(opts: {: [];return filenames.length ? (<span className="flex min-w-0 items-center gap-1 whitespace-nowrap">- {filenames.slice(0, 3).map((filename, index) => {+ {filenames.slice(0, 1).map((filename, index) => {const extension = filename.replace(/\.gz$/i, "").match(/\.([^.]+)$/)?.[1];return (<Badge@@ -329,9 +329,16 @@ function getColumns(opts: {</Badge>);})}- {filenames.length > 3 && (- <Badge className="shrink-0" size="chip" variant="outline">- +{filenames.length - 3} files+ {filenames.length > 1 && (+ <Badge+ aria-label={`Also ${filenames.slice(1).join(", ")}`}+ className="shrink-0"+ size="chip"+ tabIndex={0}+ title={filenames.slice(1).join(", ")}+ variant="outline"+ >+ +{filenames.length - 1}</Badge>)}</span>@@ -368,7 +375,7 @@ function getColumns(opts: {id: "capability",meta: { label: "Capability", noTruncate: true, orderingField: "capability" },minSize: 120,- size: 160,+ size: 140,});}@@ -385,7 +392,7 @@ function getColumns(opts: {id: "updated",meta: { label: "Updated", orderingField: "updated" },minSize: 110,- size: 120,+ size: 110,},{cell: ({ row }) => {@@ -476,21 +483,23 @@ export function DatasetsBrowser({const pageRows = sorted.slice((currentPage - 1) * pageSize, currentPage * pageSize);const hasActiveFilters = roleFilter !== "all" || capabilityFilter !== "all" || !!search;+ // Chip widths follow the rendered chip text, so two roles fit without truncation.const roleWidth = Math.max(- 130,- ...datasets.map(- (dataset) =>- 20 + dataset.roles.reduce((width, role) => width + DATASET_ROLES[role].length * 8 + 22, 0)+ 100,+ ...datasets.map((dataset) =>+ dataset.roles.reduce(+ (width, role, index) =>+ width + (DATASET_ROLES[role] ?? role).length * 6.5 + 19 + (index ? 5 : 0),+ 16+ )));- const sourceWidth = Math.max(- 180,- ...datasets.map((dataset) => {- const count = dataset.sourceSpec?.sources?.length ?? (dataset.sourceSpec?.filename ? 1 : 0);- return Math.min(3, count) * 180 + 24 + (count > 3 ? 80 : 0);- })- );+ const sourceWidth = datasets.some(+ (dataset) => dataset.sourceSpec?.sources?.length || dataset.sourceSpec?.filename+ )+ ? 160+ : 90;const columns = useMemo(() =>diff --git a/frontend/src/components/datasets/notebook/notebook-page.tsx b/frontend/src/components/datasets/notebook/notebook-page.tsxindex 1e864e7d..e9579610 100644--- a/frontend/src/components/datasets/notebook/notebook-page.tsx+++ b/frontend/src/components/datasets/notebook/notebook-page.tsx@@ -3,6 +3,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useQueryClient } from "@tanstack/react-query";import { Link, useNavigate } from "@tanstack/react-router";+import { CodingAgentIcon } from "@/components/coding-agent-icon";import { NotebookControls } from "@/components/datasets/notebook/canvas-controls";import { NotebookCell, type UsePurpose } from "@/components/datasets/notebook/cell";import { CellFlow } from "@/components/datasets/notebook/cell-flow";@@ -24,11 +25,13 @@ import {intentOf,invalidateDataset,isBusy,+ openPreparation,rankOf,useCancelDatasetMutation,useDatasetEvents,useDatasetPreparationQuery,useDatasetQuery,+ useEndPreparationMutation,usePatchDatasetMutation,useResumeDatasetImportMutation,} from "@/hooks/use-datasets";@@ -62,6 +65,7 @@ export function DatasetNotebook({const patch = usePatchDatasetMutation(datasetId);const cancel = useCancelDatasetMutation(datasetId);+ const endPreparation = useEndPreparationMutation(datasetId);const resumeImport = useResumeDatasetImportMutation(datasetId);const [showMinimap, setShowMinimap] = usePersistedState("workshopFlow:showMinimap", false);@@ -108,6 +112,7 @@ export function DatasetNotebook({const visibleIds = useMemo(() => new Set(cells.map((cell) => cell.id)), [cells]);const { motions, complete } = useCellMotion(nodes ? cells : undefined, visibleIds);const busy = isBusy(dataset);+ const preparing = openPreparation(dataset);const editable = !!dataset && !busy;const intent = intentOf(dataset);@@ -246,6 +251,22 @@ export function DatasetNotebook({</Button></div>)}+ {!busy && preparing && (+ <div className="flex items-center justify-between gap-3 rounded-sm border border-border px-3 py-2 text-xs">+ <span className="inline-flex items-center gap-1.5">+ {preparing.actorKind ? <CodingAgentIcon kind={preparing.actorKind} /> : null}+ {preparing.label}+ </span>+ <Button+ disabled={endPreparation.isPending}+ onClick={() => endPreparation.mutate()}+ size="sm"+ variant="secondary"+ >+ End preparation+ </Button>+ </div>+ )}<ContaminationReport spec={dataset.sourceSpec} />{preparationQuery.isError && (<p className="px-4 text-sm text-destructive" role="alert">diff --git a/frontend/src/components/evaluations/eval-matrix-table.tsx b/frontend/src/components/evaluations/eval-matrix-table.tsxindex 24f2004b..0e049298 100644--- a/frontend/src/components/evaluations/eval-matrix-table.tsx+++ b/frontend/src/components/evaluations/eval-matrix-table.tsx@@ -177,7 +177,11 @@ export function EvalMatrixTable({graph: buildTrajectoryGraph(detail.flow, detail.name, [], detail.entrypointFn),};},- queryKey: ["evaluation-trajectory", id, capability?.id === id ? capability : undefined],+ queryKey: [+ "evaluation-trajectory",+ id,+ capability?.id === id ? capability.updatedAt.getTime() : undefined,+ ],staleTime: 15_000,})),});@@ -268,7 +272,7 @@ export function EvalMatrixTable({filters={<><Select onValueChange={setPart} value={part}>- <SelectTrigger aria-label="Evaluation applies to" className="w-48" size="default">+ <SelectTrigger aria-label="Evaluation applies to" className="w-56" size="default"><SelectValue /></SelectTrigger><SelectContent>diff --git a/frontend/src/components/evaluations/runs-table.tsx b/frontend/src/components/evaluations/runs-table.tsxindex 34ad658f..06138546 100644--- a/frontend/src/components/evaluations/runs-table.tsx+++ b/frontend/src/components/evaluations/runs-table.tsx@@ -302,7 +302,7 @@ export function RunsTable({header: "Name",meta: { orderingField: "name" },minSize: 160,- size: 240,+ size: 220,},{accessorKey: "status",diff --git a/frontend/src/components/inference/dedicated-deployment.tsx b/frontend/src/components/inference/dedicated-deployment.tsxindex a8ba9ed4..18dd7187 100644--- a/frontend/src/components/inference/dedicated-deployment.tsx+++ b/frontend/src/components/inference/dedicated-deployment.tsx@@ -7,6 +7,7 @@ import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Card } from "@/components/ui/card";import { Checkbox } from "@/components/ui/checkbox";+import { ConfirmDialog } from "@/components/ui/confirm-dialog";import {Dialog,DialogBody,@@ -84,7 +85,9 @@ function speed(gpu: DedicatedGpu, decision: boolean): string {}function price(credits: string | null | undefined): string {- return credits == null ? "Price unavailable" : `${credits} credits/hour per GPU`;+ return credits == null+ ? "Price unavailable"+ : `${Number(credits).toLocaleString(undefined, { maximumFractionDigits: 2 })} credits/hour per GPU`;}function digits(raw: string): string {@@ -129,12 +132,14 @@ export function DedicatedDeploymentSection({}) {const [open, setOpen] = useState(false);const [snippetOpen, setSnippetOpen] = useState(false);+ const [confirmStart, setConfirmStart] = useState(false);const start = useStartDedicatedMutation(model.id);const stop = useStopDedicatedMutation(model.id);const ready = model.status === "ready";const deployment = useDedicatedDeploymentQuery(model.id, ready);- const gpus = useDedicatedGpusQuery(model.id, ready && open);+ const gpus = useDedicatedGpusQuery(model.id, ready && (open || confirmStart));const row = deployment.data ?? null;+ const startRate = gpus.data?.find((gpu) => gpu.gpuType === row?.gpuType)?.creditsPerGpuHour;const active = row != null && ACTIVE.has(row.status ?? "");const stopping = row?.status === "shutting_down";const pending = start.isPending || stop.isPending;@@ -145,18 +150,22 @@ export function DedicatedDeploymentSection({onError: (error) => notify.error(error, "Couldn't stop the deployment"),});} else {- start.mutate(- {- gpuType: row.gpuType,- idleShutdownSeconds: row.idleShutdownSeconds ?? 900,- maxReplicas: row.maxReplicas ?? 1,- minReplicas: row.scaleToZero ? 0 : Math.max(1, row.minReplicas ?? 1),- scaleToZero: row.scaleToZero ?? false,- },- { onError: (error) => notify.error(error, "Couldn't start the deployment") }- );+ setConfirmStart(true);}};+ const startDeployment = () => {+ if (!row) return;+ start.mutate(+ {+ gpuType: row.gpuType,+ idleShutdownSeconds: row.idleShutdownSeconds ?? 900,+ maxReplicas: row.maxReplicas ?? 1,+ minReplicas: row.scaleToZero ? 0 : Math.max(1, row.minReplicas ?? 1),+ scaleToZero: row.scaleToZero ?? false,+ },+ { onError: (error) => notify.error(error, "Couldn't start the deployment") }+ );+ };if (!ready) return null;return (<>@@ -278,6 +287,25 @@ export function DedicatedDeploymentSection({</DialogBody></DialogContent></Dialog>+ {row ? (+ <ConfirmDialog+ confirmDisabled={startRate == null}+ confirmLabel="Start"+ description={+ gpus.isLoading+ ? `${row.gpuType} · Loading the current rate`+ : startRate == null+ ? `${row.gpuType} · The current rate is unavailable, so the endpoint cannot start.`+ : `${row.gpuType} · ${price(startRate)} while replicas run.`+ }+ error={gpus.error}+ isPending={gpus.isLoading}+ onConfirm={startDeployment}+ onOpenChange={setConfirmStart}+ open={confirmStart}+ title="Start dedicated endpoint"+ />+ ) : null}{row ? (<ApiSnippetDialogcapabilityId={null}@@ -301,13 +329,13 @@ function DeploymentStatus({ row }: { row: DedicatedDeployment }) {["GPU", row.gpuType],["Replicas",- `${row.runningReplicas ?? "—"} running · ${row.minReplicas}–${row.maxReplicas} configured`,+ `${row.runningReplicas ?? "—"} running · ${row.minReplicas ?? "—"}–${row.maxReplicas ?? "—"} configured`,],["Idle timeout",- `${row.idleShutdownSeconds}s${row.scaleToZero ? " · scales to zero" : ""}`,+ `${row.idleShutdownSeconds == null ? "—" : `${row.idleShutdownSeconds}s`}${row.scaleToZero ? " · scales to zero" : ""}`,],- ["Rate per GPU", `${row.creditsPerGpuHour} credits/hour`],+ ["Rate", price(row.creditsPerGpuHour)],].map(([label, value]) => (<div className="space-y-1" key={label}><dt className="text-xs text-muted-foreground">{label}</dt>diff --git a/frontend/src/components/inference/dedicated-startup.tsx b/frontend/src/components/inference/dedicated-startup.tsxindex 060ac6b4..596b4724 100644--- a/frontend/src/components/inference/dedicated-startup.tsx+++ b/frontend/src/components/inference/dedicated-startup.tsx@@ -38,7 +38,7 @@ export function DedicatedStartupProgress({ row }: { row: DedicatedDeployment })return () => observer.disconnect();}, []);const startup = row.startup;- const label = startup?.label ?? "Starting worker";+ const label = startup?.label ?? "Starting";const reached = Math.max(0,...[row.status, startup?.stage, ...(startup?.logs.map((entry) => entry.stage) ?? [])].map(diff --git a/frontend/src/components/inference/model-usage.tsx b/frontend/src/components/inference/model-usage.tsxindex 4ddaeb56..7753f558 100644--- a/frontend/src/components/inference/model-usage.tsx+++ b/frontend/src/components/inference/model-usage.tsx@@ -7,6 +7,8 @@ import type { InferenceMetrics } from "@/openapi";const number = (value: number | null | undefined) =>value == null ? "—" : value.toLocaleString(undefined, { maximumFractionDigits: 2 });+const credits = (value: number | null | undefined) =>+ value == null ? "—" : `${number(value)} credits`;export function ModelUsage({ metrics }: { metrics: InferenceMetrics }) {const usage = metrics.dedicatedUsage;@@ -19,7 +21,7 @@ export function ModelUsage({ metrics }: { metrics: InferenceMetrics }) {<Card className="overflow-hidden"><div className="grid grid-cols-2 divide-x divide-border/70 lg:grid-cols-4">{[- ["Dedicated spend", `${number(usage.credits)} credits`],+ ["Dedicated spend", credits(usage.credits)],["Billed GPU hours", number(usage.gpuHours)],["Input tokens", number(metrics.promptTokens)],["Output tokens", number(metrics.completionTokens)],@@ -30,9 +32,9 @@ export function ModelUsage({ metrics }: { metrics: InferenceMetrics }) {</div>))}</div>- <div className="border-t border-border/70 p-3">- <div aria-label="Dedicated spend chart" className="h-44" role="img">- {usage.points.length ? (+ {usage.points.length ? (+ <div className="border-t border-border/70 p-3">+ <div aria-label="Dedicated spend chart" className="h-44" role="img"><ResponsiveContainer height="100%" width="100%"><BarChartdata={usage.points.map((point) => ({ ...point, time: point.bucket.getTime() }))}@@ -67,7 +69,7 @@ export function ModelUsage({ metrics }: { metrics: InferenceMetrics }) {active={active}label={label != null ? new Date(Number(label)).toLocaleString() : undefined}payload={payload}- valueFormatter={(value) => `${number(value)} credits`}+ valueFormatter={(value) => credits(value)}/>)}/>@@ -80,21 +82,19 @@ export function ModelUsage({ metrics }: { metrics: InferenceMetrics }) {/></BarChart></ResponsiveContainer>- ) : (- <div className="flex h-full items-center justify-center text-xs text-muted-foreground">- No dedicated charges recorded in this period- </div>- )}+ </div></div>- </div>+ ) : (+ <p className="border-t border-border/70 px-4 py-3 text-xs text-muted-foreground">+ No dedicated charges in this period+ </p>+ )}{usage.breakdown.length > 1 ? (<div className="flex flex-wrap gap-x-6 gap-y-2 border-t border-border/70 px-3 py-2 text-xs text-muted-foreground">{usage.breakdown.map((item) => (<span key={item.gpuType ?? "unknown"}>{item.gpuType ?? "Unspecified GPU"}- <span className="ml-2 tabular-nums text-foreground">- {number(item.credits)} credits- </span>+ <span className="ml-2 tabular-nums text-foreground">{credits(item.credits)}</span></span>))}</div>diff --git a/frontend/src/components/quickstart/onboard-with-ai-panel.tsx b/frontend/src/components/quickstart/onboard-with-ai-panel.tsxindex 8324f554..161e1682 100644--- a/frontend/src/components/quickstart/onboard-with-ai-panel.tsx+++ b/frontend/src/components/quickstart/onboard-with-ai-panel.tsx@@ -5,7 +5,7 @@ import { Button } from "@/components/ui/button";import { Icon } from "@/components/ui/icons";import { config } from "@/config";import { writeClipboardText } from "@/lib/clipboard";-import { ONBOARDING_GUIDE_URL, onboardingPrompt } from "@/lib/mcp-setup";+import { onboardingPrompt } from "@/lib/mcp-setup";import { cn } from "@/lib/utils";export function OnboardWithAiPanel({@@ -32,8 +32,7 @@ export function OnboardWithAiPanel({datasetId && projectId ? { datasetId, projectId } : undefined);- const guide =- datasetId && projectId ? `${window.location.origin}/setup.md` : ONBOARDING_GUIDE_URL;+ const guide = `${window.location.origin}/setup.md`;const copyPrompt = () =>writeClipboardText(prompt).then(@@ -59,12 +58,9 @@ export function OnboardWithAiPanel({<paria-label={compact ? "Setup prompt" : undefined}className={cn(- "rounded-sm border border-border bg-wash-subtle px-2 py-1.5 text-sm text-foreground",- compact- ? "overflow-x-auto whitespace-nowrap focus-visible:outline focus-visible:outline-ring"- : "break-all whitespace-break-spaces rounded-md px-3 py-2"+ "rounded-sm border border-border bg-wash-subtle px-3 py-2 text-sm text-foreground [overflow-wrap:anywhere]",+ !compact && "whitespace-break-spaces rounded-md")}- tabIndex={compact ? 0 : undefined}>{compact ? (<>diff --git a/frontend/src/components/quickstart/onboarding-milestones.tsx b/frontend/src/components/quickstart/onboarding-milestones.tsxindex f5fac9ca..d0837417 100644--- a/frontend/src/components/quickstart/onboarding-milestones.tsx+++ b/frontend/src/components/quickstart/onboarding-milestones.tsx@@ -1,13 +1,11 @@-import { useEffect, useRef, useState } from "react";+import { useEffect, useState } from "react";import { CodingAgentIcon } from "@/components/coding-agent-icon";import { Alert } from "@/components/ui/alert";-import { Button } from "@/components/ui/button";import { Card } from "@/components/ui/card";import { LoadingState } from "@/components/ui/spinner";import { useOnboardingMilestones } from "@/hooks/use-activity";import { cn } from "@/lib/utils";-import type { OnboardingMilestone } from "@/openapi";function StageLabel({ text, active }: { text: string; active: boolean }) {const [length, setLength] = useState(0);@@ -93,61 +91,12 @@ function CapabilityTicker({ value }: { value: number }) {export function OnboardingMilestones({projectId,projectName,- devPreview = false,- onComplete,- autoPlay = false,}: {projectId?: string;projectName?: string;- devPreview?: boolean;- onComplete?: () => void;- autoPlay?: boolean;}) {const query = useOnboardingMilestones(projectId, "agent");- const [simulation, setSimulation] = useState<OnboardingMilestone[] | null>(null);- const [playing, setPlaying] = useState(false);- const steps = simulation ?? query.data;- const autoStarted = useRef(false);- useEffect(() => {- if (autoPlay && devPreview && query.data && !autoStarted.current) {- autoStarted.current = true;- setSimulation(- query.data.map((step) => ({ ...step, activityId: null, assets: [], completedAt: null }))- );- setPlaying(true);- }- }, [autoPlay, devPreview, query.data]);- const complete = !!steps?.length && steps.every((step) => step.completedAt);- useEffect(() => {- if (complete && (!devPreview || simulation)) onComplete?.();- }, [complete, devPreview, simulation, onComplete]);- useEffect(() => {- if (!playing || !simulation) return;- const next = simulation.findIndex((step) => !step.completedAt);- if (next === -1) {- setPlaying(false);- return;- }- const timer = window.setTimeout(() => {- setSimulation(- (previous) =>- previous?.map((step, index) =>- index === next- ? {- ...step,- assets: ["capabilities_discovered", "repository_synced"].includes(step.kind)- ? ["Answer questions", "Search knowledge", "Escalate requests"].map(- (label, i) => ({ id: `preview-${i}`, kind: "capability" as const, label })- )- : [],- completedAt: new Date(),- }- : step- ) ?? null- );- }, 1800);- return () => window.clearTimeout(timer);- }, [playing, simulation]);+ const steps = query.data;if (!steps && query.isLoading) return <LoadingState label="Loading setup progress" />;if (!steps) {@@ -157,11 +106,7 @@ export function OnboardingMilestones({const completed = steps.filter((step) => step.completedAt).length;const current = steps.find((step) => !step.completedAt);const stage = current?.label ?? "Your agent is set up";- const reporter = simulation- ? { actorKind: "codex", actorName: "Codex" }- : current?.actorName- ? current- : steps.find((step) => step.actorName);+ const reporter = current?.actorName ? current : steps.find((step) => step.actorName);const connected = steps.some((step) => step.kind === "agent_connected" && step.completedAt);const synced = steps.some((step) => step.kind === "repository_synced" && step.completedAt);const capabilities = new Map(@@ -173,51 +118,10 @@ export function OnboardingMilestones({.map((asset) => [asset.id, asset.label] as const)));- const name = connected- ? simulation- ? "Support Copilot"- : (projectName ?? "Connected")- : "Waiting for connection";+ const name = connected ? (projectName ?? "Connected") : "Waiting for connection";return (<div className="space-y-2">- {import.meta.env.DEV && devPreview && (- <div className="flex flex-wrap items-center justify-between gap-2 text-xs text-muted-foreground">- <span>{simulation ? "Simulated onboarding · sample data" : "Dev preview"}</span>- <div className="flex gap-2">- {simulation && (- <Button- onClick={() => {- setPlaying(false);- setSimulation(null);- }}- size="xs"- variant="secondary"- >- Live data- </Button>- )}- <Button- disabled={playing}- onClick={() => {- setSimulation(- query.data!.map((step) => ({- ...step,- activityId: null,- assets: [],- completedAt: null,- }))- );- setPlaying(true);- }}- size="xs"- variant="secondary"- >- {playing ? "Playing…" : simulation ? "Replay" : "Play full run"}- </Button>- </div>- </div>- )}<Card className="space-y-3 p-4"><divaria-atomic="true"@@ -287,7 +191,7 @@ export function OnboardingMilestones({</div></dl></Card>- {query.error && !simulation && (+ {query.error && (<Alert variant="destructive">Couldn’t refresh progress. Showing the last saved update.</Alert>diff --git a/frontend/src/components/quickstart/quickstart-embed.tsx b/frontend/src/components/quickstart/quickstart-embed.tsxindex 1972488d..57e30a8a 100644--- a/frontend/src/components/quickstart/quickstart-embed.tsx+++ b/frontend/src/components/quickstart/quickstart-embed.tsx@@ -12,15 +12,9 @@ import { useOnboardingMilestones } from "@/hooks/use-activity";export function QuickstartEmbed({projectId,projectName,- devPreview = false,- onComplete,- autoPlay = false,}: {projectId?: string;projectName?: string;- devPreview?: boolean;- onComplete?: () => void;- autoPlay?: boolean;}) {const [source, setSource] = useState<"agent" | "data">("agent");const navigate = useNavigate();@@ -28,16 +22,11 @@ export function QuickstartEmbed({const connected = milestones.data?.some((step) => step.kind === "agent_connected" && step.completedAt);- if (source === "agent" && (connected || devPreview)) {+ if (projectId && milestones.isLoading) return null;+ if (source === "agent" && connected) {return (<section aria-label="Agent onboarding" className="w-full max-w-md">- <OnboardingMilestones- autoPlay={autoPlay}- devPreview={devPreview}- onComplete={onComplete}- projectId={projectId}- projectName={projectName}- />+ <OnboardingMilestones projectId={projectId} projectName={projectName} /></section>);}@@ -47,9 +36,9 @@ export function QuickstartEmbed({<OnboardingWindow title="Onboarding"><div className="flex flex-wrap items-center justify-between gap-3"><div className="space-y-1">- <h2 className="text-sm font-medium">Overmind works best via the MCP</h2>+ <h2 className="text-sm font-medium">Set up this project</h2><p className="text-xs text-muted-foreground">- Connect your coding agent or upload data to get started.+ Paste the prompt into a coding agent, or upload data.</p></div><Tabsdiff --git a/frontend/src/components/ui/confirm-dialog.tsx b/frontend/src/components/ui/confirm-dialog.tsxindex e0e4fc53..970b4a2d 100644--- a/frontend/src/components/ui/confirm-dialog.tsx+++ b/frontend/src/components/ui/confirm-dialog.tsx@@ -26,6 +26,7 @@ function ConfirmDialog({destructive = false,error = null,isPending = false,+ confirmDisabled = false,keepOpenOnError = false,onConfirm,}: {@@ -40,6 +41,7 @@ function ConfirmDialog({/** Restated inside the dialog, since a toast can fade before it is read. */error?: Error | null;isPending?: boolean;+ confirmDisabled?: boolean;/** Await `onConfirm` and keep the dialog open if it rejects. Requires an awaitable* `onConfirm`. */keepOpenOnError?: boolean;@@ -61,7 +63,7 @@ function ConfirmDialog({<AlertDialogFooter><AlertDialogCancel disabled={isPending}>{cancelLabel}</AlertDialogCancel><AlertDialogAction- disabled={isPending}+ disabled={isPending || confirmDisabled}onClick={(e) => {// Block the default auto-close so the `isPending` spinner stays visible.if (isPending) e.preventDefault();diff --git a/frontend/src/hooks/use-activity.ts b/frontend/src/hooks/use-activity.tsindex 1e0779e6..26493060 100644--- a/frontend/src/hooks/use-activity.ts+++ b/frontend/src/hooks/use-activity.ts@@ -1,8 +1,7 @@import { useEffect } from "react";import {- type InfiniteData,- skipToken,+ infiniteQueryOptions,useInfiniteQuery,useMutation,useQuery,@@ -14,11 +13,9 @@ import apiClient from "@/client";import { useAuthContext } from "@/contexts/auth-context";import { type ActivityFeed, ActivityFeedFromJSON, type ActivitySeenRequest } from "@/openapi";-export function useActivity(projectId?: string) {- const { isSignedIn, isGuest } = useAuthContext();- useLiveActivity(projectId, isSignedIn && !isGuest);- return useInfiniteQuery({- enabled: isSignedIn && !isGuest,+const activityQuery = (projectId: string | undefined, enabled: boolean) =>+ infiniteQueryOptions({+ enabled,getNextPageParam: (page: ActivityFeed) => page.nextOffset ?? undefined,initialPageParam: 0,queryFn: ({ pageParam }): Promise<ActivityFeed> =>@@ -26,6 +23,11 @@ export function useActivity(projectId?: string) {queryKey: ["activity", projectId],refetchInterval: 30000,});++export function useActivity(projectId?: string) {+ const { isSignedIn, isGuest } = useAuthContext();+ useLiveActivity(projectId, isSignedIn && !isGuest);+ return useInfiniteQuery(activityQuery(projectId, isSignedIn && !isGuest));}export function useMarkActivitySeen() {@@ -48,11 +50,11 @@ export function useOnboardingMilestones(projectId: string | undefined, path: "ag}export function useActivityActor(kind: string, id: string | undefined) {+ const { isSignedIn, isGuest } = useAuthContext();const { projectId } = useSearch({ shouldThrow: false, strict: false }) ?? {};- return useQuery({- queryFn: skipToken,- queryKey: ["activity", projectId],- select: (data: InfiniteData<ActivityFeed>) =>+ return useInfiniteQuery({+ ...activityQuery(projectId, isSignedIn && !isGuest),+ select: (data) =>data.pages.flatMap((page) => page.results).find((event) => event.taskKind === kind && event.taskId === id)?.actorKind,@@ -78,6 +80,15 @@ const liveQueries = new Set(["finetuning-loss-curves",]);+// Pinned cell rows and column statistics are immutable.+const isLive = (queryKey: readonly unknown[]) =>+ liveQueries.has(String(queryKey[0])) &&+ !(+ queryKey[0] === "datasets" &&+ ["rows", "columns"].includes(String(queryKey[2])) &&+ queryKey[3] !== undefined+ );+export function useActivityHighlights() {return useQuery<Record<string, number>>({enabled: false,@@ -96,6 +107,7 @@ function useLiveActivity(projectId: string | undefined, enabled: boolean) {let clear: ReturnType<typeof setTimeout> | undefined;let controller: AbortController;let previous: Map<string, number> | undefined;+ let delay = 1500;client.setQueryData(highlightKey, {});const apply = async (feed: ActivityFeed) => {const next = new Map(feed.results.map((event) => [event.id, event.updatedAt.getTime()]));@@ -108,7 +120,7 @@ function useLiveActivity(projectId: string | undefined, enabled: boolean) {predicate: (query) =>query.queryKey[0] === "activity" ||query.queryKey[0] === "onboarding-milestones" ||- (reconcileAssets && liveQueries.has(String(query.queryKey[0]))),+ (reconcileAssets && isLive(query.queryKey)),});if (stopped || !changes.length) return;const marks: Record<string, number> = {};@@ -141,18 +153,15 @@ function useLiveActivity(projectId: string | undefined, enabled: boolean) {const frames = buffer.split("\n\n");buffer = frames.pop() ?? "";for (const frame of frames) {- if (frame.startsWith("data: "))- await apply(ActivityFeedFromJSON(JSON.parse(frame.slice(6))));+ if (!frame.startsWith("data: ")) continue;+ delay = 1500;+ await apply(ActivityFeedFromJSON(JSON.parse(frame.slice(6))));}}} catch {- // Reconcile cached assets while the stream reconnects.- if (!stopped)- await client.invalidateQueries({- predicate: (query) => liveQueries.has(String(query.queryKey[0])),- });+ delay = Math.min(delay * 2, 60_000);}- if (!stopped) retry = setTimeout(connect, 1500);+ if (!stopped) retry = setTimeout(connect, delay);};void connect();return () => {diff --git a/frontend/src/hooks/use-datasets.ts b/frontend/src/hooks/use-datasets.tsindex c212f74c..3f36cae9 100644--- a/frontend/src/hooks/use-datasets.ts+++ b/frontend/src/hooks/use-datasets.ts@@ -140,7 +140,13 @@ export const activeCellOf = (dataset: Dataset | null | undefined): Cell | null =};export const isBusy = (ds: Dataset | null | undefined): boolean =>- !!ds && (!!ds.work || ds.state === "running" || ds.state === "landing");+ !!ds &&+ (["queued", "running"].includes(ds.work?.status ?? "") ||+ ds.state === "running" ||+ ds.state === "landing");++export const openPreparation = (ds: Dataset | null | undefined) =>+ ds?.work && ["preparing", "paused"].includes(ds.work.status) ? ds.work : null;/** The used-version block consumers carry (`cell_info`). */export interface UsedVersionInfo {@@ -252,7 +258,7 @@ export function useProjectDatasetsQuery(projectId: string | undefined) {enabled: !!projectId,queryFn: ({ signal }) => fetchProjectDatasets(projectId!, signal),queryKey: ["datasets", "list", projectId, "inventory"],- refetchInterval: (query) => (query.state.data?.some(isBusy) ? 1000 : 3000),+ refetchInterval: (query) => (query.state.data?.some(isBusy) ? 3000 : 15000),});}@@ -506,6 +512,15 @@ export const useCancelDatasetMutation = (id: string) => {});};+export const useEndPreparationMutation = (id: string) => {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: () => apiClient.datasets.datasetsEndPreparationCreate({ id }),+ onError: (error) => notify.error(error, "Couldn't end the preparation"),+ onSuccess: () => invalidateDataset(qc, id),+ });+};+export const useResumeDatasetImportMutation = (id: string) => {const qc = useQueryClient();return useMutation({diff --git a/frontend/src/lib/dataset-workspaces.ts b/frontend/src/lib/dataset-workspaces.tsindex 595096bd..d3598701 100644--- a/frontend/src/lib/dataset-workspaces.ts+++ b/frontend/src/lib/dataset-workspaces.ts@@ -13,7 +13,8 @@ export function datasetWorkspaces(datasets: Dataset[]): Dataset[] {const root = byId.get(id)!;const busy = members.find((member) =>- member.work && ["running", "queued", "accepted", "paused"].includes(member.work.status)+ member.work &&+ ["running", "queued", "accepted", "preparing", "paused"].includes(member.work.status));const latest = members.reduce((a, b) => (a.updatedAt > b.updatedAt ? a : b));return {diff --git a/frontend/src/lib/job-status.tsx b/frontend/src/lib/job-status.tsxindex 40c8dced..31165a3a 100644--- a/frontend/src/lib/job-status.tsx+++ b/frontend/src/lib/job-status.tsx@@ -79,8 +79,7 @@ export function statusBadgeClassName(cfg: StatusMeta, solidProgress?: boolean):return cn("gap-1",solidProgress && "h-7 py-0",- cfg.tone === "info" && "border-transparent bg-foreground text-background",- cfg.spinning && "job-active-pulse"+ solidProgress && cfg.tone === "info" && "border-transparent bg-foreground text-background");}@@ -152,16 +151,11 @@ export function ResolvedStatusBadge({{normalizedProgress != null && (<spanaria-hidden="true"- className="absolute inset-y-0 left-0 z-0 bg-background/10 transition-[width] duration-500 motion-reduce:transition-none"+ className="absolute inset-y-0 left-0 z-0 bg-info/20 transition-[width] duration-500 motion-reduce:transition-none"style={{ width: `${normalizedProgress}%` }}/>)}- <span- className={cn(- "inline-flex items-center gap-1",- normalizedProgress != null && "relative z-10"- )}- >+ <span className="relative z-10 inline-flex items-center gap-1">{cfg.spinning &&actorKind &&["codex", "claude", "cursor", "gemini", "coding_agent"].includes(actorKind) ? (diff --git a/frontend/src/lib/mcp-setup.test.ts b/frontend/src/lib/mcp-setup.test.tsindex ed66f73b..6792856d 100644--- a/frontend/src/lib/mcp-setup.test.ts+++ b/frontend/src/lib/mcp-setup.test.ts@@ -28,7 +28,7 @@ describe("mcp setup snippets", () => {projectId: PROJECT_ID,})).toBe(- `Set me up on Overmind with my uploaded data\n(project_id: ${PROJECT_ID},\ndataset_id: d-1)\n\n: https://console.overmindlab.ai/setup.md`+ `Set me up on Overmind with my uploaded data\n(project_id: ${PROJECT_ID},\ndataset_id: d-1)\n\nhttps://console.overmindlab.ai/setup.md`);});@@ -36,9 +36,9 @@ describe("mcp setup snippets", () => {STAGING,LOCAL,"https://api.customer.example",- ])("uses the hosted setup prompt on %s", (host) => {+ ])("names a non-hosted API endpoint %s", (host) => {expect(onboardingPrompt("http://localhost:5173", `${host}/`)).toBe(- "Set me up on Overmind https://console.overmindlab.ai/setup.md"+ `Set me up on Overmind\n\nusing the API at ${host}: http://localhost:5173/setup.md`);});diff --git a/frontend/src/lib/mcp-setup.ts b/frontend/src/lib/mcp-setup.tsindex b070fe91..98060170 100644--- a/frontend/src/lib/mcp-setup.ts+++ b/frontend/src/lib/mcp-setup.ts@@ -78,18 +78,18 @@ export function mcpInitCommand(].join(" &&\n");}-export const ONBOARDING_GUIDE_URL = "https://console.overmindlab.ai/setup.md";export function onboardingPrompt(origin: string,apiUrl: string,data?: { projectId: string; datasetId: string }): string {- if (!data) return `Set me up on Overmind ${ONBOARDING_GUIDE_URL}`;const guide = `${origin.replace(/\/$/, "")}/setup.md`;const url = apiUrl.replace(/\/$/, "");- const subject = `Set me up on Overmind with my uploaded data\n(project_id: ${data.projectId},\ndataset_id: ${data.datasetId})`;- const endpoint = url === HOSTED_API_URL ? "" : `using the API at ${url}`;- return `${subject}\n\n${endpoint}: ${guide}`;+ const subject = data+ ? `Set me up on Overmind with my uploaded data\n(project_id: ${data.projectId},\ndataset_id: ${data.datasetId})`+ : "Set me up on Overmind";+ if (url !== HOSTED_API_URL) return `${subject}\n\nusing the API at ${url}: ${guide}`;+ return data ? `${subject}\n\n${guide}` : `${subject} ${guide}`;}/** Instruction handed to the coding agent, addressed to the agent the user picked. */diff --git a/frontend/src/openapi/apis/DatasetsApi.ts b/frontend/src/openapi/apis/DatasetsApi.tsindex ebb0f113..1feb9087 100644--- a/frontend/src/openapi/apis/DatasetsApi.ts+++ b/frontend/src/openapi/apis/DatasetsApi.ts@@ -89,6 +89,10 @@ export interface DatasetsDestroyRequest {id: string;}+export interface DatasetsEndPreparationCreateRequest {+ id: string;+}+export interface DatasetsEventsRetrieveRequest {id: string;format?: DatasetsEventsRetrieveFormatEnum;@@ -427,6 +431,61 @@ export class DatasetsApi extends runtime.BaseAPI {await this.datasetsDestroyRaw(requestParameters, initOverrides);}+ /**+ */+ async datasetsEndPreparationCreateRaw(requestParameters: DatasetsEndPreparationCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<Dataset>> {+ if (requestParameters['id'] == null) {+ throw new runtime.RequiredError(+ 'id',+ 'Required parameter "id" was null or undefined when calling datasetsEndPreparationCreate().'+ );+ }++ const queryParameters: any = {};++ const headerParameters: runtime.HTTPHeaders = {};++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("ClerkBearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }+ if (this.configuration && this.configuration.apiKey) {+ headerParameters["X-Api-Key"] = await this.configuration.apiKey("X-Api-Key"); // ApiKeyAuth authentication+ }++ if (this.configuration && this.configuration.accessToken) {+ const token = this.configuration.accessToken;+ const tokenString = await token("BearerAuth", []);++ if (tokenString) {+ headerParameters["Authorization"] = `Bearer ${tokenString}`;+ }+ }++ let urlPath = `/api/datasets/{id}/end-preparation/`;+ urlPath = urlPath.replace(`{${"id"}}`, encodeURIComponent(String(requestParameters['id'])));++ const response = await this.request({+ path: urlPath,+ method: 'POST',+ headers: headerParameters,+ query: queryParameters,+ }, initOverrides);++ return new runtime.JSONApiResponse(response, (jsonValue) => DatasetFromJSON(jsonValue));+ }++ /**+ */+ async datasetsEndPreparationCreate(requestParameters: DatasetsEndPreparationCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<Dataset> {+ const response = await this.datasetsEndPreparationCreateRaw(requestParameters, initOverrides);+ return await response.value();+ }+/*** Dataset event stream (SSE): landing, cells, runs and chat*/diff --git a/frontend/src/routes/_auth.tsx b/frontend/src/routes/_auth.tsxindex 824559e8..4b3898a0 100644--- a/frontend/src/routes/_auth.tsx+++ b/frontend/src/routes/_auth.tsx@@ -61,6 +61,7 @@ const DYNAMIC_PARENTS = new Set(["observability","datasets","optimiser",+ "inference",]);const HIDDEN_BREADCRUMB_PATHS = new Set(["/evaluations/runs"]);@@ -119,6 +120,13 @@ function useCachedName(select: (experiment) => `${experiment.capabilityName || "Run"} · ${experiment.id.slice(0, 8)}`,});+ const deployedModelNameQuery = useQuery({+ enabled: kind === "inference" && !!slug,+ queryFn: () => apiClient.deployedModels.deployedModelsRetrieve({ id: slug ?? "" }),+ queryKey: ["deployed-model", slug],+ select: (model) => model.modelId,+ });+const evaluationNameQuery = useQuery({enabled: kind === "evaluations" && evaluationFormat !== "decision" && !!slug,queryFn: () => apiClient.evalRuns.evalRunsRetrieve({ id: slug ?? "" }),@@ -144,6 +152,7 @@ function useCachedName(if (kind === "projects") return projectNameQuery.data;if (kind === "datasets") return datasetNameQuery.data;if (kind === "optimiser") return experimentNameQuery.data;+ if (kind === "inference") return deployedModelNameQuery.data;return undefined;}diff --git a/frontend/src/routes/_auth/datasets.index.tsx b/frontend/src/routes/_auth/datasets.index.tsxindex 0699ad22..2949ceed 100644--- a/frontend/src/routes/_auth/datasets.index.tsx+++ b/frontend/src/routes/_auth/datasets.index.tsx@@ -125,7 +125,9 @@ function ProjectDatasets({ projectId }: { projectId: string }) {<DatasetsBrowser{...filters}error={query.error}- isLoading={query.isPending}+ isLoading={+ query.isPending || (!datasets.length && projects.isPending && !query.isError)+ }key={JSON.stringify([ds_search, ds_role, ds_capability])}rowSearch={{ projectId }}/>diff --git a/frontend/src/routes/_auth/index.tsx b/frontend/src/routes/_auth/index.tsxindex ca256292..9470ecd7 100644--- a/frontend/src/routes/_auth/index.tsx+++ b/frontend/src/routes/_auth/index.tsx@@ -1,11 +1,12 @@-import { useCallback, useEffect, useState } from "react";+import { useEffect, useState } from "react";-import { useQuery, useQueryClient } from "@tanstack/react-query";+import { useQuery } from "@tanstack/react-query";import { createFileRoute } from "@tanstack/react-router";import desktopMonitorIcon from "@/assets/desktop-monitor.svg";import apiClient from "@/client";import { CapabilityBrowser } from "@/components/capability-grid";+import { CodingAgentIcon } from "@/components/coding-agent-icon";import { CreateProjectDialog } from "@/components/create-project";import {NoProjectsEmptyState,@@ -15,10 +16,10 @@ import { QuickstartEmbed } from "@/components/quickstart/quickstart-embed";import { RepositorySnapshot } from "@/components/repository-snapshot";import { Alert } from "@/components/ui/alert";import { Button } from "@/components/ui/button";+import { Icon } from "@/components/ui/icons";import { PageHeader } from "@/components/ui/page-header";import { PageShell } from "@/components/ui/page-shell";import { LoadingState } from "@/components/ui/spinner";-import { Switch } from "@/components/ui/switch";import { useAuthContext } from "@/contexts/auth-context";import { useOnboardingMilestones } from "@/hooks/use-activity";import { setStoredProjectId } from "@/hooks/use-project-search-sync";@@ -32,33 +33,11 @@ export const Route = createFileRoute("/_auth/")({component: AgentPage,});-function AgentHeader({- graph,- previewNewUser,- onPreviewNewUserChange,-}: {- graph?: AgentGraph;- previewNewUser: boolean;- onPreviewNewUserChange: (checked: boolean) => void;-}) {+function AgentHeader({ graph }: { graph?: AgentGraph }) {return (<header className="space-y-3"><PageHeader- actions={- <>- {graph && <RepositorySnapshot graph={graph} />}- {import.meta.env.DEV && (- <label className="flex items-center gap-2 text-sm text-muted-foreground">- <Switch- checked={previewNewUser}- onCheckedChange={onPreviewNewUserChange}- size="sm"- />- Dev: new user- </label>- )}- </>- }+ actions={graph && <RepositorySnapshot graph={graph} />}className="flex-col sm:flex-row sm:flex-wrap [&>div:last-child]:max-w-full [&>div:last-child]:min-w-0"description="Capabilities, prompts, tools and evals."icon={@@ -75,102 +54,98 @@ function AgentHeader({);}+function OnboardingStrip({ projectId }: { projectId: string }) {+ const storageKey = `onboarding-dismissed:${projectId}`;+ const [dismissed, setDismissed] = useState(() => {+ try {+ return localStorage.getItem(storageKey) === "1";+ } catch {+ return false;+ }+ });+ const onboarding = useOnboardingMilestones(projectId, "agent");+ const steps = onboarding.data ?? [];+ const completed = steps.filter((step) => step.completedAt).length;+ const current = steps.find((step) => !step.completedAt);+ const reporter = current?.actorName ? current : steps.find((step) => step.actorName);+ if (dismissed || !completed || !current) return null;+ return (+ <section+ aria-label="Onboarding status"+ className="flex min-h-10 items-center gap-3 border border-border bg-card py-1 pr-1 pl-3 text-xs"+ >+ {reporter?.actorKind && reporter.actorName ? (+ <span className="inline-flex shrink-0 items-center gap-1.5 text-muted-foreground">+ <CodingAgentIcon kind={reporter.actorKind} />+ <span className="hidden sm:inline">{reporter.actorName}</span>+ </span>+ ) : null}+ <span className="min-w-0 truncate">Onboarding · {current.label}</span>+ <span className="ml-auto flex shrink-0 items-center gap-3">+ <span+ aria-label="Onboarding progress"+ aria-valuemax={steps.length}+ aria-valuemin={0}+ aria-valuenow={completed}+ aria-valuetext={`${completed} of ${steps.length} stages complete`}+ className="hidden w-40 gap-0.5 border border-border bg-background p-0.5 sm:flex"+ role="progressbar"+ >+ {steps.map((step) => (+ <span+ aria-hidden="true"+ className={cn("h-2 flex-1", step.completedAt ? "bg-primary" : "bg-muted")}+ key={step.kind}+ />+ ))}+ </span>+ <span className="text-muted-foreground tabular-nums">+ {completed} of {steps.length}+ </span>+ <Button+ aria-label="Dismiss onboarding progress"+ onClick={() => {+ try {+ localStorage.setItem(storageKey, "1");+ } catch {}+ setDismissed(true);+ }}+ size="icon-sm"+ variant="ghost"+ >+ <Icon.close />+ </Button>+ </span>+ </section>+ );+}+function CapabilitiesSection({graph,isLoading,error,projectId,projectName,- devPreview = false,}: {graph?: AgentGraph;isLoading: boolean;error: Error | null;projectId: string;projectName?: string;- devPreview?: boolean;}) {const capabilities: CapabilityList[] = graph?.capabilities ?? [];- const onboarding = useOnboardingMilestones(projectId, "agent");- const onboardingActive =- !!onboarding.data?.[0]?.completedAt && !onboarding.data?.every((step) => step.completedAt);- const [started, setStarted] = useState(false);- const [finished, setFinished] = useState(false);- const [exiting, setExiting] = useState(false);- const [revealed, setRevealed] = useState(false);- const [replay, setReplay] = useState(0);- const queryClient = useQueryClient();- const onComplete = useCallback(() => setFinished(true), []);- useEffect(() => {- if (onboardingActive) setStarted(true);- }, [onboardingActive]);- useEffect(() => {- if (finished && !devPreview)- void queryClient.invalidateQueries({ queryKey: ["agent-graph", projectId] });- }, [finished, devPreview, projectId, queryClient]);- useEffect(() => {- if (!finished || !capabilities.length) return;- const reduced = window.matchMedia("(prefers-reduced-motion: reduce)").matches;- const pause = window.setTimeout(() => setExiting(true), 1100);- const reveal = window.setTimeout(() => setRevealed(true), reduced ? 1100 : 1340);- return () => {- window.clearTimeout(pause);- window.clearTimeout(reveal);- };- }, [finished, capabilities.length]);-- const showOnboarding =- !revealed && (devPreview || onboardingActive || started || finished || !capabilities.length);- if (isLoading && !graph && !devPreview && !started)- return <LoadingState fullPage label="Loading agent" />;- if (error && !graph && !devPreview && !started)+ if (isLoading) return <LoadingState fullPage label="Loading agent" />;+ if (error && !graph)return <Alert variant="destructive">Failed to load capabilities: {error.message}</Alert>;- if (showOnboarding)+ if (!capabilities.length)return (- <div- className={cn(- "grid min-w-0 flex-1 place-items-center transition-opacity duration-200 motion-reduce:transition-none",- exiting && "opacity-0"- )}- >- <QuickstartEmbed- autoPlay={replay > 0}- devPreview={devPreview}- key={replay}- onComplete={onComplete}- projectId={projectId}- projectName={projectName}- />- {finished && error && (- <Alert variant="destructive">Couldn’t load your capabilities. Retrying…</Alert>- )}+ <div className="grid min-w-0 flex-1 place-items-center">+ <QuickstartEmbed projectId={projectId} projectName={projectName} /></div>);return (- <div- className={cn(- "min-w-0 space-y-4",- revealed &&- "motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-2 motion-safe:duration-300"- )}- >- {devPreview && (- <div className="flex items-center justify-between gap-3 text-xs text-muted-foreground">- <span>Preview complete · showing this project’s capabilities</span>- <Button- onClick={() => {- setFinished(false);- setExiting(false);- setRevealed(false);- setReplay((value) => value + 1);- }}- size="xs"- variant="secondary"- >- Replay onboarding- </Button>- </div>- )}+ <div className="min-w-0 space-y-4">+ <OnboardingStrip projectId={projectId} /><CapabilityBrowser capabilities={capabilities} projectId={projectId} /></div>);@@ -179,7 +154,6 @@ function CapabilitiesSection({function AgentPage() {const navigate = Route.useNavigate();const search = Route.useSearch();- const [previewNewUser, setPreviewNewUser] = useState(false);const graphQuery = useQuery({enabled: !!search.projectId,queryFn: () => apiClient.agent.agentRetrieve({ project: search.projectId! }),@@ -235,15 +209,9 @@ function AgentPage() {const createProjectDialog = (<CreateProjectDialog onOpenChange={setCreateOpen} open={createOpen} />);- const header = (- <AgentHeader- graph={previewNewUser ? undefined : graphQuery.data}- onPreviewNewUserChange={setPreviewNewUser}- previewNewUser={previewNewUser}- />- );+ const header = <AgentHeader graph={graphQuery.data} />;- if (projectsLoading && !previewNewUser) {+ if (projectsLoading) {return (<PageShell header={header} variant="scroll"><LoadingState fullPage label="Loading projects" />@@ -251,7 +219,7 @@ function AgentPage() {);}- if (projectsError && !projectsData && !previewNewUser) {+ if (projectsError && !projectsData) {return (<PageShell header={header} variant="scroll"><Alert variant="destructive">@@ -261,28 +229,16 @@ function AgentPage() {);}- if (previewNewUser || projects.length === 0) {+ if (projects.length === 0) {return (<PageShellclassName="flex min-h-full flex-col gap-6 space-y-0"header={header}variant="scroll">- {previewNewUser && search.projectId ? (- <CapabilitiesSection- devPreview- error={graphQuery.error}- graph={graphQuery.data}- isLoading={graphQuery.isLoading}- key={`preview:${search.projectId}`}- projectId={search.projectId}- projectName={projects.find((project) => project.id === search.projectId)?.name}- />- ) : (- <div className="grid min-w-0 flex-1 place-items-center">- <NoProjectsEmptyState />- </div>- )}+ <div className="grid min-w-0 flex-1 place-items-center">+ <NoProjectsEmptyState />+ </div>{createProjectDialog}</PageShell>);diff --git a/frontend/src/routes/_auth/inference_.$modelId.tsx b/frontend/src/routes/_auth/inference_.$modelId.tsxindex 6fabe713..b33e4445 100644--- a/frontend/src/routes/_auth/inference_.$modelId.tsx+++ b/frontend/src/routes/_auth/inference_.$modelId.tsx@@ -112,7 +112,7 @@ function ModelDetailPage() {{(model.status === "failed" || model.status === "deleted") && model.finetuningJobId ? (<RedeployBanner model={model} />) : null}- {model.capabilityId ? (+ {model.capabilityId && model.inferenceContract !== "decision" ? (<div className="flex flex-wrap items-center gap-2 text-xs text-muted-foreground"><CapabilityChipcapabilityId={model.capabilityId}@@ -134,7 +134,6 @@ function ModelDetailPage() {Serverless API snippet</Button></div>- <p className="px-4 py-3 text-xs text-muted-foreground">Scales on demand</p></Card><DedicatedDeploymentSection model={model} projectId={projectId} /><ModelPerformance modelId={model.id} />diff --git a/frontend/src/styles.css b/frontend/src/styles.cssindex d873306a..abc3cfe1 100644--- a/frontend/src/styles.css+++ b/frontend/src/styles.css@@ -764,18 +764,3 @@ body:has(animation: none;}}--@keyframes job-active-pulse {- 0%,- 100% {- opacity: 1;- }- 50% {- opacity: 0.8;- }-}-@media (prefers-reduced-motion: no-preference) {- .job-active-pulse {- animation: job-active-pulse 2.4s ease-in-out infinite;- }-}diff --git a/overbae/api/activity.py b/overbae/api/activity.pyindex e8f31efd..c3ffa8c4 100644--- a/overbae/api/activity.py+++ b/overbae/api/activity.py@@ -1,7 +1,10 @@import asyncioimport json+import logging+import redis.asyncio as aredisfrom asgiref.sync import sync_to_async+from django.conf import settingsfrom django.db import connectionsfrom django.http import StreamingHttpResponsefrom drf_spectacular.utils import extend_schema, extend_schema_serializer@@ -14,6 +17,9 @@ from rest_framework.response import Responsefrom overbae.api.scoping import project_ids_forfrom overbae.services import activity+logger = logging.getLogger(__name__)+STREAM_SECONDS = 300+class ActivityAssetSerializer(serializers.Serializer):kind = serializers.ChoiceField(choices=["dataset", "capability", "evaluation", "training_job"])@@ -123,18 +129,43 @@ class ActivityViewSet(viewsets.GenericViewSet):finally:connections.close_all()+ channels = [activity.channel(user_id=request.user.pk)]+ if project:+ channels.append(activity.channel(project))+async def stream():+ await sync_to_async(connections.close_all)()+ loop = asyncio.get_running_loop()+ # The stream ends so the client reconnects and membership is checked again.+ deadline = loop.time() + STREAM_SECONDS+ client = aredis.from_url(settings.CELERY_BROKER_URL, decode_responses=True)+ pubsub = client.pubsub()previous = None- # Reconnect periodically to revalidate authentication and project membership.- for tick in range(60):- data, revision = await sync_to_async(snapshot, thread_sensitive=True)()- signature = (revision, data["count"], data["unseen_count"])- if signature != previous:- yield f"data: {json.dumps(data)}\n\n"- previous = signature- elif tick % 15 == 0:- yield ": ping\n\n"- await asyncio.sleep(1)+ try:+ await pubsub.subscribe(*channels)+ stale = True+ while loop.time() < deadline:+ if stale:+ data, revision = await sync_to_async(snapshot, thread_sensitive=True)()+ signature = (revision, data["count"], data["unseen_count"])+ if signature != previous:+ yield f"data: {json.dumps(data)}\n\n"+ previous = signature+ message = await pubsub.get_message(ignore_subscribe_messages=True, timeout=15)+ stale = message is not None+ if not stale:+ yield ": ping\n\n"+ continue+ await asyncio.sleep(0.5)+ while await pubsub.get_message(ignore_subscribe_messages=True, timeout=0):+ pass+ finally:+ try:+ await pubsub.unsubscribe()+ await pubsub.aclose()+ await client.aclose()+ except Exception: # noqa: BLE001+ logger.debug("activity stream teardown failed", exc_info=True)response = StreamingHttpResponse(stream(), content_type="text/event-stream")response["Cache-Control"] = "no-cache"diff --git a/overbae/api/datasets.py b/overbae/api/datasets.pyindex 77c71a4a..03ef2a46 100644--- a/overbae/api/datasets.py+++ b/overbae/api/datasets.py@@ -38,6 +38,7 @@ from overbae.services.datasets import (lifecycle,paths,preparation,+ preparation_workflow,selection,store,workbench,@@ -235,6 +236,16 @@ class DatasetViewSet(WorkbenchActions, viewsets.ModelViewSet):return _error(exc)return Response(DatasetSerializer(dataset).data, status=202)+ @extend_schema(request=None, responses={200: DatasetSerializer})+ @action(detail=True, methods=["post"], url_path="end-preparation")+ def end_preparation(self, request, id=None):+ dataset = self.get_object()+ try:+ preparation_workflow.end(dataset)+ except lifecycle.DatasetError as exc:+ return _error(exc)+ return Response(DatasetSerializer(Dataset.objects.get(pk=dataset.pk)).data)+@extend_schema(responses={(200, "application/octet-stream"): OpenApiTypes.BINARY})@action(detail=True, methods=["get"], url_path=r"sources/(?P<artifact_id>[0-9a-f]{64})")def source_file(self, request, id=None, artifact_id=None):diff --git a/overbae/api/dedicated.py b/overbae/api/dedicated.pyindex 437fc461..5efb1735 100644--- a/overbae/api/dedicated.py+++ b/overbae/api/dedicated.py@@ -1,5 +1,6 @@import uuid+from django.http import JsonResponsefrom django.shortcuts import get_object_or_404from drf_spectacular.utils import (OpenApiParameter,@@ -149,7 +150,8 @@ class DedicatedDeploymentView(APIView):deployed = _model(request, deployment_id)row = dedicated.latest_for(deployed)if row is None:- return Response(None)+ # DRF renders None as an empty body, which the generated client cannot parse.+ return JsonResponse(None, safe=False)return Response(DedicatedDeploymentSerializer(row).data)@extend_schema(diff --git a/overbae/migrations/0055_activity_task_index.py b/overbae/migrations/0055_activity_task_index.pynew file mode 100644index 00000000..fe9041d1--- /dev/null+++ b/overbae/migrations/0055_activity_task_index.py@@ -0,0 +1,17 @@+# Generated by Django 6.0.8 on 2026-10-29 11:14++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ('overbae', '0054_merge_dedicated_and_preparation'),+ ]++ operations = [+ migrations.AddIndex(+ model_name='activity',+ index=models.Index(fields=['project', 'task_kind', 'task_id'], name='overbae_act_project_9b81c7_idx'),+ ),+ ]diff --git a/overbae/models/activity.py b/overbae/models/activity.pyindex c0fec68d..52e3e8f6 100644--- a/overbae/models/activity.py+++ b/overbae/models/activity.py@@ -25,7 +25,10 @@ class Activity(models.Model):class Meta:ordering = ["-updated_at", "-id"]- indexes = [models.Index(fields=["project", "-updated_at"])]+ indexes = [+ models.Index(fields=["project", "-updated_at"]),+ models.Index(fields=["project", "task_kind", "task_id"]),+ ]class ActivityRead(models.Model):diff --git a/overbae/services/activity.py b/overbae/services/activity.pyindex 2fa3581a..95260585 100644--- a/overbae/services/activity.py+++ b/overbae/services/activity.py@@ -1,8 +1,10 @@import hashlibimport json+import refrom urllib.parse import urlsplitfrom uuid import UUID+from django.db import transactionfrom django.db.models import Exists, OuterRef, Qfrom django.utils import timezone@@ -15,20 +17,25 @@ from overbae.models import (DatasetPreparation,FinetuningJob,)--AGENTS = {- "codex": ("codex", "Codex"),- "openai-codex": ("codex", "Codex"),- "codex-mcp-client": ("codex", "Codex"),- "claude-code": ("claude", "Claude Code"),- "claude code": ("claude", "Claude Code"),- "cursor": ("cursor", "Cursor"),- "gemini-cli": ("gemini", "Gemini CLI"),-}+from overbae.services.datasets import events++# Clients name themselves differently in MCP initialize and OAuth registration+# ("claude-code" / "Claude Code (overmind)", "codex-mcp-client" / "Codex").+AGENTS = (+ (re.compile(r"^claude[- ]code\b"), "claude", "Claude Code"),+ (re.compile(r"^(openai-)?codex\b"), "codex", "Codex"),+ (re.compile(r"^cursor\b"), "cursor", "Cursor"),+ (re.compile(r"^gemini[- ]cli\b"), "gemini", "Gemini CLI"),+ (re.compile(r"^opencode\b"), "coding_agent", "OpenCode"),+)def actor(client_name):- return AGENTS.get((client_name or "").lower(), ("coding_agent", "Coding agent"))+ name = (client_name or "").strip().lower()+ return next(+ ((kind, label) for pattern, kind, label in AGENTS if pattern.match(name)),+ ("coding_agent", "Coding agent"),+ )def credential_identity(context):@@ -72,6 +79,15 @@ def connected(context):)+def channel(project_id=None, user_id=None):+ return f"activity:project:{project_id}" if project_id else f"activity:user:{user_id}"+++def changed(project_id=None, user_id=None):+ name = channel(project_id, user_id)+ transaction.on_commit(lambda: events.signal(name))++def asset(kind, identity, label):return {"kind": kind, "id": str(identity), "label": str(label)[:160]}@@ -189,10 +205,15 @@ def record(Activity.objects.filter(key=f"preparation:{preparation.pk}").update(updated_at=timezone.now())- if event.actor_kind == "overmind" and actor_kind != "overmind":- Activity.objects.filter(pk=event.pk, actor_kind="overmind").update(+ relabelled = (+ event.actor_kind == "overmind"+ and actor_kind != "overmind"+ and Activity.objects.filter(pk=event.pk, actor_kind="overmind").update(actor_kind=actor_kind, actor_name=actor_name)+ )+ if created or relabelled:+ changed(project_id, user_id)return event@@ -220,6 +241,8 @@ def mark_seen(query, user, ids, through):activity=event, user=user, defaults={"seen_at": through})updated += 1+ if updated:+ changed(user_id=user.pk)return updated@@ -238,13 +261,16 @@ def update_task(project_id, kind, identity, status):}.get(status, status)if normalized not in {"accepted", "running", "completed", "failed", "cancelled"}:return- changed = Activity.objects.filter(- project_id=project_id, task_kind=kind, task_id=str(identity)- ).exclude(status=normalized)- preparation_ids = list(- changed.exclude(preparation=None).values_list("preparation_id", flat=True)+ # A dataset reuses its id for every import, so only the newest request moves.+ latest = (+ Activity.objects.filter(project_id=project_id, task_kind=kind, task_id=str(identity))+ .order_by("-created_at")+ .values("pk")[:1])- changed.update(status=normalized, updated_at=timezone.now())+ rows = Activity.objects.filter(pk__in=latest).exclude(status=normalized)+ preparation_ids = list(rows.exclude(preparation=None).values_list("preparation_id", flat=True))+ if rows.update(status=normalized, updated_at=timezone.now()):+ changed(project_id)if preparation_ids:Activity.objects.filter(key__in=[f"preparation:{identity}" for identity in preparation_ids]@@ -303,7 +329,8 @@ def mcp_succeeded(name, definition, output, context):)returnjob = output.get("training_run") or output.get("finetune") or output.get("job")- if isinstance(job, dict) and job.get("id") and job.get("kind"):+ # Connector syncs keep polling after the request; no status ever closes the job.+ if isinstance(job, dict) and job.get("id") and job.get("kind") not in {None, "connector_sync"}:assets = output_assets(output)training = (output.get("training_run") or output.get("finetune") or output.get("training_job")@@ -412,6 +439,7 @@ def report_onboarding_progress(context, run_id, completed_steps):def milestones(query, path):+ query = query.filter(project__isnull=False)steps = (AGENT_ONBOARDING_STEPSif path == "agent"@@ -446,6 +474,11 @@ def milestones(query, path):).first()or event)+ # Agents sign in per account; their first action in the project connects it.+ if kind == "agent_connected" and not event:+ event = (+ query.exclude(actor_kind__in=["overmind", "cli"]).order_by("created_at").first()+ )result.append({"kind": kind,diff --git a/overbae/services/datasets/events.py b/overbae/services/datasets/events.pyindex 76a59e56..e09104ff 100644--- a/overbae/services/datasets/events.py+++ b/overbae/services/datasets/events.py@@ -10,6 +10,9 @@ import osfrom functools import lru_cachefrom typing import Any+import redis as redis_lib+from django.conf import settings+logger = logging.getLogger(__name__)_REPLAY_CAP = 300@@ -17,8 +20,6 @@ _REPLAY_TTL_SECONDS = 6 * 3600def _redis_client():- from django.conf import settings-url = getattr(settings, "CELERY_BROKER_URL", "redis://localhost:6379/0")if not url.startswith(("redis://", "rediss://", "unix://")):return None@@ -27,8 +28,6 @@ def _redis_client():@lru_cache(maxsize=4)def _client(pid, url):- import redis as redis_lib-return redis_lib.from_url(url, decode_responses=True, socket_connect_timeout=2, socket_timeout=2)@@ -81,3 +80,19 @@ def replay(dataset_id: Any, *, client: Any = None) -> list[dict[str, Any]]:except ValueError:continuereturn out+++@lru_cache(maxsize=4)+def _signal_client(pid, url):+ # Runs on the request thread after commit, so an unreachable Redis must not stall it.+ return redis_lib.from_url(url, socket_connect_timeout=0.2, socket_timeout=0.2)+++def signal(name: str) -> None:+ url = getattr(settings, "CELERY_BROKER_URL", "redis://localhost:6379/0")+ if not url.startswith(("redis://", "rediss://", "unix://")):+ return+ try:+ _signal_client(os.getpid(), url).publish(name, "1")+ except Exception: # noqa: BLE001 — events are advisory, never fatal+ logger.warning("event signal failed for %s", name, exc_info=True)diff --git a/overbae/services/datasets/imports.py b/overbae/services/datasets/imports.pyindex 1affaf7e..b8bfdd9b 100644--- a/overbae/services/datasets/imports.py+++ b/overbae/services/datasets/imports.py@@ -18,7 +18,7 @@ from django.db.models.functions import Leastfrom django.utils import timezonefrom overbae.models import Dataset, DatasetImport, User-from overbae.services.activity import asset, record, update_task+from overbae.services.activity import asset, record, source_ready, update_taskfrom overbae.services.datasets import events, files, heartbeat, llm_calls, operations, pathsfrom overbae.services.datasets import land as landingfrom overbae.services.datasets.lifecycle import DatasetError@@ -719,6 +719,7 @@ def execute(task_id, inputs):rows = 0for target, result in prepared:landing.publish(target, result, user=user)+ source_ready(target, result.cell_id, user)rows += result.cell_fields["rows"]locked.state = DatasetImport.State.COMPLETEdiff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.pyindex 4a15e1e6..92d0b8fd 100644--- a/overbae/services/datasets/land.py+++ b/overbae/services/datasets/land.py@@ -187,8 +187,6 @@ def publish(dataset, prepared, *, user=None):**prepared.dataset_fields, updated_at=timezone.now())dataset.refresh_from_db()-- source_ready(dataset, prepared.cell_id, user)return dataset@@ -203,7 +201,11 @@ def commit(dataset, landing, *, user=None, state=Dataset.State.IDLE, infer_capabstate=state,infer_capability=infer_capability,)- return publish(dataset, prepared, user=user)+ with transaction.atomic():+ dataset = publish(dataset, prepared, user=user)+ if not {"derived_from", "partition_plan"} & landing.spec.keys():+ source_ready(dataset, prepared.cell_id, user)+ return datasetdef read_file(path: Path, **options) -> Landing:diff --git a/overbae/services/datasets/list_activity.py b/overbae/services/datasets/list_activity.pyindex b4fcaf02..bc0d970b 100644--- a/overbae/services/datasets/list_activity.py+++ b/overbae/services/datasets/list_activity.py@@ -11,7 +11,9 @@ def current_work(datasets):)actors = dict(Activity.objects.filter(- task_kind="dataset_pipeline", task_id__in=[str(run.pk) for run in runs]+ project_id__in={dataset.project_id for dataset in datasets},+ task_kind="dataset_pipeline",+ task_id__in=[str(run.pk) for run in runs],).values_list("task_id", "actor_kind"))for run in runs:@@ -38,12 +40,15 @@ def current_work(datasets):for preparation in DatasetPreparation.objects.filter(dataset_id__in=ids, state__in=["preparing", "paused"]):- work[str(preparation.dataset_id)] = {- "label": "Preparing" if preparation.state == "preparing" else "Preparation paused",- "status": "running" if preparation.state == "preparing" else "paused",- "actor_kind": preparation.actor_kind,- "completed": None,- "total": None,- "unit": "",- }+ work.setdefault(+ str(preparation.dataset_id),+ {+ "label": "Preparing" if preparation.state == "preparing" else "Preparation paused",+ "status": preparation.state,+ "actor_kind": preparation.actor_kind,+ "completed": None,+ "total": None,+ "unit": "",+ },+ )return workdiff --git a/overbae/services/datasets/preparation_workflow.py b/overbae/services/datasets/preparation_workflow.pyindex 3bb79fd5..f6a0634d 100644--- a/overbae/services/datasets/preparation_workflow.py+++ b/overbae/services/datasets/preparation_workflow.py@@ -1,3 +1,6 @@+import logging+from datetime import timedelta+from django.db import transactionfrom django.utils import timezone@@ -13,6 +16,9 @@ from overbae.models import (from overbae.services import activityfrom overbae.services.datasets.lifecycle import DatasetError+IDLE_LIMIT = timedelta(hours=24)+logger = logging.getLogger(__name__)+def describe(preparation):return {@@ -132,4 +138,45 @@ def update(dataset, preparation_id, state, outputs):Activity.objects.filter(key=f"preparation:{preparation.pk}").update(status=status, action=action, updated_at=timezone.now())+ activity.changed(dataset.project_id)return preparation+++def end(dataset):+ preparation = DatasetPreparation.objects.filter(+ dataset=dataset, state__in=["preparing", "paused"]+ ).first()+ if not preparation:+ raise DatasetError("This dataset has no open preparation.", code="preparation_not_found")+ return update(dataset, preparation.pk, "cancelled", [])+++def _idle(preparation_ids, cutoff):+ active = Activity.objects.filter(+ key__in=[f"preparation:{pk}" for pk in preparation_ids], updated_at__gte=cutoff+ ).values_list("task_id", flat=True)+ return DatasetPreparation.objects.filter(+ pk__in=preparation_ids, state__in=["preparing", "paused"], updated_at__lt=cutoff+ ).exclude(pk__in=[value for value in active if value])+++def expire():+ cutoff = timezone.now() - IDLE_LIMIT+ candidates = list(+ DatasetPreparation.objects.filter(+ state__in=["preparing", "paused"], updated_at__lt=cutoff+ ).values_list("pk", "dataset_id")+ )+ expired = 0+ for preparation_id, dataset_id in candidates:+ try:+ with transaction.atomic():+ # Same lock order as start() and update(); an agent update since the scan wins.+ dataset = Dataset.objects.select_for_update().filter(pk=dataset_id).first()+ if dataset is None or not _idle([preparation_id], cutoff).exists():+ continue+ update(dataset, preparation_id, "cancelled", [])+ expired += 1+ except Exception:+ logger.exception("expiring dataset preparation %s failed", preparation_id)+ return expireddiff --git a/overbae/services/mcp/server.py b/overbae/services/mcp/server.pyindex c9f34418..ce33071e 100644--- a/overbae/services/mcp/server.py+++ b/overbae/services/mcp/server.py@@ -76,8 +76,7 @@ mcp_server = Server("Declare the final step consumer (decision_train, decision_eval, chat_train or model_eval) so previews validate nested targets. Use batch_rows only for row-independent steps; sorting, grouping and deduplication require the full population. Preserve evidenced target semantics and structured provenance; never remove them to bypass a validator. Preview defers absolute min_rows/max_rows bounds to publication; lineage and preserve_rows checks remain enforced. Inspect deferred checks before publishing. Follow poll_after_seconds; queued work alone is not a failure or reason to resubmit. Report format compatibility separately from task suitability, which remains unmeasured without attributable evidence. ""Author explicit step IDs and input dependencies. Converge intended branches with inputs=[earlier IDs]; disjoint rows concatenate in declared order, overlapping source_row identities fail. The last step is the output: inspect flow.unconsumed_steps before publication. Training preparation should end in trainable examples with review metadata, not disconnected inspection tables; never invent targets or treat flags as resolved. Script conditions cite their entrypoint line and describe code, not independently verified semantics. Receipts record actual parent cells, counts and fingerprints. Pin sources and use stable request keys. ""Use author-dataset-transformation for conditional authoring, retrieval and adaptation. inspect_dataset_workbench(pipeline=revision ID) retrieves an exact recipe and its family history. Only retained packages execute in the approved isolated runtime; other code and semantic/provider work stay in the native environment. Technical format checks do not prove semantic quality or exhaustive/exclusive branches. "- "Before dataset preparation work, inspect_dataset_workbench and resume its preparation_workflow or call start_dataset_preparation with a stable request_key. Keep it preparing across local authoring, previews and publications. Use update_dataset_preparation with state=completed and verified published output cell UUIDs only when all requested agent work is finished; use paused when stopping temporarily or cancelled when abandoning. Individual job completion does not finish preparation. "- "During every repository onboarding run, including reruns and resumes, read overmind://activity for the ten-stage roadmap. Before starting the next stage and after each completion, call report_onboarding_progress using one persistent UUID run_id and the verified consecutive completed count. Await a successful receipt; retry failed reports with the same values and disclose when Console progress cannot be updated. This reporting is required even if older installed skills only describe chat updates. These local-work receipts update the landing page without creating notifications. "+ "Before dataset preparation work, inspect_dataset_workbench and resume its preparation_workflow or call start_dataset_preparation with a stable request_key. Keep it preparing across local authoring, previews and publications. Use update_dataset_preparation with state=completed and verified published output cell UUIDs only when all requested agent work is finished; use paused when stopping temporarily or cancelled when abandoning. Individual job completion does not finish preparation. An open preparation ends after 24 hours without activity or when the user ends it in the Console. ""Local scanning, file transfers, credentials and repository execution use the CLI ""handoffs in the relevant resources/prompts. The server does not edit local files. ""When a user wants a visual view, open the ordinary Console for this project; "diff --git a/overbae/tasks/datasets.py b/overbae/tasks/datasets.pyindex b876c7d4..0ebec3ee 100644--- a/overbae/tasks/datasets.py+++ b/overbae/tasks/datasets.py@@ -443,9 +443,10 @@ def reap_stuck_runs() -> dict[str, Any]:from datetime import timedeltafrom overbae.models import Dataset, DatasetPipelineRun- from overbae.services.datasets import imports+ from overbae.services.datasets import imports, preparation_workflowimports.reconcile()+ expired = preparation_workflow.expire()now = timezone.now()from overbae.services.datasets.workbench import expire_runs@@ -477,7 +478,7 @@ def reap_stuck_runs() -> dict[str, Any]:_emit(dataset_id, {"type": "run_failed", "error": "The worker stopped before this finished."})- return {"reaped": len(ids)}+ return {"reaped": len(ids), "preparations_expired": expired}@shared_task(diff --git a/tests/journeys/console/test_console.py b/tests/journeys/console/test_console.pyindex c4193501..2b27865e 100644--- a/tests/journeys/console/test_console.py+++ b/tests/journeys/console/test_console.py@@ -1,11 +1,13 @@import hashlibimport jsonimport uuid+from datetime import timedeltafrom django.utils import timezonefrom modal_shared.training_monitoring import fingerprintfrom overbae.models import (+ Activity,Cell,DataPartitionMember,DataPartitionPlan,@@ -13,6 +15,7 @@ from overbae.models import (DatasetContext,DatasetPipeline,DatasetPipelineRun,+ DatasetPreparation,DedicatedDeployment,DeployedModel,EvalRun,@@ -22,20 +25,23 @@ from overbae.models import ()from overbae.services import activity as activity_servicefrom overbae.services import training_monitoring+from overbae.tasks.datasets import reap_stuck_runsfrom ..datasets import tickets, uploadfrom ..stack import drain, settle-def test_embedded_onboarding_copies_setup_and_switches_to_data(console):- console.sees("Overmind works best via the MCP")+def test_embedded_onboarding_copies_setup_and_switches_to_data(console, console_url, live_api):console._browser.call(console._page.context.grant_permissions, ["clipboard-read", "clipboard-write"])console.press("Copy onboarding prompt")console.sees("Prompt copied")prompt = console._browser.call(console._page.evaluate, "navigator.clipboard.readText()")- assert prompt == "Set me up on Overmind https://console.overmindlab.ai/setup.md"+ assert prompt == (+ f"Set me up on Overmind\n\nusing the API at {live_api.url.rstrip('/')}: "+ f"{console_url.rstrip('/')}/setup.md"+ )console.wait_until("""() => {const panel = document.querySelector('section[aria-label="Get started"]');return panel.querySelector('a[href$="/setup.md"]') &&@@ -100,20 +106,17 @@ def test_activity_outcomes_and_setup_progress_survive_console_reload(reporter = progress["milestones"][2]["actor_name"]assert reporterconsole.goto(f"/?projectId={project}")- console.wait_until(- "() => document.querySelector('[aria-current=step]')?.textContent.includes('Inspect repository')"- )+ console.sees("Onboarding · Inspect repository")+ console.sees("2 of 10")console._browser.call(lambda: (- console._page.get_by_label("Onboarding agent", exact=True)+ console._page.get_by_label("Onboarding status", exact=True).get_by_text(reporter, exact=True).wait_for()))workshop.call("report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 9})- console.wait_until(- "() => document.querySelector('[aria-current=step]')?.textContent.includes('Instrument capabilities')"- )+ console.sees("Onboarding · Instrument capabilities")rest_for(workshop.api_key).request("POST","/api/v1/sync",@@ -130,23 +133,20 @@ def test_activity_outcomes_and_setup_progress_survive_console_reload(},)console.wait_until("""() => {- return document.querySelector('[aria-current=step]')?.textContent.includes('Instrument capabilities') && document.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow') === '9' && !document.body.textContent.includes('Copy onboarding prompt') && !document.body.textContent.includes('Get started');+ return [...document.querySelectorAll('h3')].some(node => node.textContent.includes('Onboarding capability')) && document.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow') === '9' && !document.body.textContent.includes('Copy onboarding prompt');}""")console.save_evidence("activity-and-onboarding")console._browser.call(console._page.set_viewport_size, {"width": 390, "height": 844})console.wait_until("""() => {- const panel = document.querySelector('[aria-label="Agent onboarding"]');- if (!panel) return false;- const rect = panel.getBoundingClientRect();- return rect.left >= 0 && rect.right <= innerWidth && panel.scrollWidth <= panel.clientWidth;+ const strip = document.querySelector('[aria-label="Onboarding status"]');+ if (!strip) return false;+ const rect = strip.getBoundingClientRect();+ return rect.left >= 0 && rect.right <= innerWidth && strip.scrollWidth <= strip.clientWidth;}""")console.save_evidence("onboarding-mobile")workshop.call("report_onboarding_progress", {"run_id": onboarding_run, "completed_steps": 10})console.wait_until(- "() => document.querySelector('[role=progressbar]')?.getAttribute('aria-valuenow') === '10'"- )- console.wait_until(- "() => [...document.querySelectorAll('h3')].some(node => node.textContent.includes('Onboarding capability')) && !document.querySelector('[role=progressbar]')"+ "() => !document.querySelector('[aria-label=\"Onboarding status\"]') && [...document.querySelectorAll('h3')].some(node => node.textContent.includes('Onboarding capability'))")console.save_evidence("onboarding-complete-capabilities")@@ -899,6 +899,42 @@ def test_dataset_preparation_persists_between_jobs_until_agent_finishes(console.healthy()+def test_console_ends_an_open_preparation_and_idle_preparations_expire(console, workshop):+ project = workshop.project()["id"]+ datasets = [+ workshop.call(+ "start_dataset", {"name": name, "brief": "Prepare support rows", "intent": "train"}+ )["dataset"]["id"]+ for name in ("Abandoned preparation", "Idle preparation", "Recently active preparation")+ ]+ for dataset in datasets:+ workshop.call(+ "start_dataset_preparation", {"dataset": dataset, "request_key": f"open-{dataset}"}+ )+ console.goto(f"/datasets/{datasets[0]}?projectId={project}")+ console.sees("Preparing")+ console.press("End preparation")+ console.wait_until("() => !document.body.textContent.includes('End preparation')")+ ended = workshop.call("inspect_dataset_workbench", {"dataset": datasets[0]})+ assert ended["preparation_workflow"]["state"] == "cancelled"++ idle = DatasetPreparation.objects.get(dataset_id=datasets[1])+ active = DatasetPreparation.objects.get(dataset_id=datasets[2])+ stale = timezone.now() - timedelta(hours=25)+ DatasetPreparation.objects.filter(pk__in=[idle.pk, active.pk]).update(updated_at=stale)+ Activity.objects.filter(key=f"preparation:{idle.pk}").update(updated_at=stale)+ assert reap_stuck_runs()["preparations_expired"] == 1+ kept = workshop.call("inspect_dataset_workbench", {"dataset": datasets[2]})+ assert kept["preparation_workflow"]["state"] == "preparing"+ expired = workshop.call("inspect_dataset_workbench", {"dataset": datasets[1]})+ assert expired["preparation_workflow"]["state"] == "cancelled"+ restarted = workshop.call(+ "start_dataset_preparation", {"dataset": datasets[1], "request_key": "after-expiry"}+ )+ assert restarted["preparation_workflow"]["state"] == "preparing"+ console.healthy()++def test_evaluation_scope_link_settles_on_trajectory_and_supports_repeat_clicks(console, workshop):project = workshop.project()["id"]console.goto(f"/evaluations?projectId={project}&view=matrix")diff --git a/tests/test_activity_contract.py b/tests/test_activity_contract.pyindex b5f672ab..e14eab47 100644--- a/tests/test_activity_contract.py+++ b/tests/test_activity_contract.py@@ -41,15 +41,8 @@ def client_for(context):return client-def test_mcp_mutations_share_activity_with_console_without_logging_inspections():+def test_feed_never_copies_tool_arguments_and_failed_calls_record_nothing():context = mcp_context(permission=["read", "write"], client_name="codex")- call(context, "list_datasets")- before = Activity.objects.count()- for _ in range(3):- read_activity(context)- call(context, "list_datasets")- assert Activity.objects.count() == before-created = call(context,"create_eval_matrix_row",@@ -57,19 +50,9 @@ def test_mcp_mutations_share_activity_with_console_without_logging_inspections()type="llm",source="Do not include this criterion in notifications: secret-evidence",)- project = str(context.project.pk)- client = client_for(context)- feed = client.get("/api/activity/", {"project": project})+ feed = client_for(context).get("/api/activity/", {"project": str(context.project.pk)})assert feed.status_code == 200, feed.data- event = next(item for item in feed.data["results"] if item["kind"] == "evaluation_added")- assert event["actor_kind"] == "codex"- assert event["actor_name"] == "Codex"- assert event["assets"][0]["id"] == created["row"]["id"]assert "secret-evidence" not in str(feed.data)- assert next(- step for step in read_activity(context)["milestones"] if step["kind"] == "agent_connected"- )["completed_at"]- assert client.get("/api/activity/", {"project": project, "limit": 1}).data["next_offset"] == 1call(context, "delete_eval_matrix_row", row=created["row"]["id"])after = read_activity(context)@@ -201,78 +184,6 @@ def test_reported_onboarding_uses_current_roadmap_without_notification_noise():assert rejected.isError-def test_dataset_creation_is_an_asset_action_not_a_source_import_job():- context = mcp_context(permission=["read", "write"], client_name="codex")- result = call(- context, "start_dataset", name="Passenger review", brief="Review passenger records"- )- event = Activity.objects.get(project=context.project, action="Created")- assert event.actor_name == "Codex"- assert event.assets == [- {"kind": "dataset", "id": result["dataset"]["id"], "label": "Passenger review"}- ]- assert event.task_id == ""--- "mode,action",- [- ("preview", "Requested a transformation preview for"),- ("publish", "Requested a transformation of"),- ],-)-def test_transformation_activity_uses_recorded_mode(mode, action):- from types import SimpleNamespace- from uuid import uuid4-- from overbae.services.activity import mcp_succeeded-- context = mcp_context(permission=["read", "write"], client_name="codex")- dataset_id, run_id = str(uuid4()), str(uuid4())- mcp_succeeded(- "run_dataset_pipeline",- SimpleNamespace(read_only=False),- {- "dataset": dataset_id,- "run": {"mode": mode},- "job": {"kind": "dataset_pipeline", "id": run_id, "status": "queued"},- },- context,- )- event = Activity.objects.get(task_id=run_id)- assert event.action == action- assert event.actor_name == "Codex"- assert event.assets[0]["id"] == dataset_id---def test_decision_training_activity_tracks_training_run_and_dataset():- from types import SimpleNamespace-- from overbae.services.activity import mcp_succeeded-- context = mcp_context(permission=["read", "write"], client_name="codex")- dataset = Dataset.objects.create(project=context.project, name="Passengers")- job = FinetuningJob.objects.create(project=context.project, dataset=dataset, status="queued")- mcp_succeeded(- "start_decision_job",- SimpleNamespace(read_only=False),- {- "training_run": {"kind": "finetune_job", "id": str(job.pk), "status": "queued"},- "decision_job": {- "kind": "decision_job",- "id": "separate-public-id",- "status": "queued",- },- },- context,- )- event = Activity.objects.get(task_id=str(job.pk))- assert event.task_kind == "finetune_job"- assert event.status == "queued"- assert event.action == "Started training run"- assert event.assets == [{"kind": "training_job", "id": str(job.pk), "label": job.name}]--def test_preparation_completion_rejects_foreign_outputs_and_unfinished_jobs():context = mcp_context(permission=["read", "write"], client_name="codex")peer = mcp_context(permission=["read", "write"])diff --git a/tests/test_dataset_gate.py b/tests/test_dataset_gate.pyindex 2a4de31b..63ef55e7 100644--- a/tests/test_dataset_gate.py+++ b/tests/test_dataset_gate.py@@ -139,7 +139,7 @@ def test_a_live_transformation_on_an_old_dataset_is_not_reaped():format="json",)assert started.status_code == 202, started.data- assert dataset_tasks.reap_stuck_runs() == {"reaped": 0}+ assert dataset_tasks.reap_stuck_runs()["reaped"] == 0train.refresh_from_db()assert train.state == Dataset.State.RUNNING@@ -151,7 +151,7 @@ def test_the_reaper_fails_a_state_only_after_that_state_own_limit():Dataset.objects.filter(pk=evaluation.pk).update(state="landing", updated_at=timezone.now() - age)- assert dataset_tasks.reap_stuck_runs() == {"reaped": 1}+ assert dataset_tasks.reap_stuck_runs()["reaped"] == 1train.refresh_from_db()evaluation.refresh_from_db()assert (train.state, evaluation.state) == ("running", "error")