Skip to content

The platform for continuously improving AI agents.

Fix desktop setup, recovery and data navigation (#277)

Tyler-Edwards744bba6f3dfc
diff --git a/frontend/.env.production b/frontend/.env.production
index 86beb682..1e401019 100644
--- a/frontend/.env.production
+++ b/frontend/.env.production
@@ -1,6 +1,6 @@
VITE_API_BASE_URL=https://api.overmindlab.ai
VITE_PUBLIC_POSTHOG_KEY=phc_XrIVhixaz5sOqrdzpRwwqlvKXilmcy3PWPgdk0pemZa
-VITE_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com
+VITE_PUBLIC_POSTHOG_HOST=https://v.overmindlab.ai
VITE_CLERK_PUBLISHABLE_KEY=pk_live_Y2xlcmsub3Zlcm1pbmRsYWIuYWkk
# Feature flags — dataset workshop, finetuning, inference
diff --git a/frontend/.env.staging b/frontend/.env.staging
index a1e41bf5..55118c68 100644
--- a/frontend/.env.staging
+++ b/frontend/.env.staging
@@ -1,6 +1,6 @@
VITE_API_BASE_URL=https://api-staging.overmindlab.ai
VITE_PUBLIC_POSTHOG_KEY=phc_XrIVhixaz5sOqrdzpRwwqlvKXilmcy3PWPgdk0pemZa
-VITE_PUBLIC_POSTHOG_HOST=https://eu.i.posthog.com
+VITE_PUBLIC_POSTHOG_HOST=https://v.overmindlab.ai
VITE_CLERK_PUBLISHABLE_KEY=pk_test_cGxlYXNlZC1mbGVhLTIuY2xlcmsuYWNjb3VudHMuZGV2JA
# Feature flags — dataset workshop, finetuning, inference
diff --git a/frontend/bun.lock b/frontend/bun.lock
index ad5449c8..3b93afb6 100644
--- a/frontend/bun.lock
+++ b/frontend/bun.lock
@@ -7,7 +7,6 @@
"dependencies": {
"@clerk/clerk-react": "^5.61.3",
"@lobehub/icons": "^5.10.1",
- "@posthog/react": "^1.10.3",
"@radix-ui/react-checkbox": "^1.3.6",
"@tailwindcss/vite": "^4.3.2",
"@tanstack/react-query": "^5.101.2",
@@ -387,8 +386,6 @@
"@posthog/core": ["@posthog/[email protected]", "", { "dependencies": { "@posthog/types": "^1.392.0" } }, "sha512-o6ajIwN5zXoNP0D4H/QPmOyibNTUkSyOR6ya7AG5U2ywXx4awo72L2KnCoiZPQM5x/bXv6jPBdimH8M18Ax0aw=="],
- "@posthog/react": ["@posthog/[email protected]", "", { "peerDependencies": { "@types/react": ">=16.8.0", "posthog-js": ">=1.257.2", "react": ">=16.8.0" }, "optionalPeers": ["@types/react"] }, "sha512-Qu//fGQmVlX0B9kTA3LLg67e7AYLEmeuA0Bf1qSyUM0uUILcRQGjQezhNQPLYSTakOqvXEnl6fM2iQBF6Toxrw=="],
-
"@posthog/types": ["@posthog/[email protected]", "", {}, "sha512-Qg6Gl7/1vlr8+gPtBi5gwnLgAgiyFoKOVmTvTtDcvya9cpTwZfna7rQmkGQ4B63CunUYNNbOlqcwiUwUDyTK6w=="],
"@primer/octicons": ["@primer/[email protected]", "", { "dependencies": { "object-assign": "^4.1.1" } }, "sha512-E0eMV8nXexrs7Vro7PdS8v/JfvvYCMh8HN6CXJ9l8fk9atZaY05fVUcyiAh5KjEJu7IxdFy4URfHGpM7+iOl1A=="],
diff --git a/frontend/package.json b/frontend/package.json
index cca921d7..c1f75d51 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -2,7 +2,6 @@
"dependencies": {
"@clerk/clerk-react": "^5.61.3",
"@lobehub/icons": "^5.10.1",
- "@posthog/react": "^1.10.3",
"@radix-ui/react-checkbox": "^1.3.6",
"@tailwindcss/vite": "^4.3.2",
"@tanstack/react-query": "^5.101.2",
diff --git a/frontend/public/setup.md b/frontend/public/setup.md
index 1191980a..092e3376 100644
--- a/frontend/public/setup.md
+++ b/frontend/public/setup.md
@@ -16,6 +16,10 @@ Run from the repository root. Every step is safe to repeat.
sandbox 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 when
it offers one or else by following the `Next:` line `init` printed, then call it again.
+ If the prompt supplies `project_id`, verify that exact project is in the connected catalogue
+ and use it for setup. Preserve it as `project-id` in `overmind.toml` before repository sync;
+ do not create a different project. If the repository already names another project, ask the
+ user which destination to use before changing it.
# USING OVERMIND
diff --git a/frontend/src/analytics.ts b/frontend/src/analytics.ts
index 608b5658..0f4d739e 100644
--- a/frontend/src/analytics.ts
+++ b/frontend/src/analytics.ts
@@ -1,36 +1,45 @@
-import posthog from "posthog-js";
-
const selfHosted = import.meta.env.VITE_SELF_HOSTED === "true";
+const enabled = !selfHosted && import.meta.env.MODE !== "development";
-if (!selfHosted && import.meta.env.MODE !== "development") {
- posthog.init("phc_XrIVhixaz5sOqrdzpRwwqlvKXilmcy3PWPgdk0pemZa", {
- api_host: "https://v.overmindlab.ai",
- defaults: "2026-01-30",
- person_profiles: "identified_only",
- });
-}
+const client = enabled
+ ? import("posthog-js")
+ .then(({ default: posthog }) => {
+ posthog.init(
+ import.meta.env.VITE_PUBLIC_POSTHOG_KEY ||
+ "phc_XrIVhixaz5sOqrdzpRwwqlvKXilmcy3PWPgdk0pemZa",
+ {
+ api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST || "https://v.overmindlab.ai",
+ defaults: "2026-01-30",
+ person_profiles: "identified_only",
+ }
+ );
+ return posthog;
+ })
+ // Analytics delivery must not block rendering or recursively report its own load failure.
+ .catch(() => undefined)
+ : undefined;
-if (!selfHosted && import.meta.env.MODE !== "development" && typeof window !== "undefined") {
+if (enabled && typeof window !== "undefined") {
window.addEventListener("error", (event) => {
- posthog.captureException(event.error ?? new Error(String(event.message)));
+ void client?.then((posthog) =>
+ posthog?.captureException(event.error ?? new Error(String(event.message)))
+ );
});
window.addEventListener("unhandledrejection", (event) => {
const reason = event.reason instanceof Error ? event.reason : new Error(String(event.reason));
- posthog.captureException(reason);
+ void client?.then((posthog) => posthog?.captureException(reason));
});
}
export const trackEvent = (event: string, properties?: Record<string, any>) => {
- if (!selfHosted && import.meta.env.MODE !== "development") {
- posthog.capture(event, properties);
- }
+ void client?.then((posthog) => posthog?.capture(event, properties));
};
export const identifyUser = ({
userId,
clerkUserId,
}: Partial<{ userId: string; clerkUserId: string }>) => {
- if (!selfHosted && import.meta.env.MODE !== "development" && userId && clerkUserId) {
- posthog.identify(userId, { clerkUserId: clerkUserId });
+ if (userId && clerkUserId) {
+ void client?.then((posthog) => posthog?.identify(userId, { clerkUserId: clerkUserId }));
}
};
diff --git a/frontend/src/components/billing/account-band.tsx b/frontend/src/components/billing/account-band.tsx
index 57c9a1b7..7eb513ef 100644
--- a/frontend/src/components/billing/account-band.tsx
+++ b/frontend/src/components/billing/account-band.tsx
@@ -35,7 +35,7 @@ function errorMessage(err: unknown, fallback: string): string {
}
function planBadge(sub: Subscription) {
- if (sub.plan === PlanEnum.pro && sub.cancelAtPeriodEnd) {
+ if (sub.plan === PlanEnum.pro && sub.canManageRenewal && sub.cancelAtPeriodEnd) {
return <Badge variant="warning">Cancels soon</Badge>;
}
if (sub.plan === PlanEnum.pro) {
@@ -93,6 +93,10 @@ function PlanActions({ sub }: { sub: Subscription }) {
}
}
+ if (sub.plan === PlanEnum.pro && !sub.canManageRenewal) {
+ return <SharedActions />;
+ }
+
if (sub.plan === PlanEnum.pro && sub.cancelAtPeriodEnd) {
return (
<>
@@ -284,7 +288,7 @@ export function AccountBand({
{planBadge(sub)}
{end ? (
<span className="text-muted-foreground">
- {sub.cancelAtPeriodEnd ? `until ${end}` : `renews ${end}`}
+ {sub.canManageRenewal && !sub.cancelAtPeriodEnd ? `renews ${end}` : `until ${end}`}
</span>
) : null}
</span>
@@ -304,7 +308,7 @@ export function AccountBand({
</div>
</div>
- {sub.plan === PlanEnum.pro && sub.cancelAtPeriodEnd ? (
+ {sub.plan === PlanEnum.pro && sub.canManageRenewal && sub.cancelAtPeriodEnd ? (
<p className="border-t border-border/70 px-4 py-2 text-sm text-warning">
Cancellation scheduled{end ? ` — access ends ${end}` : ""}. Renew to keep Pro.
</p>
diff --git a/frontend/src/components/create-api-key-dialog.tsx b/frontend/src/components/create-api-key-dialog.tsx
index 4ab4a653..e6a441ff 100644
--- a/frontend/src/components/create-api-key-dialog.tsx
+++ b/frontend/src/components/create-api-key-dialog.tsx
@@ -121,7 +121,7 @@ export function CreateApiKeyDialog({
</DialogHeader>
<DialogBody>
{newToken ? (
- <div className="space-y-4">
+ <div className="ph-no-capture space-y-4">
<div className="space-y-2">
<p className="text-sm font-medium">Your new API key:</p>
<div className="overflow-x-auto rounded-md border border-dashed border-warning/50 bg-warning/10 p-3 font-mono text-sm">
diff --git a/frontend/src/components/datasets/notebook/rows-grid.tsx b/frontend/src/components/datasets/notebook/rows-grid.tsx
index 6c3ac61d..0e8f0a6c 100644
--- a/frontend/src/components/datasets/notebook/rows-grid.tsx
+++ b/frontend/src/components/datasets/notebook/rows-grid.tsx
@@ -675,6 +675,7 @@ export function RowsGrid({
<div className="border-t border-border/60">
<TablePagination
count={data.total}
+ loading={rowsQuery.isPlaceholderData}
onPageChange={setPage}
onPageSizeChange={(s) => {
setLimit(s);
diff --git a/frontend/src/components/evaluations/create-run-dialog.tsx b/frontend/src/components/evaluations/create-run-dialog.tsx
index 8c776445..078a5c9b 100644
--- a/frontend/src/components/evaluations/create-run-dialog.tsx
+++ b/frontend/src/components/evaluations/create-run-dialog.tsx
@@ -1,7 +1,7 @@
import { type ReactNode, useState } from "react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useNavigate } from "@tanstack/react-router";
+import { Link, useNavigate } from "@tanstack/react-router";
import api from "@/client";
import { JudgeModelSelect } from "@/components/evaluations/judge-model-select";
@@ -223,6 +223,25 @@ function CreateRunForm({
<Field label="Eval dataset">
<SearchableSelect
ariaLabel="Eval dataset"
+ emptyMessage={
+ datasets.error ? (
+ "Couldn't load evaluation datasets."
+ ) : (
+ <>
+ No evaluation datasets in this project.{" "}
+ <Link
+ className="text-foreground underline underline-offset-2"
+ search={{ projectId }}
+ to="/datasets"
+ >
+ Open datasets
+ </Link>
+ </>
+ )
+ }
+ isLoading={
+ datasets.isPending || (datasets.isFetching && !datasets.data?.results.length)
+ }
onChange={(value) => {
setDatasetId(value);
setEvalSetId("");
@@ -236,10 +255,12 @@ function CreateRunForm({
triggerClassName="w-full"
value={datasetId}
/>
+ <p className="text-xs text-muted-foreground">Only evaluation datasets are listed.</p>
</Field>
<Field label="Model being tested">
<SearchableSelect
ariaLabel="Model being tested"
+ isLoading={catalog.isPending}
onChange={setModel}
options={(catalog.data?.models ?? [])
.filter((row) => !row.id.includes(":batch"))
@@ -258,6 +279,7 @@ function CreateRunForm({
<Field label="Eval set">
<SearchableSelect
ariaLabel="Eval set"
+ isLoading={sets.isPending}
onChange={(value) => {
setEvalSetId(value);
setJudgeModel("");
diff --git a/frontend/src/components/evaluations/searchable-select.tsx b/frontend/src/components/evaluations/searchable-select.tsx
index e21891af..a7629487 100644
--- a/frontend/src/components/evaluations/searchable-select.tsx
+++ b/frontend/src/components/evaluations/searchable-select.tsx
@@ -19,6 +19,8 @@ export function SearchableSelect({
ariaLabel,
triggerClassName,
renderOption,
+ isLoading = false,
+ emptyMessage = "No options available.",
}: {
options: Option[];
value: string;
@@ -28,6 +30,8 @@ export function SearchableSelect({
ariaLabel: string;
triggerClassName?: string;
renderOption?: (option: Option) => ReactNode;
+ isLoading?: boolean;
+ emptyMessage?: ReactNode;
}) {
const [open, setOpen] = useState(false);
const [search, setSearch] = useState("");
@@ -91,8 +95,14 @@ export function SearchableSelect({
</div>
</div>
<SelectableCardGroup className="max-h-[280px] overflow-y-auto p-1">
- {filtered.length === 0 ? (
- <p className="px-2 py-3 text-xs text-muted-foreground">No matches for "{search}".</p>
+ {isLoading ? (
+ <p className="px-2 py-3 text-xs text-muted-foreground" role="status">
+ Loading options
+ </p>
+ ) : filtered.length === 0 ? (
+ <p className="px-2 py-3 text-xs text-muted-foreground">
+ {search.trim() ? `No matches for "${search.trim()}".` : emptyMessage}
+ </p>
) : (
filtered.map((o) => {
const isSelected = o.value === value;
diff --git a/frontend/src/components/local-login-form.tsx b/frontend/src/components/local-login-form.tsx
index 97a255c3..09a1c34b 100644
--- a/frontend/src/components/local-login-form.tsx
+++ b/frontend/src/components/local-login-form.tsx
@@ -39,7 +39,7 @@ export function LocalLoginForm({ onSignedIn }: { onSignedIn: () => void }) {
return (
<form
- className="animate-fade-in-up flex w-full max-w-sm flex-col gap-4 rounded-md border border-auth-border bg-auth-panel/90 p-6 [animation-delay:400ms]"
+ className="flex w-full max-w-sm flex-col gap-4 rounded-md border border-auth-border bg-auth-panel/90 p-6"
onSubmit={(e) => void onSubmit(e)}
>
<div className="flex flex-col gap-1">
diff --git a/frontend/src/components/project-required-empty-state.tsx b/frontend/src/components/project-required-empty-state.tsx
index d0a8e29c..d5fece28 100644
--- a/frontend/src/components/project-required-empty-state.tsx
+++ b/frontend/src/components/project-required-empty-state.tsx
@@ -1,6 +1,5 @@
-import { Navigate } from "@tanstack/react-router";
-
import { QuickstartEmbed } from "@/components/quickstart/quickstart-embed";
+import { Alert } from "@/components/ui/alert";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
import { LoadingState } from "@/components/ui/spinner";
@@ -17,16 +16,16 @@ export function ProjectRequiredEmptyState({
title?: string;
description?: string;
}) {
- const { data, isLoading } = useProjectsList();
+ const { data, isLoading, error } = useProjectsList({ pollWhileEmpty: true });
const projects = data?.projects ?? [];
if (isLoading) {
return <LoadingState fullPage label="Loading projects" />;
}
- if (projects.length === 0) {
- return <Navigate replace search={{ projectId: undefined }} to="/" />;
- }
+ if (error && !data) return <Alert variant="destructive">Couldn’t load projects.</Alert>;
+
+ if (projects.length === 0) return <QuickstartEmbed />;
return <EmptyState description={description} icon={Icon.folderAdd} title={title} />;
}
diff --git a/frontend/src/components/quickstart/onboard-with-ai-panel.tsx b/frontend/src/components/quickstart/onboard-with-ai-panel.tsx
index 161e1682..7246c87c 100644
--- a/frontend/src/components/quickstart/onboard-with-ai-panel.tsx
+++ b/frontend/src/components/quickstart/onboard-with-ai-panel.tsx
@@ -1,5 +1,6 @@
import { useState } from "react";
+import { trackEvent } from "@/analytics";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
@@ -23,26 +24,31 @@ export function OnboardWithAiPanel({
projectId?: string;
waitingHint?: string;
}) {
- const [promptCopied, setPromptCopied] = useState(false);
+ const [copiedPrompt, setCopiedPrompt] = useState<string>();
const [copyError, setCopyError] = useState("");
const prompt = onboardingPrompt(
window.location.origin,
config.apiUrl,
- datasetId && projectId ? { datasetId, projectId } : undefined
+ projectId ? { datasetId, projectId } : undefined
);
const guide = `${window.location.origin}/setup.md`;
+ const promptCopied = copiedPrompt === prompt;
const copyPrompt = () =>
writeClipboardText(prompt).then(
() => {
setCopyError("");
- setPromptCopied(true);
+ setCopiedPrompt(prompt);
+ trackEvent("setup_prompt_copied", { dataset_id: datasetId, project_id: projectId });
onPromptCopied?.();
- setTimeout(() => setPromptCopied(false), 2000);
},
- () => setCopyError("Couldn't copy — select the prompt text and copy it manually.")
+ () => {
+ setCopiedPrompt(undefined);
+ setCopyError("Couldn't copy — select the prompt text and copy it manually.");
+ trackEvent("setup_prompt_copy_failed", { dataset_id: datasetId, project_id: projectId });
+ }
);
return (
@@ -80,8 +86,13 @@ export function OnboardWithAiPanel({
</p>
<Button className="w-full gap-2" onClick={() => void copyPrompt()} size="sm" type="button">
{promptCopied ? <Icon.success /> : <Icon.copy />}
- {promptCopied ? "Prompt copied" : "Copy onboarding prompt"}
+ <span>{promptCopied ? "Prompt copied" : "Copy onboarding prompt"}</span>
</Button>
+ {promptCopied ? (
+ <p aria-live="polite" className="text-xs text-muted-foreground">
+ Paste the prompt into your coding agent to start setup.
+ </p>
+ ) : null}
{copyError ? <Alert variant="destructive">{copyError}</Alert> : null}
{waitingHint ? <p className="text-xs text-muted-foreground">{waitingHint}</p> : null}
</div>
diff --git a/frontend/src/components/quickstart/quickstart-embed.tsx b/frontend/src/components/quickstart/quickstart-embed.tsx
index 57e30a8a..b205e55d 100644
--- a/frontend/src/components/quickstart/quickstart-embed.tsx
+++ b/frontend/src/components/quickstart/quickstart-embed.tsx
@@ -6,6 +6,7 @@ import { DataProjectForm } from "@/components/onboarding/data-project-form";
import { OnboardingWindow } from "@/components/onboarding/onboarding-window";
import { OnboardWithAiPanel } from "@/components/quickstart/onboard-with-ai-panel";
import { OnboardingMilestones } from "@/components/quickstart/onboarding-milestones";
+import { LoadingState } from "@/components/ui/spinner";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { useOnboardingMilestones } from "@/hooks/use-activity";
@@ -22,7 +23,7 @@ export function QuickstartEmbed({
const connected = milestones.data?.some(
(step) => step.kind === "agent_connected" && step.completedAt
);
- if (projectId && milestones.isLoading) return null;
+ if (projectId && milestones.isLoading) return <LoadingState label="Loading setup progress" />;
if (source === "agent" && connected) {
return (
<section aria-label="Agent onboarding" className="w-full max-w-md">
@@ -53,7 +54,7 @@ export function QuickstartEmbed({
</Tabs>
</div>
{source === "agent" ? (
- <OnboardWithAiPanel compact />
+ <OnboardWithAiPanel compact key={projectId ?? "new"} projectId={projectId} />
) : (
<DataProjectForm
onCreated={({ projectId: createdProjectId, datasetId }) =>
diff --git a/frontend/src/components/route-error.tsx b/frontend/src/components/route-error.tsx
index 95d9cf9f..42673ec9 100644
--- a/frontend/src/components/route-error.tsx
+++ b/frontend/src/components/route-error.tsx
@@ -8,10 +8,22 @@ import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
+import { LoadingState } from "@/components/ui/spinner";
import { ApiError } from "@/lib/api-error";
import { hasChunkReloadFlag, isChunkLoadError, tryReloadOnceOnChunkError } from "@/lib/chunk-error";
import { errorMessage } from "@/lib/notify";
+export function AuthenticationLoadingState() {
+ return (
+ <div className="flex flex-col items-center justify-center gap-4">
+ <LoadingState label="Loading sign in" />
+ <Button onClick={() => window.location.reload()} variant="outline">
+ Reload sign in
+ </Button>
+ </div>
+ );
+}
+
export function DetailErrorState({
action,
error,
@@ -46,16 +58,13 @@ export function RouteErrorFallback({ error, reset }: { error: unknown; reset?: (
const router = useRouter();
const chunkError = isChunkLoadError(error);
const awaitingChunkReload = chunkError && !hasChunkReloadFlag();
- const [reloading, setReloading] = useState(awaitingChunkReload);
+ const [retrying, setRetrying] = useState(false);
useEffect(() => {
if (!awaitingChunkReload) return;
tryReloadOnceOnChunkError(error);
- setReloading(true);
}, [awaitingChunkReload, error]);
- if (reloading || awaitingChunkReload) return null;
-
const notFound = error instanceof ApiError && error.status === 404;
// A `validateSearch` failure carries the raw issue array as its `.message`,
// and retrying the same URL throws again — hence its own title and no retry.
@@ -71,7 +80,7 @@ export function RouteErrorFallback({ error, reset }: { error: unknown; reset?: (
<>
<Button onClick={() => window.location.reload()}>Refresh page</Button>
<Button asChild variant="outline">
- <Link to="/">Go to home</Link>
+ <a href="/">Go to home</a>
</Button>
</>
}
@@ -92,17 +101,23 @@ export function RouteErrorFallback({ error, reset }: { error: unknown; reset?: (
<>
{!invalidLink && (
<Button
- onClick={() => {
- reset?.();
- router.invalidate();
+ disabled={retrying}
+ onClick={async () => {
+ setRetrying(true);
+ try {
+ await router.invalidate();
+ reset?.();
+ } finally {
+ setRetrying(false);
+ }
}}
variant="outline"
>
- Try again
+ {retrying ? "Retrying" : "Try again"}
</Button>
)}
<Button asChild>
- <Link to="/">Go to home</Link>
+ <a href="/">Go to home</a>
</Button>
</>
}
@@ -143,3 +158,16 @@ export function RouteNotFound() {
</div>
);
}
+
+export function AuthenticationLoadError() {
+ return (
+ <div className="flex min-h-screen items-center justify-center p-6">
+ <EmptyState
+ action={<Button onClick={() => window.location.reload()}>Reload sign in</Button>}
+ description="The sign-in service could not load. Check your connection and reload."
+ icon={Icon.warning}
+ title="Sign in unavailable"
+ />
+ </div>
+ );
+}
diff --git a/frontend/src/components/ui/credits.tsx b/frontend/src/components/ui/credits.tsx
index c42dc52e..f3ef0fe4 100644
--- a/frontend/src/components/ui/credits.tsx
+++ b/frontend/src/components/ui/credits.tsx
@@ -1,5 +1,5 @@
import { Icon } from "@/components/ui/icons";
-import { cn, usdToOvermindCredits, usdToOvermindCreditsWithLabel } from "@/lib/utils";
+import { cn, formatOvermindCredits, usdToOvermindCreditsWithLabel } from "@/lib/utils";
/** The glyph replaces the word "credits" visually; screen readers still get the full
* phrase. */
@@ -11,7 +11,7 @@ export function CreditsAmount({ usd, className }: { usd: number; className?: str
title={usdToOvermindCreditsWithLabel(usd)}
>
<Icon.credits aria-hidden className="size-3.5 shrink-0" />
- {usdToOvermindCredits(usd).toLocaleString("en-US")}
+ {formatOvermindCredits(usd)}
</span>
);
}
diff --git a/frontend/src/components/ui/data-table.tsx b/frontend/src/components/ui/data-table.tsx
index 3ff5db48..20fb169b 100644
--- a/frontend/src/components/ui/data-table.tsx
+++ b/frontend/src/components/ui/data-table.tsx
@@ -621,6 +621,7 @@ export function DataTable<T>({
<div className="shrink-0 border-border/70 border-t">
<TablePagination
count={count}
+ loading={unsettled || isLoading}
onPageChange={onPageChange}
onPageSizeChange={onPageSizeChange}
page={page}
diff --git a/frontend/src/components/ui/table-pagination.tsx b/frontend/src/components/ui/table-pagination.tsx
index 6111eff5..5052bd1e 100644
--- a/frontend/src/components/ui/table-pagination.tsx
+++ b/frontend/src/components/ui/table-pagination.tsx
@@ -7,6 +7,7 @@ import {
SelectTrigger,
SelectValue,
} from "@/components/ui/select";
+import { Spinner } from "@/components/ui/spinner";
import { cn, paginationFromPageLimit } from "@/lib/utils";
interface TablePaginationProps {
@@ -16,6 +17,7 @@ interface TablePaginationProps {
page: number;
pageSize: number;
count: number;
+ loading?: boolean;
onPageChange: (page: number) => void;
onPageSizeChange: (size: number) => void;
}
@@ -24,6 +26,7 @@ export function TablePagination({
className,
size = "default",
count,
+ loading = false,
page,
pageSize,
onPageChange,
@@ -41,8 +44,16 @@ export function TablePagination({
className
)}
>
- <div className="flex-1 whitespace-nowrap tabular-nums">
- {pagination.count > 0 ? (
+ <div
+ aria-live="polite"
+ className="flex flex-1 items-center gap-2 whitespace-nowrap tabular-nums"
+ >
+ {loading ? (
+ <>
+ <Spinner size="sm" />
+ Loading page {page}
+ </>
+ ) : pagination.count > 0 ? (
<>
{pagination.startItem}–{pagination.endItem} of {pagination.total}{" "}
{pagination.total === 1 ? "row" : "rows"}
@@ -73,7 +84,7 @@ export function TablePagination({
</div>
<div className="flex items-center gap-1">
<Button
- disabled={!pagination.hasPrevious}
+ disabled={loading || !pagination.hasPrevious}
onClick={() => onPageChange(page - 1)}
size={size === "xs" ? "icon-xs" : "icon-sm"}
variant="secondary"
@@ -82,7 +93,7 @@ export function TablePagination({
<Icon.chevronLeft />
</Button>
<Button
- disabled={!pagination.hasNext}
+ disabled={loading || !pagination.hasNext}
onClick={() => onPageChange(page + 1)}
size={size === "xs" ? "icon-xs" : "icon-sm"}
variant="secondary"
diff --git a/frontend/src/hooks/use-inference.ts b/frontend/src/hooks/use-inference.ts
index cc09fc3d..49952b85 100644
--- a/frontend/src/hooks/use-inference.ts
+++ b/frontend/src/hooks/use-inference.ts
@@ -36,6 +36,7 @@ export const useDeployedModelsQuery = ({
status,
}: DeployedModelsQueryParams = {}) =>
useQuery({
+ enabled: !!projectId,
queryFn: () =>
apiClient.deployedModels.deployedModelsList({
capability: capability || undefined,
diff --git a/frontend/src/hooks/use-project-search-sync.ts b/frontend/src/hooks/use-project-search-sync.ts
index fa86cc65..3b311881 100644
--- a/frontend/src/hooks/use-project-search-sync.ts
+++ b/frontend/src/hooks/use-project-search-sync.ts
@@ -64,7 +64,11 @@ export function useProjectSearchSync() {
if (projects.length === 0) {
clearStoredProjectId();
if (projectId) {
- navigate({ replace: true, search: {}, to: "/" });
+ navigate({
+ replace: true,
+ search: (prev) => ({ ...prev, projectId: undefined }),
+ to: ".",
+ });
}
return;
}
@@ -79,19 +83,28 @@ export function useProjectSearchSync() {
if (projectId && !isValid(projectId)) {
if (isFetching) return;
clearStoredProjectId();
- navigate({ replace: true, search: {}, to: "/" });
+ navigate({
+ replace: true,
+ search: (prev) => ({ ...prev, projectId: undefined }),
+ to: ".",
+ });
return;
}
const storedId = getStoredProjectId();
- if (storedId && isValid(storedId)) {
+ const selectedId = isValid(storedId)
+ ? storedId
+ : projects.length === 1
+ ? projects[0].projectId
+ : undefined;
+ if (selectedId) {
// Pathname can flip to /datasets before this hook sees the new projectId.
// The navigation already in flight carries that id; keep it.
navigate({
replace: true,
search: (prev) => {
if ("projectId" in prev && prev.projectId) return prev;
- return { ...prev, projectId: storedId };
+ return { ...prev, projectId: selectedId };
},
to: ".",
});
@@ -101,8 +114,5 @@ export function useProjectSearchSync() {
if (storedId) {
clearStoredProjectId();
}
- if (projectId || pathname !== "/") {
- navigate({ replace: true, search: {}, to: "/" });
- }
}, [projectId, pathname, navigate, data, isFetching]);
}
diff --git a/frontend/src/integrations/posthog-provider.tsx b/frontend/src/integrations/posthog-provider.tsx
deleted file mode 100644
index 74a9ef55..00000000
--- a/frontend/src/integrations/posthog-provider.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import type { ReactNode } from "react";
-
-import { PostHogProvider as BasePostHogProvider } from "@posthog/react";
-import posthog from "posthog-js";
-
-const selfHosted = import.meta.env.VITE_SELF_HOSTED === "true";
-
-if (
- !selfHosted &&
- typeof window !== "undefined" &&
- window.location.hostname !== "localhost" &&
- import.meta.env.VITE_PUBLIC_POSTHOG_KEY
-) {
- posthog.init(import.meta.env.VITE_PUBLIC_POSTHOG_KEY, {
- api_host: import.meta.env.VITE_PUBLIC_POSTHOG_HOST || "https://us.i.posthog.com",
- capture_pageview: false,
- defaults: "2025-11-30",
- person_profiles: "identified_only",
- });
-}
-
-interface PostHogProviderProps {
- children: ReactNode;
-}
-
-export default function PostHogProvider({ children }: PostHogProviderProps) {
- if (selfHosted || window.location.hostname === "localhost") {
- return children;
- }
- return <BasePostHogProvider client={posthog}>{children}</BasePostHogProvider>;
-}
diff --git a/frontend/src/lib/chunk-error.test.ts b/frontend/src/lib/chunk-error.test.ts
index 25e3e28f..71c21c1f 100644
--- a/frontend/src/lib/chunk-error.test.ts
+++ b/frontend/src/lib/chunk-error.test.ts
@@ -17,6 +17,7 @@ describe("isChunkLoadError", () => {
"Importing a module script failed.",
"error loading dynamically imported module",
"ChunkLoadError: Loading chunk 42 failed.",
+ "Loading chunk 9573 failed. (error: https://example.com/ui-common.js)",
'Failed to load module script: Expected a JavaScript-or-Wasm module script but the server responded with a MIME type of "text/html".',
])("detects %s", (message) => {
expect(isChunkLoadError(new TypeError(message))).toBe(true);
diff --git a/frontend/src/lib/chunk-error.ts b/frontend/src/lib/chunk-error.ts
index 76b92eac..6b2025f8 100644
--- a/frontend/src/lib/chunk-error.ts
+++ b/frontend/src/lib/chunk-error.ts
@@ -5,6 +5,7 @@ const CHUNK_LOAD_PATTERNS = [
/importing a module script failed/i,
/error loading dynamically imported module/i,
/chunkloaderror/i,
+ /loading chunk \S+ failed/i,
// SPA fallback serves index.html for missing hashed chunks.
/expected a javascript.*text\/html/i,
];
diff --git a/frontend/src/lib/mcp-setup.ts b/frontend/src/lib/mcp-setup.ts
index 98060170..8d98e634 100644
--- a/frontend/src/lib/mcp-setup.ts
+++ b/frontend/src/lib/mcp-setup.ts
@@ -81,13 +81,15 @@ export function mcpInitCommand(
export function onboardingPrompt(
origin: string,
apiUrl: string,
- data?: { projectId: string; datasetId: string }
+ data?: { projectId: string; datasetId?: string }
): string {
const guide = `${origin.replace(/\/$/, "")}/setup.md`;
const url = apiUrl.replace(/\/$/, "");
- const subject = data
+ const subject = data?.datasetId
? `Set me up on Overmind with my uploaded data\n(project_id: ${data.projectId},\ndataset_id: ${data.datasetId})`
- : "Set me up on Overmind";
+ : data
+ ? `Set me up on Overmind\n(project_id: ${data.projectId})`
+ : "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}`;
}
diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts
index 6369cb56..897d742e 100644
--- a/frontend/src/lib/utils.test.ts
+++ b/frontend/src/lib/utils.test.ts
@@ -1,6 +1,11 @@
import { describe, expect, it } from "vitest";
-import { paginationItems, usdToOvermindCredits, usdToOvermindCreditsWithLabel } from "./utils";
+import {
+ formatOvermindCredits,
+ paginationItems,
+ usdToOvermindCredits,
+ usdToOvermindCreditsWithLabel,
+} from "./utils";
describe("usdToOvermindCredits", () => {
it("converts at 100 credits per USD", () => {
@@ -9,6 +14,13 @@ describe("usdToOvermindCredits", () => {
expect(usdToOvermindCredits(0.126)).toBe(13);
expect(usdToOvermindCreditsWithLabel(2.5)).toBe("250 credits");
});
+
+ it("keeps fractions only below one credit", () => {
+ expect(formatOvermindCredits(0.0000312)).toBe("0.00312");
+ expect(formatOvermindCredits(-0.0000312)).toBe("-0.00312");
+ expect(formatOvermindCredits(12.3456)).toBe("1,235");
+ expect(usdToOvermindCreditsWithLabel(0.0000312)).toBe("0.00312 credits");
+ });
});
describe("paginationItems", () => {
diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts
index 03d8fad0..52bfbc91 100644
--- a/frontend/src/lib/utils.ts
+++ b/frontend/src/lib/utils.ts
@@ -69,8 +69,15 @@ export function usdToOvermindCredits(usd: number): number {
return Math.round(usd / 0.01);
}
+export function formatOvermindCredits(usd: number): string {
+ const credits = usd / 0.01;
+ return Math.abs(credits) < 1
+ ? credits.toLocaleString("en-US", { maximumFractionDigits: 5 })
+ : usdToOvermindCredits(usd).toLocaleString("en-US");
+}
+
export function usdToOvermindCreditsWithLabel(usd: number): string {
- return `${usdToOvermindCredits(usd)} credits`;
+ return `${formatOvermindCredits(usd)} credits`;
}
export const plural = (count: number, noun: string): string =>
diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx
index 7f1e1b2e..9bbb6bf8 100644
--- a/frontend/src/main.tsx
+++ b/frontend/src/main.tsx
@@ -1,11 +1,16 @@
import { StrictMode } from "react";
import ReactDOM from "react-dom/client";
-import { ClerkProvider } from "@clerk/clerk-react";
+import { ClerkFailed, ClerkLoaded, ClerkLoading, ClerkProvider } from "@clerk/clerk-react";
import { createRouter as createTanStackRouter } from "@tanstack/react-router";
import { AuthRouter } from "./components/auth-router";
-import { RouteErrorFallback, RouteNotFound } from "./components/route-error";
+import {
+ AuthenticationLoadError,
+ AuthenticationLoadingState,
+ RouteErrorFallback,
+ RouteNotFound,
+} from "./components/route-error";
import { Toaster } from "./components/ui/sonner";
import "./styles.css";
@@ -13,7 +18,6 @@ import "./analytics";
import { config } from "./config";
import { AuthProvider } from "./contexts/auth-context";
-import PostHogProvider from "./integrations/posthog-provider";
import { getContext } from "./integrations/tanstack-query";
import { installAutohideScrollbars } from "./lib/autohide-scrollbars";
import { routeTree } from "./routeTree.gen";
@@ -44,10 +48,24 @@ const router = getRouter();
function App() {
return (
<AuthProvider>
- <PostHogProvider>
+ {config.clerkReady ? (
+ <>
+ <ClerkLoading>
+ <div className="flex min-h-screen flex-col items-center justify-center gap-4">
+ <AuthenticationLoadingState />
+ </div>
+ </ClerkLoading>
+ <ClerkFailed>
+ <AuthenticationLoadError />
+ </ClerkFailed>
+ <ClerkLoaded>
+ <AuthRouter router={router} />
+ </ClerkLoaded>
+ </>
+ ) : (
<AuthRouter router={router} />
- <Toaster position="bottom-right" />
- </PostHogProvider>
+ )}
+ <Toaster position="bottom-right" />
</AuthProvider>
);
}
diff --git a/frontend/src/openapi/models/Subscription.ts b/frontend/src/openapi/models/Subscription.ts
index b846edf8..40982b4d 100644
--- a/frontend/src/openapi/models/Subscription.ts
+++ b/frontend/src/openapi/models/Subscription.ts
@@ -88,6 +88,12 @@ export interface Subscription {
* @memberof Subscription
*/
cancelAtPeriodEnd: boolean;
+ /**
+ *
+ * @type {boolean}
+ * @memberof Subscription
+ */
+ canManageRenewal: boolean;
/**
*
* @type {PlanUsage}
@@ -111,6 +117,7 @@ export function instanceOfSubscription(value: object): value is Subscription {
if (!('startDate' in value) || value['startDate'] === undefined) return false;
if (!('endDate' in value) || value['endDate'] === undefined) return false;
if (!('cancelAtPeriodEnd' in value) || value['cancelAtPeriodEnd'] === undefined) return false;
+ if (!('canManageRenewal' in value) || value['canManageRenewal'] === undefined) return false;
if (!('usage' in value) || value['usage'] === undefined) return false;
return true;
}
@@ -134,6 +141,7 @@ export function SubscriptionFromJSONTyped(json: any, ignoreDiscriminator: boolea
'startDate': (json['start_date'] == null ? null : new Date(json['start_date'])),
'endDate': (json['end_date'] == null ? null : new Date(json['end_date'])),
'cancelAtPeriodEnd': json['cancel_at_period_end'],
+ 'canManageRenewal': json['can_manage_renewal'],
'usage': PlanUsageFromJSON(json['usage']),
};
}
@@ -158,6 +166,7 @@ export function SubscriptionToJSONTyped(value?: Subscription | null, ignoreDiscr
'start_date': value['startDate'] == null ? value['startDate'] : value['startDate'].toISOString(),
'end_date': value['endDate'] == null ? value['endDate'] : value['endDate'].toISOString(),
'cancel_at_period_end': value['cancelAtPeriodEnd'],
+ 'can_manage_renewal': value['canManageRenewal'],
'usage': PlanUsageToJSON(value['usage']),
};
}
diff --git a/frontend/src/routes/_auth/index.tsx b/frontend/src/routes/_auth/index.tsx
index 9470ecd7..8ca17dd6 100644
--- a/frontend/src/routes/_auth/index.tsx
+++ b/frontend/src/routes/_auth/index.tsx
@@ -22,7 +22,6 @@ import { PageShell } from "@/components/ui/page-shell";
import { LoadingState } from "@/components/ui/spinner";
import { useAuthContext } from "@/contexts/auth-context";
import { useOnboardingMilestones } from "@/hooks/use-activity";
-import { setStoredProjectId } from "@/hooks/use-project-search-sync";
import { useProjectsList } from "@/hooks/use-projects";
import { getGuestProjectId } from "@/lib/guest";
import { errorMessage } from "@/lib/notify";
@@ -171,15 +170,6 @@ function AgentPage() {
const { createProject } = search;
- useEffect(() => {
- if (projects.length !== 1 || search.projectId) return;
- const id = projects[0].id;
- setStoredProjectId(id);
- void navigate({
- replace: true,
- search: (prev) => ({ ...prev, projectId: id }),
- });
- }, [navigate, projects, search.projectId]);
useEffect(() => {
if (!isGuest || search.projectId) return;
const guestProjectId = getGuestProjectId();
diff --git a/frontend/src/routes/_auth/inference.tsx b/frontend/src/routes/_auth/inference.tsx
index fdefc7cc..e5003a41 100644
--- a/frontend/src/routes/_auth/inference.tsx
+++ b/frontend/src/routes/_auth/inference.tsx
@@ -19,7 +19,6 @@ import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
import { PageHeader } from "@/components/ui/page-header";
import { PageShell } from "@/components/ui/page-shell";
-import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useDeployedModelsQuery, useModelLiveQuery } from "@/hooks/use-inference";
import { type InferenceSearch, inferenceSearchSchema } from "@/lib/schemas";
import type { DeployedModel } from "@/openapi";
@@ -63,18 +62,18 @@ function InferencePage() {
const navigate = Route.useNavigate();
const [ordering, setOrdering] = useState<string | undefined>();
const [searchText, setSearchText] = useState(search);
- const debouncedSearch = useDebouncedValue(searchText, 400);
-
- // Publish settled draft → URL. No-op when equal so mount doesn't reset page.
useEffect(() => {
- const next = debouncedSearch.trim();
+ const next = searchText.trim();
if (next === search) return;
- void navigate({
- replace: true,
- resetScroll: false,
- search: (prev) => ({ ...prev, inf_search: next, page: 1 }),
- });
- }, [debouncedSearch, search, navigate]);
+ const timer = setTimeout(() => {
+ void navigate({
+ replace: true,
+ resetScroll: false,
+ search: (prev) => ({ ...prev, inf_search: next, page: 1 }),
+ });
+ }, 400);
+ return () => clearTimeout(timer);
+ }, [searchText, search, navigate]);
// Back/forward wins over stale keystrokes; trim-equal keeps in-flight typing.
useEffect(() => {
diff --git a/frontend/src/routes/login.tsx b/frontend/src/routes/login.tsx
index e4bf313c..98a2d8c5 100644
--- a/frontend/src/routes/login.tsx
+++ b/frontend/src/routes/login.tsx
@@ -3,8 +3,8 @@ import { createFileRoute, Link, Navigate } from "@tanstack/react-router";
import { z } from "zod";
import { LocalLoginForm } from "@/components/local-login-form";
+import { AuthenticationLoadingState } from "@/components/route-error";
import { SplashBackground } from "@/components/splash-background";
-import { LoadingState } from "@/components/ui/spinner";
import { config } from "@/config";
import { useAuthContext } from "@/contexts/auth-context";
import { useLoginGate } from "@/hooks/use-login-gate";
@@ -23,7 +23,6 @@ const CLERK_APPEARANCE = {
elements: {
card: "bg-transparent shadow-none",
cardBox: "rounded-md border border-auth-border bg-auth-panel/90 shadow-none",
- rootBox: "animate-fade-in-up [animation-delay:400ms]",
},
};
@@ -43,7 +42,7 @@ function RouteComponent() {
if (gate.kind === "loading") {
return (
<SplashBackground>
- <LoadingState className="max-w-sm" label="Loading sign in" />
+ <AuthenticationLoadingState />
</SplashBackground>
);
}
@@ -74,6 +73,7 @@ function RouteComponent() {
{mode === "signup" ? (
<SignUp
appearance={CLERK_APPEARANCE}
+ fallback={<AuthenticationLoadingState />}
forceRedirectUrl={forceRedirectUrl}
oauthFlow="popup"
routing="hash"
@@ -82,6 +82,7 @@ function RouteComponent() {
) : (
<SignIn
appearance={CLERK_APPEARANCE}
+ fallback={<AuthenticationLoadingState />}
forceRedirectUrl={forceRedirectUrl}
oauthFlow="popup"
routing="hash"
diff --git a/frontend/src/self-hosted-analytics.test.ts b/frontend/src/self-hosted-analytics.test.ts
index d76e5209..3aa913dd 100644
--- a/frontend/src/self-hosted-analytics.test.ts
+++ b/frontend/src/self-hosted-analytics.test.ts
@@ -19,6 +19,7 @@ describe("self-hosted PostHog strip", () => {
vi.unstubAllEnvs();
vi.resetModules();
posthogInit.mockClear();
+ posthogCapture.mockClear();
});
it("skips analytics.ts init when VITE_SELF_HOSTED is true", async () => {
@@ -28,11 +29,21 @@ describe("self-hosted PostHog strip", () => {
expect(posthogInit).not.toHaveBeenCalled();
});
- it("skips posthog-provider init when VITE_SELF_HOSTED is true", async () => {
- vi.stubEnv("VITE_SELF_HOSTED", "true");
+ it("initializes once and preserves events captured while the SDK loads", async () => {
+ vi.stubEnv("VITE_SELF_HOSTED", "false");
vi.stubEnv("VITE_PUBLIC_POSTHOG_KEY", "phc_test");
+ vi.stubEnv("VITE_PUBLIC_POSTHOG_HOST", "https://analytics.example");
vi.stubEnv("MODE", "production");
- await import("./integrations/posthog-provider");
- expect(posthogInit).not.toHaveBeenCalled();
+ const { trackEvent } = await import("./analytics");
+ trackEvent("setup_prompt_copied", { project_id: "project-1" });
+ await vi.dynamicImportSettled();
+ expect(posthogInit).toHaveBeenCalledOnce();
+ expect(posthogInit).toHaveBeenCalledWith(
+ "phc_test",
+ expect.objectContaining({
+ api_host: "https://analytics.example",
+ })
+ );
+ expect(posthogCapture).toHaveBeenCalledWith("setup_prompt_copied", { project_id: "project-1" });
});
});
diff --git a/overbae/api/billing.py b/overbae/api/billing.py
index 243c5309..357ebba1 100644
--- a/overbae/api/billing.py
+++ b/overbae/api/billing.py
@@ -317,6 +317,7 @@ def _subscription_payload(user: User) -> dict:
"start_date": None,
"end_date": None,
"cancel_at_period_end": False,
+ "can_manage_renewal": False,
"usage": usage,
}
@@ -330,6 +331,11 @@ def _subscription_payload(user: User) -> dict:
"start_date": sub.start_date,
"end_date": sub.end_date,
"cancel_at_period_end": sub.cancel_at_period_end,
+ "can_manage_renewal": (
+ billing.enabled
+ and sub.status == SubscriptionStatus.ACTIVE
+ and bool(sub.stripe_subscription_id)
+ ),
"usage": usage,
}
@@ -614,7 +620,7 @@ class CheckoutSessionView(APIView):
customer=customer_id,
line_items=[{"price": price_id, "quantity": 1}],
success_url=f"{frontend}/settings?billing=success",
- cancel_url=f"{frontend}/pricing?checkout=cancel",
+ cancel_url=f"{frontend}/settings?billing=cancel",
client_reference_id=str(user.pk),
metadata={"user_id": str(user.pk)},
subscription_data={"metadata": {"user_id": str(user.pk)}},
diff --git a/overbae/api/dataset_serializers.py b/overbae/api/dataset_serializers.py
index 1e006a54..c4229c44 100644
--- a/overbae/api/dataset_serializers.py
+++ b/overbae/api/dataset_serializers.py
@@ -299,10 +299,6 @@ class DatasetSerializer(serializers.ModelSerializer):
work = list_activity.current_work([obj])
return work.get(str(obj.pk))
- def _chain(self, obj) -> list[Cell]:
- cached = getattr(obj, "_prefetched_objects_cache", {}).get("cells")
- return sorted(cached, key=lambda c: c.position) if cached is not None else obj.chain
-
@extend_schema_field(serializers.DictField())
def get_operation(self, obj):
if self.context.get("summary"):
@@ -338,7 +334,7 @@ class DatasetSerializer(serializers.ModelSerializer):
def get_cells(self, obj) -> list[dict]:
if self.context.get("summary"):
return []
- chain = self._chain(obj)
+ chain = obj.prefetched_chain()
versions = obj.versions(chain=chain)
frozen = max((c.position for c in chain if c.used_at is not None), default=-1)
return CellSerializer(
@@ -355,7 +351,7 @@ class DatasetSerializer(serializers.ModelSerializer):
).data
def _active(self, obj) -> Cell | None:
- chain = self._chain(obj)
+ chain = obj.prefetched_chain()
ran = [c for c in chain if c.state == Cell.State.OK and c.fingerprint]
if obj.active_id is not None:
for cell in ran:
@@ -365,7 +361,7 @@ class DatasetSerializer(serializers.ModelSerializer):
def get_active_version(self, obj) -> str:
cell = self._active(obj)
- return obj.versions(chain=self._chain(obj)).get(cell.id, "") if cell else ""
+ return obj.versions(chain=obj.prefetched_chain()).get(cell.id, "") if cell else ""
def get_rows(self, obj) -> int:
cell = self._active(obj)
diff --git a/overbae/api/native_evaluation.py b/overbae/api/native_evaluation.py
index e2720ba9..8e4801f9 100644
--- a/overbae/api/native_evaluation.py
+++ b/overbae/api/native_evaluation.py
@@ -1,5 +1,6 @@
import logging
+from django.db.models import Prefetch
from django.http import FileResponse
from django.shortcuts import get_object_or_404
from drf_spectacular.utils import extend_schema
@@ -57,7 +58,7 @@ class NativeEvaluationSuiteSerializer(serializers.Serializer):
dataset = cell.dataset
return super().to_representation(
{
- **use.describe(cell),
+ **use.describe(cell, chain=dataset.prefetched_chain()),
"dataset_name": dataset.name,
"capability_id": dataset.capability_id,
"capability_name": dataset.capability.name if dataset.capability_id else "",
@@ -272,6 +273,15 @@ class NativeEvaluationViewSet(
)
.order_by("-created_at")
)
+ if self.action == "list":
+ # Actions freeze cells after loading the plan, so only the list reuses prefetched cells.
+ version_cells = Cell.objects.only("id", "dataset_id", "position", "used_at")
+ queryset = queryset.prefetch_related(
+ *(
+ Prefetch(f"{relation}__dataset__cells", queryset=version_cells)
+ for relation in ("final_cell", "calibration_cell")
+ )
+ )
return (
queryset if self.action in {"destroy", "report"} else queryset.filter(deleted_at=None)
)
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index e3ec5f5f..192c3ce7 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -1089,9 +1089,9 @@ class ModelSwapPromptSerializer(serializers.Serializer):
def _describe_cell(job: FinetuningJob) -> dict | None:
- from overbae.services.datasets import use # noqa: PLC0415 — avoid import cycle
-
- return use.describe(job.cell if job.cell_id else None)
+ if not job.cell_id:
+ return None
+ return dataset_use.describe(job.cell, chain=job.cell.dataset.prefetched_chain())
class FinetuningJobListSerializer(serializers.ModelSerializer):
@@ -2626,6 +2626,7 @@ class SubscriptionSerializer(serializers.Serializer):
start_date = serializers.DateTimeField(allow_null=True)
end_date = serializers.DateTimeField(allow_null=True)
cancel_at_period_end = serializers.BooleanField()
+ can_manage_renewal = serializers.BooleanField()
usage = PlanUsageSerializer()
diff --git a/overbae/api/views.py b/overbae/api/views.py
index 1eef7894..30faead7 100644
--- a/overbae/api/views.py
+++ b/overbae/api/views.py
@@ -2,7 +2,7 @@ import logging
from collections import defaultdict
from django.core.exceptions import ValidationError
-from django.db.models import Avg, Count, FloatField, Max, Min, OuterRef, Q, Subquery, Sum
+from django.db.models import Avg, Count, FloatField, Max, Min, OuterRef, Prefetch, Q, Subquery, Sum
from django.db.models.expressions import RawSQL
from django.db.models.fields.json import KeyTextTransform
from django.db.models.functions import Cast, Coalesce
@@ -721,22 +721,34 @@ class FinetuningJobViewSet(viewsets.ModelViewSet):
def get_queryset(self):
if getattr(self, "swagger_fake_view", False):
return FinetuningJob.objects.none()
- return FinetuningJob.objects.filter(
- project_id__in=_user_project_ids(self.request.user)
- ).select_related(
- "project",
- "capability",
- "dataset",
- "cell__dataset",
- "eval_cell__dataset",
- "eval_set",
- "native_evaluation",
- "native_evaluation__final_cell__dataset__capability",
- "native_evaluation__calibration_cell__dataset__capability",
- "validation_cell__dataset",
- "triggered_by",
- "deployed_model",
- "decision_job",
+ version_cells = Cell.objects.only("id", "dataset_id", "position", "used_at")
+ return (
+ FinetuningJob.objects.filter(project_id__in=_user_project_ids(self.request.user))
+ .select_related(
+ "project",
+ "capability",
+ "dataset",
+ "cell__dataset",
+ "eval_cell__dataset",
+ "eval_set",
+ "native_evaluation",
+ "native_evaluation__final_cell__dataset__capability",
+ "native_evaluation__calibration_cell__dataset__capability",
+ "validation_cell__dataset",
+ "triggered_by",
+ "deployed_model",
+ "decision_job",
+ )
+ .prefetch_related(
+ *(
+ Prefetch(f"{relation}__dataset__cells", queryset=version_cells)
+ for relation in (
+ "cell",
+ "native_evaluation__final_cell",
+ "native_evaluation__calibration_cell",
+ )
+ )
+ )
)
def perform_create(self, serializer):
diff --git a/overbae/models/datasets.py b/overbae/models/datasets.py
index 2cf935a3..2d9c18c3 100644
--- a/overbae/models/datasets.py
+++ b/overbae/models/datasets.py
@@ -90,6 +90,12 @@ class Dataset(models.Model):
"""Every cell in position order."""
return list(self.cells.order_by("position"))
+ def prefetched_chain(self) -> list["Cell"]:
+ """``chain`` from a ``prefetch_related("cells")`` cache when one exists.
+ The cache does not see writes made after the prefetch."""
+ cached = getattr(self, "_prefetched_objects_cache", {}).get("cells")
+ return sorted(cached, key=lambda cell: cell.position) if cached is not None else self.chain
+
@property
def source(self) -> "Cell | None":
return self.cells.filter(position=0).first()
diff --git a/overbae/services/datasets/use.py b/overbae/services/datasets/use.py
index 0828d019..e6d5c08e 100644
--- a/overbae/services/datasets/use.py
+++ b/overbae/services/datasets/use.py
@@ -78,12 +78,12 @@ def label(dataset: Dataset, cell: Cell) -> str:
return dataset.versions().get(cell.id, cell.title)
-def describe(cell: Cell | None) -> dict[str, Any] | None:
+def describe(cell: Cell | None, *, chain: list[Cell] | None = None) -> dict[str, Any] | None:
if cell is None:
return None
return {
"id": str(cell.id),
- "version": cell.dataset.versions().get(cell.id, ""),
+ "version": cell.dataset.versions(chain=chain).get(cell.id, ""),
"title": cell.title,
"rows": cell.rows,
"fingerprint": cell.fingerprint,
diff --git a/overbae/services/mcp/contracts/datasets.py b/overbae/services/mcp/contracts/datasets.py
index 36c7922e..9316da9f 100644
--- a/overbae/services/mcp/contracts/datasets.py
+++ b/overbae/services/mcp/contracts/datasets.py
@@ -526,13 +526,6 @@ class StartDatasetInput(MCPModel):
capability: str | None = Field(default=None, max_length=255)
-def _chain(dataset) -> list[Cell]:
- cached = getattr(dataset, "_prefetched_objects_cache", {}).get("cells")
- if cached is not None:
- return sorted(cached, key=lambda cell: cell.position)
- return dataset.chain
-
-
def _active_cell(dataset, chain: list[Cell]) -> Cell | None:
ran = [cell for cell in chain if cell.state == Cell.State.OK and cell.fingerprint]
if dataset.active_id is not None:
@@ -592,7 +585,7 @@ def _list_fields(dataset, chain: list[Cell]) -> dict[str, Any]:
def serialize_dataset_list_item(dataset) -> DatasetListItem:
- return DatasetListItem.model_validate(_list_fields(dataset, _chain(dataset)))
+ return DatasetListItem.model_validate(_list_fields(dataset, dataset.prefetched_chain()))
def _cell_summary(
@@ -800,7 +793,7 @@ def serialize_dataset_detail(
source_offset: int = 0,
source_limit: int = 10,
) -> DatasetDetail:
- chain = _chain(dataset)
+ chain = dataset.prefetched_chain()
versions = dataset.versions(chain=chain)
frozen_before = _frozen_before(chain)
active = _active_cell(dataset, chain)
diff --git a/tests/fakes/clerk.py b/tests/fakes/clerk.py
index a3efaeaf..dcb50dfd 100644
--- a/tests/fakes/clerk.py
+++ b/tests/fakes/clerk.py
@@ -20,6 +20,27 @@ _KID = "ins_fake"
_ids = itertools.count(1)
+PENDING_BROWSER_FORM_SCRIPT = """
+window.Clerk = {
+ loaded: true,
+ user: null,
+ session: null,
+ organization: null,
+ client: { signIn: {}, signUp: {} },
+ load: async () => {},
+ addListener(listener) {
+ listener({ client: this.client, user: null, session: null, organization: null });
+ return () => {};
+ },
+ mountSignIn() { fetch('https://clerk.example.invalid/pending-form'); },
+ mountSignUp() { fetch('https://clerk.example.invalid/pending-form'); },
+ unmountSignIn() {},
+ unmountSignUp() {},
+ __unstable__updateProps() {},
+};
+"""
+
+
def _json(body: Any, status: int = 200) -> tuple[int, dict, bytes]:
return status, {"content-type": "application/json"}, json.dumps(body).encode()
diff --git a/tests/journeys/console/conftest.py b/tests/journeys/console/conftest.py
index 04370bfc..13991a62 100644
--- a/tests/journeys/console/conftest.py
+++ b/tests/journeys/console/conftest.py
@@ -17,6 +17,31 @@ FRONTEND = Path(__file__).resolve().parents[3] / "frontend"
PASSWORD = "test-pass-123"
[email protected](scope="session")
+def replay_recorder(tmp_path_factory):
+ bundle = tmp_path_factory.mktemp("replay-recorder") / "recorder.js"
+ entry = bundle.with_suffix(".ts")
+ entry.write_text(
+ f"import {{ record }} from {json.dumps(str(FRONTEND / 'node_modules/posthog-js/dist/rrweb.js'))};"
+ "window.ReplayRecorder = { record };"
+ )
+ subprocess.run(
+ [
+ "bun",
+ "build",
+ str(entry),
+ "--format=iife",
+ "--outfile",
+ str(bundle),
+ ],
+ cwd=FRONTEND,
+ check=True,
+ capture_output=True,
+ timeout=60,
+ )
+ return bundle
+
+
class _SinglePageApp(SimpleHTTPRequestHandler):
def send_head(self):
if not Path(self.translate_path(self.path)).exists():
@@ -28,7 +53,7 @@ class _SinglePageApp(SimpleHTTPRequestHandler):
@pytest.fixture(scope="session")
-def console_url(live_api, tmp_path_factory):
+def console_url(live_api, tmp_path_factory, request):
dist = tmp_path_factory.mktemp("console")
env = {
**os.environ,
@@ -38,6 +63,9 @@ def console_url(live_api, tmp_path_factory):
"VITE_PUBLIC_POSTHOG_KEY": "",
"VITE_FEATURE_SIGNALS": "true",
}
+ if getattr(request, "param", None) == "clerk":
+ env["VITE_SELF_HOSTED"] = "false"
+ env["VITE_CLERK_PUBLISHABLE_KEY"] = "pk_test_Y2xlcmsuZXhhbXBsZS5pbnZhbGlkJA"
subprocess.run(
["bun", "run", "build", "--outDir", str(dist), "--emptyOutDir"],
cwd=FRONTEND,
diff --git a/tests/journeys/console/test_console.py b/tests/journeys/console/test_console.py
index 2b27865e..2f41c092 100644
--- a/tests/journeys/console/test_console.py
+++ b/tests/journeys/console/test_console.py
@@ -3,11 +3,13 @@ import json
import uuid
from datetime import timedelta
+import pytest
from django.utils import timezone
from modal_shared.training_monitoring import fingerprint
from overbae.models import (
Activity,
+ BillingTelemetry,
Cell,
DataPartitionMember,
DataPartitionPlan,
@@ -22,15 +24,415 @@ from overbae.models import (
FinetuningJob,
NativeEvaluationPlan,
OperationalRun,
+ Subscription,
)
from overbae.services import activity as activity_service
from overbae.services import training_monitoring
from overbae.tasks.datasets import reap_stuck_runs
+from tests.fakes.clerk import PENDING_BROWSER_FORM_SCRIPT
from ..datasets import tickets, upload
from ..stack import drain, settle
+def test_project_navigation_keeps_the_destination_without_a_project(console):
+ console.goto("/inference?inf_search=needle")
+ console.sees("Copy onboarding prompt")
+ console.wait_until(
+ "() => location.pathname === '/inference' && "
+ "new URLSearchParams(location.search).get('inf_search') === 'needle'"
+ )
+ console.save_evidence("project-navigation-without-project")
+
+
+def test_translated_onboarding_prompt_can_be_copied(console):
+ console.goto("/inference")
+ console.sees("Copy onboarding prompt")
+ console._browser.call(
+ lambda: console._page.context.grant_permissions(["clipboard-read", "clipboard-write"])
+ )
+ console._browser.call(
+ console._page.evaluate,
+ """() => {
+ const button = [...document.querySelectorAll('button')].find(
+ element => element.textContent.includes('Copy onboarding prompt'));
+ const texts = document.createTreeWalker(button, NodeFilter.SHOW_TEXT);
+ const nodes = [];
+ while (texts.nextNode()) nodes.push(texts.currentNode);
+ for (const text of nodes) {
+ if (!text.textContent.includes('Copy onboarding prompt')) continue;
+ const translated = document.createElement('font');
+ translated.textContent = 'Copiar instrucciones';
+ text.replaceWith(translated);
+ }
+ }""",
+ )
+ console.press("Copiar instrucciones")
+ console.sees("Paste the prompt into your coding agent to start setup.")
+ assert "/setup.md" in console._browser.call(
+ lambda: console._page.evaluate("navigator.clipboard.readText()")
+ )
+ console.save_evidence("translated-onboarding-prompt-copied")
+
+
+def test_project_navigation_selects_the_only_project_without_leaving(console, workshop):
+ project = workshop.project()["id"]
+ console._browser.call(console._page.evaluate, "localStorage.removeItem('__selectedProject')")
+ console.goto("/inference?inf_search=needle")
+ console.wait_until(
+ f"() => location.pathname === '/inference' && "
+ f"new URLSearchParams(location.search).get('projectId') === '{project}' && "
+ "new URLSearchParams(location.search).get('inf_search') === 'needle'"
+ )
+ console.save_evidence("project-navigation-destination")
+
+
+def test_onboarding_prompt_retains_the_selected_project(console, rest_for, account_key):
+ project = rest_for(account_key).request(
+ "POST", "/api/projects/", json={"name": "Existing setup", "slug": "existing-setup"}
+ )["id"]
+ console.goto(f"/?projectId={project}")
+ 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 f"project_id: {project}" in prompt
+ assert "dataset_id" not in prompt
+ console.save_evidence("onboarding-selected-project")
+
+
[email protected]("console_url", ["clerk"], indirect=True)
+def test_sign_in_script_failure_offers_a_document_reload(browser, console_url):
+ console = browser.page(console_url)
+ attempts = []
+
+ def external_request(route):
+ if route.request.url.startswith(console_url):
+ route.continue_()
+ else:
+ attempts.append(route.request.url)
+ route.abort()
+
+ console._browser.call(console._page.route, "**/*", external_request)
+ try:
+ console.goto("/login")
+ console.sees("Sign in unavailable")
+ before = len(attempts)
+ console.press("Reload sign in")
+ console.sees("Sign in unavailable")
+ assert len(attempts) > before
+ assert any("clerk" in url for url in attempts)
+ console.save_evidence("sign-in-script-failure")
+ finally:
+ console.close()
+
+
[email protected]("console_url", ["clerk"], indirect=True)
+def test_pending_sign_in_offers_a_document_reload(browser, console_url):
+ console = browser.page(console_url)
+ pending = []
+
+ def external_request(route):
+ if route.request.url.startswith(console_url):
+ route.continue_()
+ elif "clerk" in route.request.url:
+ pending.append(route)
+ else:
+ route.abort()
+
+ console._browser.call(console._page.route, "**/*", external_request)
+ try:
+ console._browser.call(lambda: console._page.goto("/login", wait_until="domcontentloaded"))
+ console.sees("Loading sign in")
+ console.save_evidence("sign-in-pending")
+ console._browser.call(
+ lambda: console._page.get_by_role("button", name="Reload sign in").wait_for(
+ state="visible", timeout=15000
+ )
+ )
+ before = len(pending)
+
+ def reload_sign_in():
+ with console._page.expect_request(lambda request: "clerk" in request.url):
+ console._page.get_by_role("button", name="Reload sign in").click()
+
+ console._browser.call(reload_sign_in)
+ console.sees("Loading sign in")
+ assert len(pending) > before
+ console.save_evidence("sign-in-pending-recovery")
+ finally:
+ console.close()
+
+
[email protected]("console_url", ["clerk"], indirect=True)
[email protected]("mode", ["signin", "signup"])
+def test_pending_authentication_form_offers_recovery(browser, console_url, mode):
+ console = browser.page(console_url)
+ pending = []
+
+ def external_request(route):
+ if route.request.url.startswith(console_url):
+ route.continue_()
+ elif "clerk.browser.js" in route.request.url:
+ route.fulfill(content_type="application/javascript", body=PENDING_BROWSER_FORM_SCRIPT)
+ elif route.request.url.endswith("/pending-form"):
+ pending.append(route)
+ else:
+ route.abort()
+
+ console._browser.call(console._page.route, "**/*", external_request)
+ try:
+
+ def open_form():
+ with console._page.expect_request("**/pending-form"):
+ console._page.goto("/login?mode=signup" if mode == "signup" else "/login")
+
+ console._browser.call(open_form)
+ console.sees("Set up locally")
+ assert pending
+ console.save_evidence(f"authentication-form-pending-{mode}")
+ console.sees("Loading sign in")
+
+ def reload_form():
+ with console._page.expect_request("**/pending-form"):
+ console._page.get_by_role("button", name="Reload sign in").click()
+
+ console._browser.call(reload_form)
+ console.sees("Loading sign in")
+ console.save_evidence(f"authentication-form-recovery-{mode}")
+ finally:
+ console._browser.call(lambda: console._page.unroute_all(behavior="ignoreErrors"))
+ console.close()
+
+
+def test_route_error_home_action_reloads_the_document(console):
+ console.goto("/inference?page=broken")
+ console.sees("Invalid link")
+ console._browser.call(console._page.evaluate, "window.failedDocument = true")
+ console._browser.call(lambda: console._page.get_by_role("link", name="Go to home").click())
+ console.sees("Copy onboarding prompt")
+ console.wait_until("() => location.pathname === '/' && !window.failedDocument")
+ console.save_evidence("route-error-home-recovery")
+
+
+def test_cancelled_plan_checkout_returns_to_account_settings(
+ console, console_url, settings, stripe_api, rest_for, account_key
+):
+ settings.STRIPE_PRO_PRICE_ID = "price_journey"
+ settings.FRONTEND_URL = console_url
+ rest_for(account_key).request("POST", "/api/billing/checkout/")
+ cancel_url = stripe_api.sessions[-1]["cancel_url"]
+ console.goto(cancel_url)
+ console.save_evidence("plan-checkout-cancel-return")
+ console.sees("Settings")
+ console.sees("Buy Pro")
+
+
[email protected]("linked_to_stripe", [False, True])
+def test_account_settings_only_offer_renewal_controls_for_managed_plans(
+ console, account, linked_to_stripe
+):
+ user, _ = account
+ Subscription.objects.create(
+ user=user,
+ status="active",
+ stripe_subscription_id="sub_console" if linked_to_stripe else "",
+ end_date=timezone.now() + timedelta(days=30),
+ )
+ console.goto("/settings")
+ console.sees("Plan")
+ console.sees("Pro")
+ console.save_evidence(f"plan-renewal-controls-{linked_to_stripe}")
+ assert console._browser.call(
+ lambda: console._page.get_by_role("button", name="Cancel plan", exact=True).count()
+ ) == int(linked_to_stripe)
+
+
+def test_usage_history_keeps_small_charges_visible(console, account):
+ user, _ = account
+ BillingTelemetry.objects.create(user=user, service="inference", amount="-0.0000312")
+ console.goto("/settings")
+ console.sees("Usage history")
+ console.sees("0.00312")
+ console._browser.call(
+ lambda: console._page.get_by_label("0.00312 credits", exact=True).wait_for()
+ )
+ console.save_evidence("usage-small-charge")
+
+
+def test_dataset_pagination_waits_for_the_requested_rows(
+ console, workshop, cli, sample_agent, tmp_path
+):
+ project = workshop.project()["id"]
+ dataset = upload(cli, sample_agent, tickets(tmp_path, n=25))
+ console.goto(f"/datasets/{dataset}?projectId={project}")
+ console.sees("1–10 of 25 rows")
+ pending = []
+ console._browser.call(
+ console._page.route, "**/rows/?*offset=10*", lambda route: pending.append(route)
+ )
+ try:
+ console.press("Go to next page")
+ console.sees("Loading page 2")
+ assert console._browser.call(
+ lambda: console._page.get_by_role("button", name="Go to next page").is_disabled()
+ )
+ assert pending
+ console._browser.call(lambda: pending.pop().continue_())
+ console.sees("11–20 of 25 rows")
+ console.sees("Refund order 10 please", exact=False)
+ console.save_evidence("dataset-pagination-next-page")
+ finally:
+ for route in pending:
+ console._browser.call(route.continue_)
+ console._browser.call(console._page.unroute, "**/rows/?*offset=10*")
+
+
+def test_dataset_navigation_keeps_rows_with_their_source(
+ console, workshop, cli, sample_agent, tmp_path, worker
+):
+ project = workshop.project()["id"]
+ first_path = tickets(tmp_path, n=25).rename(tmp_path / "large-source.jsonl")
+ first = upload(cli, sample_agent, first_path)
+ second_path = tickets(tmp_path, n=3).rename(tmp_path / "small-source.jsonl")
+ second = upload(cli, sample_agent, second_path)
+ drain(worker)
+ console.goto(f"/datasets/{first}?projectId={project}")
+ console.sees("1–10 of 25 rows")
+ console._browser.call(
+ lambda: console._page.get_by_role("link", name="Datasets", exact=True).first.click()
+ )
+ console.click("small-source.jsonl")
+ console.wait_until(f"() => location.pathname === '/datasets/{second}'")
+ console.sees("3 rows × 2")
+ console.wait_until("() => !document.body.innerText.includes('of 25 rows')")
+ console.sees("Refund order 2 please", exact=False)
+ console.save_evidence("dataset-navigation-matching-source")
+
+
+def test_dataset_pagination_starts_at_the_first_row(console, workshop, cli, sample_agent, tmp_path):
+ project = workshop.project()["id"]
+ dataset = upload(cli, sample_agent, tickets(tmp_path, n=225))
+ console.goto(f"/datasets/{dataset}?projectId={project}")
+ console.sees("1–10 of 225 rows")
+ console._browser.call(lambda: console._page.get_by_role("combobox").click())
+ console._browser.call(
+ lambda: console._page.get_by_role("option", name="100", exact=True).click()
+ )
+ console.sees("1–100 of 225 rows")
+ console._browser.call(
+ lambda: console._page.get_by_role(
+ "button", name="Inspect row 99", exact=True
+ ).scroll_into_view_if_needed()
+ )
+ console.save_evidence("dataset-pagination-before-next")
+ console.press("Go to next page")
+ console.sees("101–200 of 225 rows")
+ console._browser.call(
+ lambda: console._page.get_by_role("button", name="Inspect row 100", exact=True).wait_for()
+ )
+ console.save_evidence("dataset-pagination-first-row")
+ console.wait_until("""() => {
+ const row = document.querySelector('button[aria-label="Inspect row 100"]');
+ const rect = row.getBoundingClientRect();
+ return rect.top >= 0 && rect.bottom <= innerHeight;
+ }""")
+
+
+def test_evaluation_dataset_picker_waits_for_its_options(
+ console, workshop, cli, sample_agent, tmp_path, fake_llm
+):
+ fake_llm.catalog_payload = [{"id": "qwen/qwen3-8b", "name": "Qwen: Qwen3 8B"}]
+ project = workshop.project()["id"]
+ upload(cli, sample_agent, tickets(tmp_path), "--intent", "eval")
+ pending = []
+
+ def hold_eval_datasets(route):
+ if "intent=eval" in route.request.url:
+ pending.append(route)
+ else:
+ route.continue_()
+
+ console._browser.call(console._page.route, "**/datasets/?*", hold_eval_datasets)
+ try:
+ console.goto(f"/evaluations?projectId={project}")
+ console.press("New evaluation")
+ console._browser.call(
+ lambda: console._page.get_by_role("button", name="Eval dataset", exact=True).click()
+ )
+ assert pending
+ console.sees("Loading options")
+ console.save_evidence("evaluation-dataset-picker-pending")
+ console._browser.call(lambda: pending.pop().continue_())
+ console._browser.call(
+ lambda: console._page.get_by_role("radio", name="tickets.jsonl", exact=True).click()
+ )
+ console._browser.call(
+ lambda: (
+ console._page.get_by_role("button", name="Eval dataset", exact=True)
+ .get_by_text("tickets.jsonl", exact=True)
+ .wait_for()
+ )
+ )
+ console.save_evidence("evaluation-dataset-picker-selected")
+ console._browser.call(
+ lambda: console._page.get_by_role(
+ "button", name="Model being tested", exact=True
+ ).click()
+ )
+ model_picker_id = console._browser.call(
+ lambda: console._page.get_by_role(
+ "button", name="Model being tested", exact=True
+ ).get_attribute("aria-controls")
+ )
+ console._browser.call(
+ lambda: (
+ console._page.locator(f'[id="{model_picker_id}"]')
+ .get_by_role("textbox", name="Search…", exact=True)
+ .fill("qwen")
+ )
+ )
+ console._browser.call(
+ lambda: console._page.get_by_role("radio", name="Qwen3 8B", exact=True).click()
+ )
+ console._browser.call(
+ lambda: (
+ console._page.get_by_role("button", name="Model being tested", exact=True)
+ .get_by_text("Qwen3 8B", exact=True)
+ .wait_for()
+ )
+ )
+ console.save_evidence("evaluation-model-search-selected")
+ finally:
+ for route in pending:
+ console._browser.call(route.continue_)
+ console._browser.call(console._page.unroute, "**/datasets/?*")
+
+
[email protected]("clear_action", ["Clear search", "Clear filters"])
+def test_inference_search_clear_restores_models(console, workshop, clear_action):
+ project = workshop.project()["id"]
+ dataset = Dataset.objects.create(project_id=project, name="Search fixture")
+ job = FinetuningJob.objects.create(
+ project_id=project,
+ dataset=dataset,
+ base_model="Qwen/Qwen3-8B",
+ status="succeeded",
+ output_model_name="ft-search-result",
+ )
+ DeployedModel.objects.create(
+ project_id=project, finetuning_job=job, model_id="ft-search-result", status="ready"
+ )
+ console.goto(f"/inference?projectId={project}&inf_search=missing-model")
+ console.sees("No results")
+ console.press(clear_action)
+ console.sees("ft-search-result")
+ console.wait_until("() => !new URLSearchParams(location.search).get('inf_search')")
+ console.save_evidence(f"inference-{clear_action.lower().replace(' ', '-')}")
+
+
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"]
@@ -512,6 +914,40 @@ def test_decision_data_selects_native_training_controls(
assert not FinetuningJob.objects.filter(project_id=project).exists()
+def test_api_key_remains_private_in_session_replay(console, workshop, replay_recorder):
+ project = workshop.project()["id"]
+ console.goto(f"/projects/{project}?projectId={project}")
+ console.press("New API key")
+ console._browser.call(lambda: console._page.add_script_tag(path=str(replay_recorder)))
+ console._browser.call(
+ console._page.evaluate,
+ """() => {
+ window.replayEvents = [];
+ window.stopReplay = ReplayRecorder.record({
+ emit: event => window.replayEvents.push(event),
+ blockClass: 'ph-no-capture', maskTextClass: 'ph-mask', maskAllInputs: true
+ });
+ }""",
+ )
+ console.press("Create API key")
+ console.sees("Your new API key:")
+ console.wait_until("() => window.replayEvents.some(event => event.type === 3)")
+ leaked = console._browser.call(
+ console._page.evaluate,
+ """() => {
+ ReplayRecorder.record.takeFullSnapshot();
+ const key = document.querySelector('[role="dialog"] code').textContent;
+ const leaked = JSON.stringify(window.replayEvents).includes(key);
+ window.stopReplay();
+ return leaked;
+ }""",
+ )
+ console.press("Done")
+ console.wait_until("() => !document.querySelector('[role=\"dialog\"]')")
+ console.save_evidence("api-key-replay-privacy")
+ assert leaked is False, "Session replay captured the API key"
+
+
def test_native_monitoring_evidence_remains_readable_after_cancellation(console, workshop):
project = workshop.project()["id"]
group = uuid.uuid4()
@@ -522,6 +958,7 @@ def test_native_monitoring_evidence_remains_readable_after_cancellation(console,
status="running",
group_id=group,
hyperparameters={"objective": "decision_cross_entropy"},
+ progress={"activity": [{"ts": 1, "message": "Booting and verifying"}]},
)
examples = [
{
@@ -561,6 +998,7 @@ def test_native_monitoring_evidence_remains_readable_after_cancellation(console,
console.goto(f"/training?projectId={project}&groupId={group}&jobId={job.pk}")
console.sees("Development loss")
console.sees("0.6250")
+ console.sees("Running — Booting and verifying")
check = job.validation_runs.get()
evidence = workshop.call(
"inspect_training_progress", {"job": str(job.pk), "check": str(check.pk)}
@@ -570,6 +1008,7 @@ def test_native_monitoring_evidence_remains_readable_after_cancellation(console,
console.sees("Requests cancellation. Completed checks and saved checkpoints remain available.")
console.press("Cancel Job")
console.sees("Cancelled")
+ console.wait_until("() => !document.body.innerText.includes('Booting and verifying')")
job.refresh_from_db()
assert job.status == "cancelled"
console.goto(f"/training?projectId={project}&groupId={group}&jobId={job.pk}")
diff --git a/tests/test_dataset_chain.py b/tests/test_dataset_chain.py
index 5719c595..32b9e1fe 100644
--- a/tests/test_dataset_chain.py
+++ b/tests/test_dataset_chain.py
@@ -3,7 +3,7 @@ from __future__ import annotations
import uuid
import pytest
-from conftest import EVAL_ROWS, TRAIN_ROWS, import_version, review_fixture
+from conftest import EVAL_ROWS, TRAIN_ROWS, frozen_dataset, import_version, review_fixture
from overbae.models import Capability, Cell, Dataset, EvalRun, Project
from overbae.services.datasets import diff, land, lifecycle, paths, store, use
@@ -142,6 +142,14 @@ def test_use_marks_the_cell_and_starts_a_new_major(django_assert_num_queries):
assert dataset.versions(chain=[]) == {}
+def test_versions_see_a_use_made_after_the_cells_were_prefetched():
+ dataset = frozen_dataset(_project(), contract="train")
+ child = Cell.objects.create(dataset=dataset, position=1, title="step", state="ok")
+ loaded = Dataset.objects.prefetch_related("cells").get(pk=dataset.pk)
+ use.freeze(child)
+ assert loaded.versions()[child.id] == "2.0"
+
+
def test_a_used_cell_is_protected_and_blocks_deletion():
project = _project()
dataset = _landed(project, [dict(r) for r in EVAL_ROWS], intent="eval")
diff --git a/tests/test_finetuning_runs_api.py b/tests/test_finetuning_runs_api.py
index 162b641d..15ad5b6e 100644
--- a/tests/test_finetuning_runs_api.py
+++ b/tests/test_finetuning_runs_api.py
@@ -5,6 +5,8 @@ from datetime import timedelta
import pytest
from conftest import TRAIN_ROWS, frozen_dataset
+from django.db import connection
+from django.test.utils import CaptureQueriesContext
from django.urls import reverse
from django.utils import timezone
from rest_framework.test import APIClient
@@ -57,6 +59,24 @@ def test_group_id_filter_finds_a_run_regardless_of_its_age():
assert {row["id"] for row in body["results"]} == {str(j.id) for j in wanted}
[email protected]("endpoint", [LIST_URL, RUNS_URL])
+def test_training_history_reads_dataset_versions_once_per_page(endpoint):
+ client, project, dataset = _setup()
+ cell = dataset.active_cell
+ assert cell is not None
+ _job(project, dataset, cell=cell)
+ with CaptureQueriesContext(connection) as first:
+ response = client.get(endpoint, {"project": str(project.id), "page_size": 25})
+ assert response.status_code == 200, response.content
+ for _ in range(9):
+ _job(project, dataset, cell=cell)
+ with CaptureQueriesContext(connection) as many:
+ response = client.get(endpoint, {"project": str(project.id), "page_size": 25})
+ assert response.status_code == 200, response.content
+ assert response.json()["count"] == 10
+ assert len(many) <= len(first) + 1, (len(first), len(many))
+
+
def test_runs_returns_whole_runs_and_counts_runs_not_jobs():
client, project, dataset = _setup()
groups = [uuid.uuid4() for _ in range(3)]