Skip to content

The platform for continuously improving AI agents.

Fix Console pagination, polling, and job state (#312)

Tyler-Edwards1d14d8de14c6
diff --git a/frontend/src/components/capability-detail/ModelsTab.tsx b/frontend/src/components/capability-detail/ModelsTab.tsx
index 3c7d1c38..4c4e148e 100644
--- a/frontend/src/components/capability-detail/ModelsTab.tsx
+++ b/frontend/src/components/capability-detail/ModelsTab.tsx
@@ -305,6 +305,7 @@ export function ModelsTab({ capability, capabilityId, projectId }: ModelsTabProp
refetch,
} = useDeployedModelsQuery({ capability: capabilityId, pageSize: 100, projectId });
const models = deployed?.results ?? [];
+ const incumbentQuery = useDeployedModelQuery(capability.activeModel ?? undefined);
const [modelSearch, setModelSearch] = useState("");
const [modelStatus, setModelStatus] = useState("all");
const filteredModels = useMemo(() => {
@@ -349,7 +350,7 @@ export function ModelsTab({ capability, capabilityId, projectId }: ModelsTabProp
? variables?.id
: null;
const liveId = capability.activeModel ?? null;
- const live = models.find((m) => m.id === liveId) ?? null;
+ const live = incumbentQuery.data ?? models.find((m) => m.id === liveId) ?? null;
return (
<TooltipProvider>
@@ -486,7 +487,7 @@ export function ModelsTab({ capability, capabilityId, projectId }: ModelsTabProp
key={m.id}
model={m}
onSetLive={guard((model: DeployedModel) => {
- if (!pendingId) setLive(model, live);
+ if (!pendingId && (!liveId || live)) setLive(model, live);
})}
projectId={projectId}
/>
diff --git a/frontend/src/components/evaluations/generated-run-results.tsx b/frontend/src/components/evaluations/generated-run-results.tsx
index 62de785d..a8d3ffef 100644
--- a/frontend/src/components/evaluations/generated-run-results.tsx
+++ b/frontend/src/components/evaluations/generated-run-results.tsx
@@ -1,6 +1,6 @@
import { useMemo, useRef, useState } from "react";
-import { useQueries } from "@tanstack/react-query";
+import { useQueries, useQueryClient } from "@tanstack/react-query";
import type { ColumnDef } from "@tanstack/react-table";
import { EntityRef } from "@/components/entity-ref";
@@ -33,7 +33,11 @@ import {
TableHeader,
TableRow,
} from "@/components/ui/table";
-import { fetchEvalRunRows, isActiveRunStatus } from "@/hooks/use-evaluations";
+import {
+ evalRowsPollingInterval,
+ fetchEvalRunRows,
+ isActiveRunStatus,
+} from "@/hooks/use-evaluations";
import { TITLE } from "@/lib/typography";
import type { EvalRun, EvalRunRow } from "@/openapi";
@@ -123,11 +127,20 @@ function Payload({ title, value }: { title: string; value: unknown }) {
export function GeneratedRunResults({ runs }: { runs: EvalRun[] }) {
const datapointsRef = useRef<HTMLElement>(null);
+ const queryClient = useQueryClient();
const queries = useQueries({
queries: runs.map((run) => ({
- queryFn: () => fetchEvalRunRows(run.id),
- queryKey: ["eval-run-rows", run.id],
- refetchInterval: isActiveRunStatus(run.status) ? 4000 : (false as const),
+ // The key changes when a run finishes; show the rows polled while it ran.
+ placeholderData: () =>
+ queryClient.getQueryData<Awaited<ReturnType<typeof fetchEvalRunRows>>>([
+ "eval-run-rows",
+ run.id,
+ true,
+ ]),
+ queryFn: ({ signal }: { signal: AbortSignal }) => fetchEvalRunRows(run.id, signal),
+ queryKey: ["eval-run-rows", run.id, isActiveRunStatus(run.status)],
+ refetchInterval: (q: { state: { status: string; data?: { count: number } } }) =>
+ evalRowsPollingInterval(q, isActiveRunStatus(run.status)),
})),
});
const points = alignRunDatapoints(
diff --git a/frontend/src/components/evaluations/generated-run-results.ui.test.tsx b/frontend/src/components/evaluations/generated-run-results.ui.test.tsx
index c9433031..89401b32 100644
--- a/frontend/src/components/evaluations/generated-run-results.ui.test.tsx
+++ b/frontend/src/components/evaluations/generated-run-results.ui.test.tsx
@@ -7,6 +7,10 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { EvalRun, EvalRunRow } from "@/openapi";
import { GeneratedRunResults } from "./generated-run-results";
+vi.mock("@/client", () => ({
+ default: { evalRunRows: { evalRunRowsList: () => new Promise(() => {}) } },
+}));
+
beforeEach(() => {
vi.stubGlobal(
"ResizeObserver",
@@ -54,7 +58,7 @@ it("opens all model outputs together, retaining full text, reasoning, errors and
] as EvalRunRow[];
for (const run of runs) {
const results = samples.filter((sample) => sample.run === run.id);
- client.setQueryData(["eval-run-rows", run.id], { count: results.length, results });
+ client.setQueryData(["eval-run-rows", run.id, false], { count: results.length, results });
}
render(
<QueryClientProvider client={client}>
@@ -72,3 +76,17 @@ it("opens all model outputs together, retaining full text, reasoning, errors and
fireEvent.click(dialog.getByRole("button", { name: "Close" }));
client.clear();
});
+
+it("keeps the rows polled while a run was active during its final fetch", () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const run = { cell: "cell", id: "alpha", label: "alpha", status: "completed", summary: {} };
+ const row = { id: 1, input: "in", metrics: {}, output: "out", rowIndex: 0, run: "alpha" };
+ client.setQueryData(["eval-run-rows", "alpha", true], { count: 1, results: [row] });
+ render(
+ <QueryClientProvider client={client}>
+ <GeneratedRunResults runs={[run as EvalRun]} />
+ </QueryClientProvider>
+ );
+ expect(screen.getByRole("button", { name: "Open alpha output for datapoint 0" })).toBeTruthy();
+ client.clear();
+});
diff --git a/frontend/src/components/finetuning/model-live-action.test.tsx b/frontend/src/components/finetuning/model-live-action.test.tsx
index 83cc35b6..a98ecfde 100644
--- a/frontend/src/components/finetuning/model-live-action.test.tsx
+++ b/frontend/src/components/finetuning/model-live-action.test.tsx
@@ -16,12 +16,13 @@ const mocks = vi.hoisted(() => ({
capabilitiesPartialUpdate: vi.fn(),
swapPromptProps: vi.fn(),
useCapabilityDetailQuery: vi.fn(),
+ useDeployedModelQuery: vi.fn(),
useDeployedModelsQuery: vi.fn(),
}));
vi.mock("@/hooks/use-query", () => ({ useCapabilityDetailQuery: mocks.useCapabilityDetailQuery }));
vi.mock("@/hooks/use-inference", () => ({
- useDeployedModelQuery: () => ({ data: undefined }),
+ useDeployedModelQuery: mocks.useDeployedModelQuery,
useDeployedModelsQuery: mocks.useDeployedModelsQuery,
}));
vi.mock("@/client", () => ({
@@ -96,6 +97,12 @@ const renderAction = ({
data: deployedPending ? undefined : { count: models.length, results: models },
isPending: deployedPending,
});
+ mocks.useDeployedModelQuery.mockReturnValue({
+ data: capability?.activeModel
+ ? deployment(capability.activeModel, capability.activeModel === "dm-wide" ? 8192 : 4096)
+ : undefined,
+ isPending: false,
+ });
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={queryClient}>
@@ -173,10 +180,9 @@ describe("ModelLiveAction — the retarget state", () => {
// Inherited from the Models tab through the shared mutation.
it("asks before narrowing the context window", async () => {
- const incumbent = { ...deployment("dm-wide", 8192), finetuningJobId: "job-w" };
renderAction({
capability: capabilityState({ activeModel: "dm-wide" }),
- models: [incumbent as DeployedModel, deployment("dm-1", 4096)],
+ models: [deployment("dm-1", 4096)],
});
fireEvent.click(screen.getByLabelText("Make live — ft:dm-1"));
diff --git a/frontend/src/components/finetuning/model-live-action.tsx b/frontend/src/components/finetuning/model-live-action.tsx
index bccdea33..6c75f0ba 100644
--- a/frontend/src/components/finetuning/model-live-action.tsx
+++ b/frontend/src/components/finetuning/model-live-action.tsx
@@ -10,7 +10,7 @@ import {
SetActiveModelButton,
} from "@/components/finetuning/set-active-model-button";
import { Skeleton } from "@/components/ui/skeleton";
-import { useDeployedModelsQuery } from "@/hooks/use-inference";
+import { useDeployedModelQuery, useDeployedModelsQuery } from "@/hooks/use-inference";
import { useCapabilityDetailQuery } from "@/hooks/use-query";
import type { DeployedModel, FinetuningJobList } from "@/openapi";
@@ -42,11 +42,13 @@ export function ModelLiveAction({
});
const capability = capabilityQuery.data;
+ const incumbentQuery = useDeployedModelQuery(capability?.activeModel ?? undefined);
const models = deployedQuery.data?.results ?? [];
const jobId = jobs[0]?.id;
const candidate = model ?? (jobId ? models.find((m) => m.finetuningJobId === jobId) : undefined);
// What the alias answers with today; null when it answers nothing.
- const incumbent = models.find((m) => m.id === capability?.activeModel) ?? null;
+ const incumbent =
+ incumbentQuery.data ?? models.find((m) => m.id === capability?.activeModel) ?? null;
const isLive = !!candidate && capability?.activeModel === candidate.id;
const control = (() => {
@@ -79,7 +81,7 @@ export function ModelLiveAction({
<span className="inline-flex items-center gap-2">
{prompt}
<SetActiveModelButton
- activating={activationPending(capability)}
+ activating={activationPending(capability) || (!!capability?.activeModel && !incumbent)}
candidate={candidate}
capabilityId={capabilityId}
incumbent={incumbent}
diff --git a/frontend/src/contexts/auth-context.tsx b/frontend/src/contexts/auth-context.tsx
index 264bdd02..7dec6c47 100644
--- a/frontend/src/contexts/auth-context.tsx
+++ b/frontend/src/contexts/auth-context.tsx
@@ -8,7 +8,6 @@ import apiClient, {
getAccessToken,
getLocalAccountId,
getLocalIdentity,
- ResponseError,
rememberLocalIdentity,
setAsyncTokenGetter,
setTokens,
@@ -16,6 +15,7 @@ import apiClient, {
import { config } from "@/config";
import { setStoredProjectId } from "@/hooks/use-project-search-sync";
import { getContext } from "@/integrations/tanstack-query";
+import { isPermanentApiRefusal } from "@/lib/api-error";
import { emitGuestUpgrade, hasGuestSession, markGuestSession } from "@/lib/guest";
import { notify } from "@/lib/notify";
@@ -78,7 +78,10 @@ function ClerkAuthProvider({ children }: { children: React.ReactNode }) {
let settled = true;
try {
const token = await getToken();
- if (!token) return;
+ if (!token) {
+ settled = false;
+ return;
+ }
const claimed = await apiClient.auth.authGuestClaimCreate({
guestClaimRequest: { clerkToken: token },
});
@@ -86,7 +89,7 @@ function ClerkAuthProvider({ children }: { children: React.ReactNode }) {
trackEvent("guest_claimed");
} catch (err) {
// A refusal is final; a transport failure keeps the guest so a reload retries.
- settled = err instanceof ResponseError && err.response.status < 500;
+ settled = isPermanentApiRefusal(err);
notify.error(err, "Could not attach the demo workspace to this account.");
} finally {
if (settled) {
diff --git a/frontend/src/hooks/use-evaluations.rows.test.tsx b/frontend/src/hooks/use-evaluations.rows.test.tsx
index 1264a7f2..20bd06a6 100644
--- a/frontend/src/hooks/use-evaluations.rows.test.tsx
+++ b/frontend/src/hooks/use-evaluations.rows.test.tsx
@@ -9,7 +9,7 @@ vi.mock("@/client", () => ({
default: { evalRunRows: { evalRunRowsList: listRows } },
}));
-import { useEvalRunRowsQuery } from "./use-evaluations";
+import { evalRowsPollingInterval, useEvalRunRowsQuery } from "./use-evaluations";
afterEach(() => {
cleanup();
@@ -31,12 +31,31 @@ it("loads every server page so local filtering and pagination retain later rows"
{ id: 1, score: 1 },
{ id: 2, score: 0 },
]);
- expect(listRows).toHaveBeenNthCalledWith(2, {
- ordering: "row_index",
- page: 2,
- pageSize: 1000,
- run: "run",
- });
+ expect(listRows).toHaveBeenNthCalledWith(
+ 2,
+ {
+ ordering: "row_index",
+ page: 2,
+ pageSize: 1000,
+ run: "run",
+ },
+ { signal: expect.any(AbortSignal) }
+ );
expect(listRows).toHaveBeenCalledTimes(2);
client.clear();
});
+
+it("reduces refresh frequency as full result sets grow and stops on errors", () => {
+ const small = evalRowsPollingInterval(
+ { state: { data: { count: 10 }, status: "success" } },
+ true
+ );
+ const large = evalRowsPollingInterval(
+ { state: { data: { count: 10_000 }, status: "success" } },
+ true
+ );
+ expect(large).toBeGreaterThan(small as number);
+ expect(
+ evalRowsPollingInterval({ state: { data: { count: 10_000 }, status: "error" } }, true)
+ ).toBe(false);
+});
diff --git a/frontend/src/hooks/use-evaluations.ts b/frontend/src/hooks/use-evaluations.ts
index a0a8e2aa..780b9a91 100644
--- a/frontend/src/hooks/use-evaluations.ts
+++ b/frontend/src/hooks/use-evaluations.ts
@@ -1,4 +1,4 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import apiClient from "@/client";
import { notify } from "@/lib/notify";
@@ -237,26 +237,43 @@ export const useEvalRunComparisonQuery = (
retry: false,
});
-export async function fetchEvalRunRows(runId: string) {
+export async function fetchEvalRunRows(runId: string, signal?: AbortSignal) {
const results: EvalRunRow[] = [];
for (let page = 1; ; page++) {
- const data = await apiClient.evalRunRows.evalRunRowsList({
- ordering: "row_index",
- page,
- pageSize: 1000,
- run: runId,
- });
+ const data = await apiClient.evalRunRows.evalRunRowsList(
+ {
+ ordering: "row_index",
+ page,
+ pageSize: 1000,
+ run: runId,
+ },
+ { signal }
+ );
results.push(...data.results);
if (!data.next) return { ...data, next: null, previous: null, results };
}
}
+export function evalRowsPollingInterval(
+ query: { state: { status: string; data?: { count: number } } },
+ active: boolean
+) {
+ // Large result sets still support cross-page filtering; refresh them less often.
+ return backoffPolling(
+ query,
+ active
+ ? Math.min(60_000, 4_000 * Math.max(1, Math.ceil((query.state.data?.count ?? 0) / 1000)))
+ : false
+ );
+}
+
export const useEvalRunRowsQuery = (runId: string | undefined, active = false) =>
useQuery({
enabled: !!runId,
- queryFn: () => fetchEvalRunRows(runId!),
- queryKey: ["eval-run-rows", runId],
- refetchInterval: (q) => backoffPolling(q, active ? 4_000 : false),
+ placeholderData: keepPreviousData,
+ queryFn: ({ signal }) => fetchEvalRunRows(runId!, signal),
+ queryKey: ["eval-run-rows", runId, active],
+ refetchInterval: (q) => evalRowsPollingInterval(q, active),
});
export const useEvalRunRowQuery = (id: number | undefined) =>
diff --git a/frontend/src/hooks/use-finetuning.runs.test.ts b/frontend/src/hooks/use-finetuning.runs.test.ts
index 1678d5cf..f53b68a6 100644
--- a/frontend/src/hooks/use-finetuning.runs.test.ts
+++ b/frontend/src/hooks/use-finetuning.runs.test.ts
@@ -98,7 +98,13 @@ describe("useFinetuningRunsQuery", () => {
const poll = options.refetchInterval;
if (typeof poll !== "function") throw new Error("Expected adaptive history polling");
const query = (jobs: { status: string }[], fetchFailureCount = 0) =>
- ({ state: { data: { results: [{ jobs }] }, fetchFailureCount } }) as never;
+ ({
+ state: {
+ data: { results: [{ jobs }] },
+ fetchFailureCount,
+ status: fetchFailureCount ? "error" : "success",
+ },
+ }) as never;
expect(poll(query([]))).toBe(10_000);
expect(poll(query([{ status: "succeeded" }]))).toBe(10_000);
expect(poll(query([{ status: "preprocessing" }]))).toBe(5_000);
diff --git a/frontend/src/hooks/use-running-jobs.ts b/frontend/src/hooks/use-running-jobs.ts
index 629426e1..b740d4d3 100644
--- a/frontend/src/hooks/use-running-jobs.ts
+++ b/frontend/src/hooks/use-running-jobs.ts
@@ -11,6 +11,7 @@ import {
completionToastCopy,
detectCompletedJobs,
type RunningJobItem,
+ rememberActive,
} from "@/lib/running-jobs";
import {
clearUnseenCompletions,
@@ -101,7 +102,7 @@ export function useRunningJobs(projectId: string | undefined) {
}
const completed = detectCompletedJobs(previouslyActive.current, current, latest);
- previouslyActive.current = new Map(current.map((j) => [j.key, j]));
+ rememberActive(previouslyActive.current, current, completed);
if (completed.length === 0) return;
diff --git a/frontend/src/hooks/use-tokens.test.tsx b/frontend/src/hooks/use-tokens.test.tsx
new file mode 100644
index 00000000..3c901221
--- /dev/null
+++ b/frontend/src/hooks/use-tokens.test.tsx
@@ -0,0 +1,50 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, renderHook, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import { useTokensList } from "./use-tokens";
+
+const list = vi.hoisted(() => vi.fn());
+vi.mock("@/client", () => ({ default: { auth: { authApiKeysList: list } } }));
+afterEach(() => {
+ cleanup();
+ vi.resetAllMocks();
+});
+it("finds project keys after the first account page", async () => {
+ list
+ .mockResolvedValueOnce({
+ next: "page2",
+ results: [{ id: "other", project: "other", scope: {} }],
+ })
+ .mockResolvedValueOnce({
+ next: null,
+ results: [{ id: "target", project: "project", scope: {} }],
+ });
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { result } = renderHook(() => useTokensList("project"), {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.tokens.map((token) => token.id)).toEqual(["target"]);
+ expect(list).toHaveBeenCalledTimes(2);
+ client.clear();
+});
+it("keeps one entry per key when a key shifts between pages", async () => {
+ const key = { id: "target", project: "project", scope: {} };
+ list
+ .mockResolvedValueOnce({ next: "page2", results: [key] })
+ .mockResolvedValueOnce({ next: null, results: [key] });
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const { result } = renderHook(() => useTokensList("project"), {
+ wrapper: ({ children }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ ),
+ });
+ await waitFor(() => expect(result.current.isSuccess).toBe(true));
+ expect(result.current.data?.tokens.map((token) => token.id)).toEqual(["target"]);
+ client.clear();
+});
diff --git a/frontend/src/hooks/use-tokens.ts b/frontend/src/hooks/use-tokens.ts
index 11321739..454dbc31 100644
--- a/frontend/src/hooks/use-tokens.ts
+++ b/frontend/src/hooks/use-tokens.ts
@@ -6,11 +6,17 @@ import { notify } from "@/lib/notify";
export function useTokensList(projectId?: string) {
return useQuery({
enabled: !!projectId,
- queryFn: async () => {
+ queryFn: async ({ signal }) => {
const pid = projectId ?? "";
- const res = await apiClient.auth.authApiKeysList({ page: undefined, search: undefined });
+ // A key created mid-walk shifts later pages, so one key can arrive twice.
+ const byId = new Map();
+ for (let page = 1; ; page++) {
+ const res = await apiClient.auth.authApiKeysList({ page }, { signal });
+ for (const key of res.results) byId.set(key.id, key);
+ if (!res.next) break;
+ }
return {
- tokens: res.results
+ tokens: [...byId.values()]
.filter(
(k) =>
k.project === pid ||
diff --git a/frontend/src/hooks/use-uploads.ts b/frontend/src/hooks/use-uploads.ts
index 57caa89a..e2615d41 100644
--- a/frontend/src/hooks/use-uploads.ts
+++ b/frontend/src/hooks/use-uploads.ts
@@ -1,9 +1,9 @@
import { useCallback, useEffect, useRef, useState } from "react";
import apiClient from "@/client";
+import { isPermanentApiRefusal } from "@/lib/api-error";
import { formatBytes } from "@/lib/formatters";
import type { UploadReserved, UploadState } from "@/openapi";
-import { ResponseError } from "@/openapi";
export interface UploadProgress {
sent: number;
@@ -13,10 +13,6 @@ export interface UploadProgress {
/** The server's refusal reason, when there is one — never a generic code. */
async function uploadError(err: unknown): Promise<Error> {
- if (err instanceof ResponseError) {
- const detail = (await err.response.json().catch(() => null))?.detail;
- if (typeof detail === "string" && detail) return new Error(detail);
- }
return err instanceof Error ? err : new Error("Upload failed.");
}
@@ -35,7 +31,7 @@ async function sendChunk(
try {
return await apiClient.uploads.uploadsChunkUpdate({ body, id, offset }, { signal });
} catch (err) {
- const refused = err instanceof ResponseError;
+ const refused = isPermanentApiRefusal(err);
if (refused || signal?.aborted || attempt === CHUNK_ATTEMPTS) throw await uploadError(err);
await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
}
diff --git a/frontend/src/lib/api-error.test.ts b/frontend/src/lib/api-error.test.ts
new file mode 100644
index 00000000..34f3ae50
--- /dev/null
+++ b/frontend/src/lib/api-error.test.ts
@@ -0,0 +1,21 @@
+// covers: console-logic
+import { expect, it } from "vitest";
+
+import { ApiError, isPermanentApiRefusal } from "./api-error";
+import { PaymentRequiredError } from "./credits";
+import { GuestUpgradeError } from "./guest";
+import { PlanLimitError } from "./plan-limits";
+
+it.each([0, 408, 429, 500, 503])("keeps retryable HTTP %s failures recoverable", (status) => {
+ expect(isPermanentApiRefusal(new ApiError(status, "failure", true))).toBe(false);
+});
+it.each([400, 401, 403, 404, 409, 413, 422])("recognizes permanent HTTP %s refusals", (status) => {
+ expect(isPermanentApiRefusal(new ApiError(status, "refused", true))).toBe(true);
+});
+it.each([
+ new PaymentRequiredError(),
+ new GuestUpgradeError(),
+ new PlanLimitError("Seat limit"),
+])("recognizes the client's specialised refusal %s", (error) => {
+ expect(isPermanentApiRefusal(error)).toBe(true);
+});
diff --git a/frontend/src/lib/api-error.ts b/frontend/src/lib/api-error.ts
index c9e17834..340f8050 100644
--- a/frontend/src/lib/api-error.ts
+++ b/frontend/src/lib/api-error.ts
@@ -1,3 +1,7 @@
+import { PaymentRequiredError } from "@/lib/credits";
+import { GuestUpgradeError } from "@/lib/guest";
+import { PlanLimitError } from "@/lib/plan-limits";
+
/**
* Thrown by the `client.ts` middleware for non-2xx responses, in place of the
* generated client's `ResponseError` whose message is always the literal
@@ -17,6 +21,22 @@ export class ApiError extends Error {
}
}
+export function isPermanentApiRefusal(error: unknown): boolean {
+ // The client raises these for 402 and 403 bodies before the generic ApiError.
+ if (
+ error instanceof PaymentRequiredError ||
+ error instanceof GuestUpgradeError ||
+ error instanceof PlanLimitError
+ )
+ return true;
+ return (
+ error instanceof ApiError &&
+ error.status >= 400 &&
+ error.status < 500 &&
+ ![408, 429].includes(error.status)
+ );
+}
+
export const NETWORK_ERROR_MESSAGE =
"Could not reach the server. Check your connection and try again.";
diff --git a/frontend/src/lib/poll.test.ts b/frontend/src/lib/poll.test.ts
new file mode 100644
index 00000000..f480f425
--- /dev/null
+++ b/frontend/src/lib/poll.test.ts
@@ -0,0 +1,18 @@
+// covers: console-logic
+import { QueryClient } from "@tanstack/react-query";
+import { expect, it } from "vitest";
+
+import { backoffPolling } from "./poll";
+
+it("stops after the retry budget and resumes after a successful explicit refetch", async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: 1, retryDelay: 0 } } });
+ await client
+ .fetchQuery({ queryFn: () => Promise.reject(new Error("offline")), queryKey: ["poll"] })
+ .catch(() => {});
+ const query = client.getQueryCache().find({ queryKey: ["poll"] })!;
+ expect(query.state.fetchFailureCount).toBe(2);
+ expect(backoffPolling(query, 5000)).toBe(false);
+ await client.fetchQuery({ queryFn: async () => "recovered", queryKey: ["poll"] });
+ expect(backoffPolling(query, 5000)).toBe(5000);
+ client.clear();
+});
diff --git a/frontend/src/lib/poll.ts b/frontend/src/lib/poll.ts
index f15c6d06..829d3caf 100644
--- a/frontend/src/lib/poll.ts
+++ b/frontend/src/lib/poll.ts
@@ -1,11 +1,9 @@
-/** Stops the poll loop rather than hammering a failing endpoint; any later
- * successful fetch (a refocus refetch, say) resets the count and resumes it. */
-const POLL_FAILURE_LIMIT = 3;
-
+/** A fetch exhausts its configured retries before entering error state.
+ * Refocus or an explicit refetch can recover it and resume polling. */
export function backoffPolling(
- query: { state: { fetchFailureCount: number } },
+ query: { state: { status: string } },
interval: number | false | (() => number | false)
): number | false {
- if (query.state.fetchFailureCount >= POLL_FAILURE_LIMIT) return false;
+ if (query.state.status === "error") return false;
return typeof interval === "function" ? interval() : interval;
}
diff --git a/frontend/src/lib/running-jobs.test.ts b/frontend/src/lib/running-jobs.test.ts
index 451f80af..b5937906 100644
--- a/frontend/src/lib/running-jobs.test.ts
+++ b/frontend/src/lib/running-jobs.test.ts
@@ -6,6 +6,7 @@ import {
completionToastCopy,
detectCompletedJobs,
type RunningJobItem,
+ rememberActive,
} from "./running-jobs";
describe("buildRunningJobs", () => {
@@ -313,3 +314,56 @@ describe("detectCompletedJobs", () => {
expect(completed).toHaveLength(0);
});
});
+
+it.each([
+ "finetuning",
+ "optimizer",
+ "eval",
+] as const)("does not infer %s completion from an absent list row", (kind) => {
+ const previous: RunningJobItem = {
+ id: "id",
+ key: "work",
+ kind,
+ startedAt: "",
+ status: "running",
+ title: "Work",
+ };
+ expect(detectCompletedJobs(new Map([[previous.key, previous]]), [], {})).toEqual([]);
+});
+
+it("does not declare a training group complete while a known member is absent", () => {
+ const previous: RunningJobItem = {
+ groupId: "g",
+ id: "one",
+ key: "ft:g",
+ kind: "finetuning",
+ memberIds: ["one", "two"],
+ startedAt: "",
+ status: "running",
+ title: "Work",
+ };
+ expect(
+ detectCompletedJobs(new Map([[previous.key, previous]]), [], {
+ finetuning: [{ groupId: "g", id: "one", status: "succeeded" }],
+ })
+ ).toEqual([]);
+});
+
+it("keeps a group member that left the polled page", () => {
+ const job = (memberIds: string[]) =>
+ ({
+ id: "f1",
+ key: "ft:g1",
+ kind: "finetuning",
+ memberIds,
+ status: "running",
+ }) as RunningJobItem;
+ const tracked = new Map<string, RunningJobItem>();
+ rememberActive(tracked, [job(["f1", "f2"])], []);
+ rememberActive(tracked, [job(["f1"])], []);
+ expect(tracked.get("ft:g1")?.memberIds).toEqual(["f1", "f2"]);
+ const done = detectCompletedJobs(tracked, [], {
+ finetuning: [{ groupId: "g1", id: "f1", name: "swift fox", status: "succeeded" }],
+ });
+ expect(done).toEqual([]);
+});
diff --git a/frontend/src/lib/running-jobs.ts b/frontend/src/lib/running-jobs.ts
index f47850ac..f2030d77 100644
--- a/frontend/src/lib/running-jobs.ts
+++ b/frontend/src/lib/running-jobs.ts
@@ -11,6 +11,7 @@ export interface RunningJobItem {
id: string;
/** FT monitor group; equals `id` for lone jobs. */
groupId?: string;
+ memberIds?: string[];
title: string;
status: string;
error?: string;
@@ -188,6 +189,7 @@ export function buildRunningJobs(
id: rep.id,
key: `ft:${gid}`,
kind: "finetuning",
+ memberIds: members.map((m) => m.id),
startedAt: startedAt || toIso(rep.startedAt ?? rep.createdAt),
status: activeOnly ? rep.status : foldFtGroupStatus(members),
title: ftGroupTitle(members),
@@ -271,33 +273,38 @@ export function detectCompletedJobs(
const members = (latest.finetuning ?? []).filter(
(j) => ftGroupId(j) === gid || j.id === prev.id
);
- if (members.some((j) => !isTerminalFinetuningStatus(j.status))) continue;
- const status = members.length > 0 ? foldFtGroupStatus(members) : "succeeded";
+ if (
+ !members.length ||
+ (prev.memberIds ?? [prev.id]).some((id) => !members.some((j) => j.id === id)) ||
+ members.some((j) => !isTerminalFinetuningStatus(j.status))
+ )
+ continue;
+ const status = foldFtGroupStatus(members);
completed.push({
...prev,
status,
- title: members.length > 0 ? ftGroupTitle(members) : prev.title,
+ title: ftGroupTitle(members),
});
continue;
}
if (prev.kind === "optimizer") {
const row = latest.optimizerExperiments?.find((e) => e.id === prev.id);
- if (row && !isTerminalOptimizerStatus(row.status)) continue;
+ if (!row || !isTerminalOptimizerStatus(row.status)) continue;
completed.push({
...prev,
- status: row ? foldOptimizerStatus(row.status) : "completed",
- title: row ? optimizerTitle(row) : prev.title,
+ status: foldOptimizerStatus(row.status),
+ title: optimizerTitle(row),
});
continue;
}
if (prev.kind === "eval") {
const row = latest.evalRuns?.find((j) => j.id === prev.id);
- if (row && !isTerminalEvalStatus(row.status)) continue;
+ if (!row || !isTerminalEvalStatus(row.status)) continue;
completed.push({
...prev,
- status: row?.status ?? "completed",
+ status: row.status,
title: row?.name?.trim() || prev.title,
});
}
@@ -320,3 +327,18 @@ export function completionToastCopy(job: RunningJobItem): { message: string; des
message: `${kind} ${ok}`,
};
}
+
+/** Tracks active jobs between polls. A group keeps every member it has shown,
+ * so a member that leaves the first page still gates its completion. */
+export function rememberActive(
+ previous: Map<string, RunningJobItem>,
+ current: RunningJobItem[],
+ completed: RunningJobItem[]
+) {
+ for (const job of current) {
+ const seen = previous.get(job.key)?.memberIds ?? [];
+ const memberIds = job.memberIds && [...new Set([...seen, ...job.memberIds])];
+ previous.set(job.key, { ...job, memberIds });
+ }
+ for (const job of completed) previous.delete(job.key);
+}
diff --git a/frontend/src/routes/_auth/evaluations.index.tsx b/frontend/src/routes/_auth/evaluations.index.tsx
index 9e162a5f..19c67888 100644
--- a/frontend/src/routes/_auth/evaluations.index.tsx
+++ b/frontend/src/routes/_auth/evaluations.index.tsx
@@ -115,6 +115,7 @@ function EvaluationsPage() {
<RunsTable
action={<CreateRunDialog key={projectId} projectId={projectId} />}
filters={search}
+ key={projectId}
onSearchChange={patchSearch}
page={page}
pageSize={pageSize}