Skip to content

The platform for continuously improving AI agents.

Carry the no-decision parts of Experiments v2 and its chat look to main (#382)

Freyam Mehta51e5448779fa
diff --git a/.agents/skills/backend-architecture/references/experiments.md b/.agents/skills/backend-architecture/references/experiments.md
index cddc6e23..66ec99b9 100644
--- a/.agents/skills/backend-architecture/references/experiments.md
+++ b/.agents/skills/backend-architecture/references/experiments.md
@@ -13,7 +13,7 @@ An experiment is a saved flow of stages with its own conversation. The Console,
- `runs.plan` resolves parameters and gives each stage an action: `reference` (an input stage), `decide` (a control stage), `reuse` (unchanged since the run named by `reuse_run`, by stage identity: kind, resolved settings and upstream identities) or `execute`. Its fingerprint pins `runs.start`: a changed plan is refused. A run's deadline is 24 hours unless set (1–168).
- A Model stage's candidate settings (`catalog.CANDIDATE`: system prompt, generation strategy, max steps, reasoning effort) ride on its model port: Evaluate passes them as the target's `params` and labels the run with the stage title; Qualify gives the system prompt to its participant as `instructions` and measures with purpose `final`.
-- A stage is one call to an MCP catalog tool, made in process for the run's starter (`stages.START`), then the records it started read through `get_job` until they end (`stages.FINISH`). Input and control stages decide at once. Variants, subflow and iterate run another experiment as child runs under their step. `ExperimentStep` holds each attempt's inputs, outputs, receipts and calls.
+- A stage is one call to an MCP catalog tool, made in process for the run's starter (`stages.START`), then the records it started read through `get_job` until they end (`stages.FINISH`). Input and control stages decide at once. Variants, subflow and iterate run another experiment as child runs under their step. `ExperimentStep` holds each attempt's inputs, outputs, receipts and calls; once it ends, its `report` (`failures.py`) names the tool, the record it ended on, its duration and, unless it completed, a failure class, whether a retry can succeed and the last Python exception of a failed program. The class is set where the failure is known, never parsed back from `error`.
- `runs.advance` (task `experiments.advance_run`, io queue) holds a cache lock, never a transaction across tool calls. It starts every stage whose inputs arrived, reads running ones, skips a branch a condition did not take, and ends the run `completed` or `unmet`. The `experiments.reconcile` beat task (control, 15 s) advances every active run not checked in 30 s: that is the polling interval and the recovery from a lost task.
- A stage's calls run as the `overmind experiment` client, credited to the experiment, never to a coding agent. A top-level run is one activity row from start to end.
- `stop` marks the run `stopping`; the next advance cancels each running stage's work through the cancel tool of its record's kind (`stages.CANCEL`) and names on the step what it could not stop. `retry` adds an attempt for each failed or cancelled stage.
@@ -21,7 +21,7 @@ An experiment is a saved flow of stages with its own conversation. The Console,
## The experiment's agent
- Its conversation is the experiment's `AssistantThread`; every conversation is one, and a dataset page has none. `records.dataset_links` gives each dataset the experiment that made it (a stage whose output version appeared during the stage) and those that read it; an experiment that pins a dataset blocks its delete. The brief (`describe.brief`) carries the flow, its problems and the newest runs; the experiment tools are in `tools.CATALOG_TOOLS`, so the assistant and an MCP client call the same tools.
-- When a top-level run ends, `operator.run_ended` queues a notice (`AssistantInput.origin=run`) as the run's starter, and the turn reads it as the platform's words. The agent starts at most `runs.AGENT_RUNS` runs (3) per person's message or trigger send, and while no person is in the loop none once a trigger's `max_spend_credits` is reached by `describe.spend` (the ledger rows charged to the experiment; workspace time is the project's and named as not attributed). A run the agent started stops the deployments it made when it ends, unless one became a capability's active model.
+- When a top-level run ends, `operator.run_ended` queues a notice (`AssistantInput.origin=run`) as the run's starter, with each failed stage's class, and the turn reads it as the platform's words. The agent starts at most `runs.AGENT_RUNS` runs (3) per person's message or trigger send, and while no person is in the loop none once a trigger's `max_spend_credits` is reached by `describe.spend` (the ledger rows charged to the experiment; workspace time is the project's and named as not attributed). A run the agent started stops the deployments it made when it ends, unless one became a capability's active model.
- A person's save (Console or MCP) marks the settings it set on each node as `protected`. The agent's save that changes one is refused (`ProtectedSettingError`, MCP `protected_setting`) and logged as a `proposal` event; `records.resolve_proposal` applies it as the person's own revision, or dismisses it.
- `Experiment.notes` holds the agent's notes, written with `revise_experiment` `notes` and shown read-only in the Console.
- Your system (`system` kind, `services/experiments/system.py`): the stage waits on a `system_outputs` receipt; `overmind run` reads `GET /api/experiment-steps/<id>/rows/` and posts `outputs/`, which imports the rows with a `_overmind_output` column into the step's own dataset (`uuid5(step, "outputs")`, so the input's active version stays; provenance: step, label, commit) and replaces the receipt with the import's run. The same outputs again replay that import, also after the stage moved on. A final holdout is refused. Evaluate scores it with a `recorded` target, whose `recorded_output` reads `_overmind_output`.
diff --git a/DESIGN.md b/DESIGN.md
index 24d7fc08..0f81f04c 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -377,7 +377,10 @@ card, dialog, sheet, section and empty-state headings use Geist Pixel.
genuine 700 cut. NeueBit sizes itself by hand because its caps are half its
declared size.
- **Prose** (400, inherits size, normal tracking): Markdown, chat and assistant
- messages, score reasoning, long descriptions, empty-state subcopy.
+ messages, score reasoning, long descriptions, empty-state subcopy. Chat replies
+ (`.chat-prose`) set 15px body text, 1.6 line height, 12px block gaps, 1.3em and
+ 1.15em first- and second-level headings, 0.86em code and tables, and a Copy
+ button on each code block.
### Named rules
@@ -533,8 +536,7 @@ a scale transform or hover lift.
## Shapes
One corner: `--radius`, 4px. `rounded-xs`, `rounded-sm` and `rounded-md` all
-resolve to it. Joined surfaces keep square edges at the seam, such as the
-workspace panel under its tab strip.
+resolve to it. Joined surfaces keep square edges at the seam.
The pixel logic extends past radius. The sidebar's sub-item connector is drawn as
a stepped staircase in SVG mask data rather than a smooth elbow. Icons are
@@ -655,10 +657,17 @@ tones get away with a 1.65:1 border because their hue does the work.
tab. Home is pinned first and cannot close; "New experiment" opens another Home
chat tab that keeps its draft. Tabs reorder by drag or Alt+Arrow and restore per
user and project for the browser session. A running job opens its own tab,
- outlined until viewed.
+ outlined until viewed. All tabs are detached, equally sized chips: the selected
+ tab inverts to a foreground background with dark text and icons, and the
+ workspace panel below keeps its full border. One sidebar icon opens and closes
+ the sidebar.
- **Experiment canvas:** A read-only graph of stage cards laid out left to right;
a card shows its inputs, settings and state, its settings and results open as
- dialogs over the canvas, and the conversation is the assistant dock at its foot.
+ dialogs over the canvas, and the conversation sits in the chat sidebar to its
+ right (320 to 720px, resizable, black, toggled by the inverted button at the
+ canvas's top right). In the sidebar, messages are 14px at 1.45, headings 15px,
+ code and tables 13px; the composer is a bordered field on the background tone
+ with an inverted send button.
- **Scroll fades:** Scroll areas fade at an edge that has more content
(`scroll-fade-y`; `scroll-fade-bottom` under a sticky table header).
diff --git a/frontend/public/thinking-eye.gif b/frontend/public/thinking-eye.gif
new file mode 100644
index 00000000..2963ec68
Binary files /dev/null and b/frontend/public/thinking-eye.gif differ
diff --git a/frontend/src/components/app-sidebar.tsx b/frontend/src/components/app-sidebar.tsx
index 5450eab7..cfec5a2c 100644
--- a/frontend/src/components/app-sidebar.tsx
+++ b/frontend/src/components/app-sidebar.tsx
@@ -189,7 +189,7 @@ export function AppSidebar({ onSearchOpen }: { onSearchOpen: () => void }) {
src={overmindEyeIcon}
/>
<span className={cn("absolute inset-0 grid place-items-center", styles.toggle)}>
- {expanded ? <Icon.panelLeftClose /> : <Icon.panelLeftOpen />}
+ <Icon.sidebar />
</span>
</Button>
</TooltipTrigger>
diff --git a/frontend/src/components/assistant/approval-card.test.tsx b/frontend/src/components/assistant/approval-card.test.tsx
new file mode 100644
index 00000000..36e2a355
--- /dev/null
+++ b/frontend/src/components/assistant/approval-card.test.tsx
@@ -0,0 +1,44 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import { ApprovalCard } from "./approval-card";
+
+afterEach(cleanup);
+
+function show(onDecide = vi.fn(() => Promise.resolve())) {
+ render(
+ <ApprovalCard
+ fields={[{ label: "Train · epochs", value: "3 → 5" }]}
+ onDecide={onDecide}
+ title="Change settings"
+ />
+ );
+ return onDecide;
+}
+
+it("approves with no reason", () => {
+ const onDecide = show();
+ fireEvent.click(screen.getByRole("button", { name: "Approve" }));
+ expect(onDecide).toHaveBeenCalledWith(true, "");
+});
+
+it("asks what to do instead before it denies", () => {
+ const onDecide = show();
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ expect(onDecide).not.toHaveBeenCalled();
+ fireEvent.change(screen.getByRole("textbox", { name: "Reason for denying" }), {
+ target: { value: " Keep three epochs. " },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ expect(onDecide).toHaveBeenCalledWith(false, "Keep three epochs.");
+});
+
+it("says so when the decision did not reach the server", async () => {
+ show(vi.fn(() => Promise.reject(new Error("offline"))));
+ fireEvent.click(screen.getByRole("button", { name: "Approve" }));
+ await waitFor(() =>
+ expect(screen.getByRole("alert").textContent).toBe("Couldn't send. Try again.")
+ );
+});
diff --git a/frontend/src/components/assistant/approval-card.tsx b/frontend/src/components/assistant/approval-card.tsx
new file mode 100644
index 00000000..c81f5442
--- /dev/null
+++ b/frontend/src/components/assistant/approval-card.tsx
@@ -0,0 +1,168 @@
+import { type ReactNode, useId, useState } from "react";
+
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icons";
+import { Input } from "@/components/ui/input";
+import { cn } from "@/lib/utils";
+
+export interface ApprovalField {
+ label: string;
+ value: string;
+}
+
+const SHOWN = 4;
+
+/** Something the agent asks a person to allow: what it is, the facts it rests on, and
+ * Approve or Deny with what to do instead. */
+export function ApprovalCard({
+ title,
+ detail,
+ fields,
+ icon,
+ disabled = false,
+ onDecide,
+}: {
+ title: string;
+ detail?: string;
+ fields: ApprovalField[];
+ icon?: ReactNode;
+ disabled?: boolean;
+ onDecide: (approved: boolean, reason: string) => Promise<unknown>;
+}) {
+ const titleId = useId();
+ const [all, setAll] = useState(false);
+ const [denying, setDenying] = useState(false);
+ const [reason, setReason] = useState("");
+ const [sending, setSending] = useState(false);
+ const [failed, setFailed] = useState(false);
+ const locked = disabled || sending;
+ const decide = async (approved: boolean) => {
+ if (locked) return;
+ setSending(true);
+ setFailed(false);
+ try {
+ await onDecide(approved, approved ? "" : reason.trim());
+ } catch {
+ setFailed(true);
+ setDenying(false);
+ } finally {
+ setSending(false);
+ }
+ };
+ const shown = all ? fields : fields.slice(0, SHOWN);
+ const more = fields.length - SHOWN;
+ return (
+ <section
+ aria-labelledby={titleId}
+ className="relative flex w-full max-w-md min-w-0 animate-in flex-col rounded-md border border-border bg-card p-2.5 text-foreground duration-300 ease-out fade-in-0 slide-in-from-bottom-2 motion-reduce:animate-none"
+ data-slot="approval-card"
+ >
+ <div className="flex min-w-0 items-start gap-2">
+ <span
+ className={cn(
+ "inline-flex size-6 flex-none items-center justify-center rounded-md",
+ icon ? "bg-muted text-foreground" : "bg-warning/10 text-warning"
+ )}
+ >
+ {icon ?? <Icon.lock aria-hidden className="size-3.5" />}
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col pt-1">
+ <span className="truncate text-sm leading-4 font-medium" id={titleId}>
+ {title}
+ </span>
+ {detail && (
+ <span className="line-clamp-2 pt-0.5 text-xs leading-4 text-pretty text-muted-foreground">
+ {detail}
+ </span>
+ )}
+ </div>
+ </div>
+ {fields.length > 0 && (
+ <div className="pt-2">
+ <div className="flex min-w-0 flex-col overflow-hidden rounded-md bg-muted px-2.5 py-2 text-xs leading-4">
+ <dl className="m-0 grid min-w-0 grid-cols-[auto_minmax(0,1fr)] gap-x-4 gap-y-1.5">
+ {shown.map((field) => (
+ <div className="col-span-2 grid grid-cols-subgrid" key={field.label}>
+ <dt className="max-w-28 truncate text-muted-foreground" title={field.label}>
+ {field.label}
+ </dt>
+ <dd
+ className={cn(
+ "m-0 min-w-0 break-words whitespace-pre-wrap",
+ !all && "line-clamp-3"
+ )}
+ >
+ {field.value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ {more > 0 && (
+ <button
+ aria-expanded={all}
+ className="-mx-2.5 mt-2 -mb-2 flex cursor-pointer items-center justify-between gap-2 border-t border-border/70 px-2.5 py-1.5 text-start text-xs leading-4 text-muted-foreground outline-none transition-colors hover:bg-accent/50 hover:text-foreground focus-visible:bg-accent/50 focus-visible:text-foreground motion-reduce:transition-none"
+ onClick={() => setAll(!all)}
+ type="button"
+ >
+ {all ? "Show less" : `${more} more`}
+ <Icon.chevronDown
+ aria-hidden
+ className={cn(
+ "size-3 flex-none transition-[rotate] duration-200 motion-reduce:transition-none",
+ all && "rotate-180"
+ )}
+ />
+ </button>
+ )}
+ </div>
+ </div>
+ )}
+ <div className="flex min-h-7 min-w-0 flex-wrap items-center justify-end gap-x-2 gap-y-1.5 pt-2">
+ {failed && (
+ <span className="me-auto text-xs leading-4 text-error" role="alert">
+ Couldn't send. Try again.
+ </span>
+ )}
+ {denying ? (
+ <form
+ className="flex min-w-0 flex-1 basis-56 items-center gap-1.5"
+ onSubmit={(event) => {
+ event.preventDefault();
+ void decide(false);
+ }}
+ >
+ <Input
+ aria-label="Reason for denying"
+ autoComplete="off"
+ autoFocus
+ className="min-w-0 flex-1"
+ disabled={locked}
+ onChange={(event) => setReason(event.target.value)}
+ placeholder="What should it do instead?"
+ size="xs"
+ value={reason}
+ />
+ <Button disabled={locked} size="xs" type="submit">
+ Deny
+ </Button>
+ </form>
+ ) : (
+ <div className="flex flex-none items-center gap-1.5">
+ <Button
+ disabled={locked}
+ onClick={() => setDenying(true)}
+ size="xs"
+ type="button"
+ variant="secondary"
+ >
+ Deny
+ </Button>
+ <Button disabled={locked} onClick={() => void decide(true)} size="xs" type="button">
+ Approve
+ </Button>
+ </div>
+ )}
+ </div>
+ </section>
+ );
+}
diff --git a/frontend/src/components/assistant/assistant-chat.tsx b/frontend/src/components/assistant/assistant-chat.tsx
new file mode 100644
index 00000000..dc938c0a
--- /dev/null
+++ b/frontend/src/components/assistant/assistant-chat.tsx
@@ -0,0 +1,333 @@
+import { useCallback, useMemo, useRef, useState } from "react";
+
+import { useNavigate } from "@tanstack/react-router";
+
+import apiClient from "@/client";
+import { Alert } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icons";
+import { Spinner } from "@/components/ui/spinner";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import type { useAssistantThread } from "@/hooks/use-assistant-thread";
+import { useGuestGate } from "@/hooks/use-guest-gate";
+import { type MentionRange, serializeMentions } from "@/lib/entity-mentions";
+import { errorMessage, notify } from "@/lib/notify";
+import type { Cell } from "@/openapi";
+import { AssistantQueue } from "./assistant-queue";
+import { answerKey, type ResultActions } from "./assistant-result";
+import { AssistantTranscript, runningLabel } from "./assistant-transcript";
+import { useGhostCompletion } from "./ghost-completion";
+import { type LocalMention, MentionTextarea } from "./mention-textarea";
+import { MessageLimit } from "./message-limit";
+import {
+ type AssistantEvent,
+ type Interaction,
+ MESSAGE_CHARS,
+ type QuestionNode,
+ type ResultNode,
+} from "./types";
+
+function* nodesOf(node: ResultNode): Generator<ResultNode> {
+ yield node;
+ if ("children" in node) for (const child of node.children) yield* nodesOf(child);
+ if (node.type === "Tabs")
+ for (const tab of node.tabs) for (const child of tab.children) yield* nodesOf(child);
+}
+
+/** The newest unanswered question with one text field: the composer can answer it. */
+function openQuestion(events: AssistantEvent[], answered: ReadonlySet<string>) {
+ for (const event of [...events].reverse()) {
+ if (event.kind !== "tool_result" || !event.presentation) continue;
+ const call = event.payload.call;
+ for (const node of nodesOf(event.presentation.root))
+ if (
+ node.type === "Question" &&
+ node.fields.length === 1 &&
+ node.fields[0].type === "text" &&
+ !answered.has(answerKey(call, node.id))
+ )
+ return { call, node: node as QuestionNode };
+ return null;
+ }
+ return null;
+}
+
+function statusOf(assistant: ReturnType<typeof useAssistantThread>, stopping: boolean) {
+ if (stopping) return "Stopping";
+ // A queued message no turn took yet: no step runs.
+ if (assistant.thread?.state === "idle") return "Queued";
+ return runningLabel(assistant.events) ?? assistant.draft?.steps.at(-1) ?? "Thinking";
+}
+
+/** The draft with the added passage after it, unless that makes it too long. */
+export function appendDraft(current: string, addition: string) {
+ const combined = current.trim() ? `${current.trimEnd()}\n\n${addition}` : addition;
+ return combined.length <= MESSAGE_CHARS ? combined : null;
+}
+
+const NO_CELLS: Cell[] = [];
+const INPUT =
+ "chat-composer-input block w-full resize-none border-0 bg-transparent px-1 py-1.5 outline-none placeholder:text-muted-foreground";
+
+/** A record's conversation in the chat sidebar: the thread, then the composer. */
+export function AssistantChat({
+ assistant,
+ projectId,
+ cells = NO_CELLS,
+ nodes,
+ onNode,
+ suggestions = [],
+ label = "Chat",
+ placeholder = "Ask about the experiment or describe a change…",
+ readOnly,
+}: {
+ assistant: ReturnType<typeof useAssistantThread>;
+ projectId: string;
+ cells?: Cell[];
+ /** Records on the page the composer can mention with `@`. */
+ nodes?: LocalMention[];
+ /** Shows a mentioned record on the page. */
+ onNode?: (id: string) => void;
+ /** Endings the composer offers for the draft, the first for an empty one. */
+ suggestions?: string[];
+ label?: string;
+ placeholder?: string;
+ /** Why the conversation takes no message now. */
+ readOnly?: string;
+}) {
+ const navigate = useNavigate();
+ const guard = useGuestGate();
+ const textarea = useRef<HTMLTextAreaElement>(null);
+ const [text, setText] = useState("");
+ const [references, setReferences] = useState<MentionRange[]>([]);
+ const [sent, setSent] = useState(0);
+ // A retry of the same message is the same request; a changed message is a new one.
+ const request = useRef<{ key: string; body: string } | null>(null);
+
+ const { thread, events, send, stop } = assistant;
+ const queue = thread?.queue ?? [];
+ // Members share the conversation: a teammate's message carries their name.
+ const participants = thread?.participants;
+ const teammates = useMemo(
+ () =>
+ new Map((participants ?? []).filter((who) => !who.me).map((who) => [who.user, who.email])),
+ [participants]
+ );
+ const active = (thread?.state ?? "idle") !== "idle" || queue.length > 0;
+ const stopping = !!thread?.stopRequested || stop.isPending;
+ const answered = useMemo(() => {
+ const keys = new Set<string>();
+ const add = (given: Interaction | null | undefined) =>
+ given && keys.add(answerKey(given.call, given.id));
+ for (const event of events) if (event.kind === "user") add(event.payload.interaction);
+ for (const message of queue) add(message.interaction);
+ return keys;
+ }, [events, queue]);
+ const question = useMemo(() => openQuestion(events, answered), [events, answered]);
+ const answerHint = question?.node.fields[0].placeholder;
+ const ghost = useGhostCompletion(text, setText, answerHint ? [answerHint] : suggestions);
+
+ const deliver = (
+ message: string,
+ interaction?: Interaction,
+ restore = false,
+ onSent?: () => void
+ ) => {
+ if (readOnly) return;
+ const body = { cells: [], interaction, text: message };
+ const signature = JSON.stringify(body);
+ if (request.current?.body !== signature)
+ request.current = { body: signature, key: crypto.randomUUID() };
+ setSent((count) => count + 1);
+ send.mutate(
+ { ...body, requestKey: request.current.key },
+ {
+ // Only an untouched composer gets its text back.
+ onError: () => restore && setText((current) => current || message),
+ onSuccess: () => {
+ request.current = null;
+ onSent?.();
+ },
+ }
+ );
+ };
+ const submit = guard(() => {
+ const message = serializeMentions(text, references).trim();
+ if (!message || send.isPending || stopping || readOnly) return;
+ setText("");
+ setReferences([]);
+ const field = question?.node.fields[0].name;
+ deliver(
+ message,
+ question && field
+ ? { call: question.call, id: question.node.id, values: { [field]: message } }
+ : undefined,
+ true
+ );
+ });
+ const draft = useCallback((addition: string) => {
+ setText((current) => {
+ const next = appendDraft(current, addition);
+ if (next === null) {
+ notify.info("The draft is too long to add this");
+ return current;
+ }
+ return next;
+ });
+ requestAnimationFrame(() => {
+ const field = textarea.current;
+ field?.focus();
+ field?.setSelectionRange(field.value.length, field.value.length);
+ });
+ }, []);
+ // The transcript re-renders when its actions change: these read the newest handlers
+ // through a ref, so a keystroke in the composer changes nothing it sees.
+ const handlers = useRef({ deliver, guard });
+ handlers.current = { deliver, guard };
+ const threadId = thread?.id;
+ const sending = send.isPending;
+ // Its own identity: an image loads again whenever this function changes.
+ const loadImage = useCallback(
+ (name: string) =>
+ apiClient.assistantThreads.assistantThreadsImagesRetrieve({ id: threadId!, name }),
+ [threadId]
+ );
+ const actions: ResultActions = useMemo(
+ () => ({
+ answered,
+ loadImage,
+ onAnswer: (message, interaction, onSent) =>
+ handlers.current.guard(() =>
+ handlers.current.deliver(message, interaction, false, onSent)
+ )(),
+ onCell: (cell, dataset) =>
+ void navigate({
+ params: { datasetId: dataset },
+ search: { cell, projectId },
+ to: "/datasets/$datasetId",
+ }),
+ onTrain: (dataset) =>
+ void navigate({ search: { datasetId: dataset, projectId, train: true }, to: "/training" }),
+ sending,
+ }),
+ [answered, loadImage, navigate, projectId, sending]
+ );
+ const sendHint =
+ readOnly ??
+ (stopping ? "Wait for the run to stop" : active ? "Queue a follow-up" : "Send message");
+
+ return (
+ <section aria-label={label} className="chat-surface flex min-h-0 flex-1 flex-col">
+ <AssistantTranscript
+ actions={actions}
+ active={active}
+ activity={active && !assistant.draft ? statusOf(assistant, stopping) : undefined}
+ cells={cells}
+ draft={assistant.draft}
+ events={events}
+ onDraft={readOnly ? undefined : draft}
+ onNode={onNode}
+ onSelectCell={() => {}}
+ sent={sent}
+ teammates={teammates}
+ />
+ {assistant.error && (
+ <Alert className="mx-3 w-auto text-xs">
+ {errorMessage(assistant.error, "The conversation is not available.")}
+ </Alert>
+ )}
+ <div className="chat-composer-stack flex min-w-0 shrink-0 flex-col">
+ {sending && (
+ <div className="flex min-w-0 items-center gap-1.5 px-2 py-1 text-xs text-muted-foreground">
+ <Spinner size="sm" />
+ <span className="truncate" role="status">
+ Sending message
+ </span>
+ </div>
+ )}
+ <AssistantQueue
+ // A change in flight holds the revision the next one needs.
+ disabled={stopping || assistant.changeQueued.isPending}
+ messages={queue}
+ onChange={guard((change) => assistant.changeQueued.mutate(change))}
+ teammates={teammates}
+ />
+ <form
+ aria-label="Message the assistant"
+ className="chat-composer flex min-w-0 flex-col"
+ onSubmit={(event) => {
+ event.preventDefault();
+ submit();
+ }}
+ >
+ <div className="chat-composer-field relative min-h-0">
+ {ghost.hint}
+ <MentionTextarea
+ {...ghost.inputProps}
+ aria-label="Message"
+ className={INPUT}
+ disabled={!!readOnly}
+ local={nodes}
+ maxLength={MESSAGE_CHARS}
+ onKeyDown={(event) => {
+ const plain = !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey;
+ if (event.nativeEvent.isComposing || !plain || event.key !== "Enter") return;
+ event.preventDefault();
+ submit();
+ }}
+ onReferencesChange={setReferences}
+ onValueChange={setText}
+ overlay={ghost.layer(INPUT)}
+ placeholder={
+ ghost.suffix
+ ? ""
+ : readOnly || answerHint || (active ? "Queue a follow-up…" : placeholder)
+ }
+ projectId={projectId}
+ ref={textarea}
+ references={references}
+ rows={1}
+ value={text}
+ />
+ {text.length >= MESSAGE_CHARS && <MessageLimit />}
+ </div>
+ <div className="chat-composer-footer flex min-w-0 items-center">
+ {active && thread && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label={stopping ? "Stopping…" : "Stop"}
+ disabled={stopping}
+ onClick={guard(() => stop.mutate())}
+ size="icon-xs"
+ type="button"
+ variant="ghost"
+ >
+ {stopping ? <Spinner size="sm" /> : <Icon.stop />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Stop run</TooltipContent>
+ </Tooltip>
+ )}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>
+ <Button
+ aria-label={active ? "Queue" : "Send"}
+ disabled={sending || stopping || !!readOnly || !text.trim()}
+ size="icon-sm"
+ type="submit"
+ variant="send"
+ >
+ {sending ? <Spinner size="sm" /> : <Icon.send />}
+ </Button>
+ </span>
+ </TooltipTrigger>
+ <TooltipContent>{sendHint}</TooltipContent>
+ </Tooltip>
+ </div>
+ </form>
+ </div>
+ </section>
+ );
+}
diff --git a/frontend/src/components/assistant/assistant-dock.tsx b/frontend/src/components/assistant/assistant-dock.tsx
deleted file mode 100644
index 7cfb591e..00000000
--- a/frontend/src/components/assistant/assistant-dock.tsx
+++ /dev/null
@@ -1,457 +0,0 @@
-import { type CSSProperties, useCallback, useId, useMemo, useRef, useState } from "react";
-import { flushSync } from "react-dom";
-
-import { useNavigate } from "@tanstack/react-router";
-
-import apiClient from "@/client";
-import { Alert } from "@/components/ui/alert";
-import { Button } from "@/components/ui/button";
-import { Card } from "@/components/ui/card";
-import { Icon } from "@/components/ui/icons";
-import { Spinner } from "@/components/ui/spinner";
-import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import type { useAssistantThread } from "@/hooks/use-assistant-thread";
-import { useGuestGate } from "@/hooks/use-guest-gate";
-import { usePersistedState } from "@/hooks/use-persisted-state";
-import { errorMessage } from "@/lib/notify";
-import type { Cell } from "@/openapi";
-import { AssistantQueue } from "./assistant-queue";
-import { answerKey, type ResultActions } from "./assistant-result";
-import { AssistantTranscript, runningLabel } from "./assistant-transcript";
-import { MessageLimit } from "./message-limit";
-import { PANEL_WIDTH, PanelResize } from "./panel-resize";
-import {
- type AssistantEvent,
- type Interaction,
- MESSAGE_CHARS,
- type QuestionNode,
- type ResultNode,
-} from "./types";
-
-const PHONE = "(max-width: 767px)";
-
-function* nodesOf(node: ResultNode): Generator<ResultNode> {
- yield node;
- if ("children" in node) for (const child of node.children) yield* nodesOf(child);
- if (node.type === "Tabs")
- for (const tab of node.tabs) for (const child of tab.children) yield* nodesOf(child);
-}
-
-/** The newest unanswered question with one text field: the composer can answer it. */
-function openQuestion(events: AssistantEvent[], answered: ReadonlySet<string>) {
- for (const event of [...events].reverse()) {
- if (event.kind !== "tool_result" || !event.presentation) continue;
- const call = event.payload.call;
- for (const node of nodesOf(event.presentation.root))
- if (
- node.type === "Question" &&
- node.fields.length === 1 &&
- node.fields[0].type === "text" &&
- !answered.has(answerKey(call, node.id))
- )
- return { call, node: node as QuestionNode };
- return null;
- }
- return null;
-}
-
-function statusOf(
- assistant: ReturnType<typeof useAssistantThread>,
- active: boolean,
- stopping: boolean,
- idle: string
-) {
- if (stopping) return "Stopping";
- const last = assistant.events.at(-1);
- if (active) {
- // A queued message no turn took yet: no step runs.
- if (assistant.thread?.state === "idle") return "Queued";
- return runningLabel(assistant.events) ?? assistant.draft?.steps.at(-1) ?? "Working";
- }
- if (last?.kind === "status")
- return {
- failed: "Reply failed",
- interrupted: "Interrupted",
- resumed: "Complete",
- stopped: "Stopped",
- }[last.payload.state];
- return last ? "Complete" : idle;
-}
-
-const NO_CELLS: Cell[] = [];
-
-export function AssistantDock({
- assistant,
- projectId,
- datasetId,
- cells = NO_CELLS,
- selectedCell = null,
- onSelectCell,
- label = "Assistant chat",
- idle = "Ask about this data",
- placeholder = "Ask about the data or describe a change…",
- readOnly,
-}: {
- assistant: ReturnType<typeof useAssistantThread>;
- projectId: string;
- /** The dataset the conversation is about; an experiment's conversation has none. */
- datasetId?: string;
- cells?: Cell[];
- selectedCell?: string | null;
- onSelectCell?: (id: string) => void;
- label?: string;
- /** The status line before the first message. */
- idle?: string;
- placeholder?: string;
- /** Why the conversation takes no message now. */
- readOnly?: string;
-}) {
- const navigate = useNavigate();
- const guard = useGuestGate();
- const panelId = useId();
- const bodyId = useId();
- const textarea = useRef<HTMLTextAreaElement>(null);
- const [text, setText] = useState("");
- const [expanded, setExpanded] = useState(false);
- const [sent, setSent] = useState(0);
- const [panel, setPanel] = useState(false);
- const [keptWidth, keepWidth] = usePersistedState("assistant:panelWidth", PANEL_WIDTH.default);
- const [draggedWidth, setDraggedWidth] = useState<number | null>(null);
- // A retry of the same message is the same request; a changed message is a new one.
- const request = useRef<{ key: string; body: string } | null>(null);
-
- const { thread, events, send, stop } = assistant;
- const queue = thread?.queue ?? [];
- // Members share the conversation: a teammate's message carries their name.
- const participants = thread?.participants;
- const teammates = useMemo(
- () =>
- new Map((participants ?? []).filter((who) => !who.me).map((who) => [who.user, who.email])),
- [participants]
- );
- const active = (thread?.state ?? "idle") !== "idle" || queue.length > 0;
- const stopping = !!thread?.stopRequested || stop.isPending;
- const selected = cells.find((cell) => cell.id === selectedCell);
- const answered = useMemo(() => {
- const keys = new Set<string>();
- const add = (given: Interaction | null | undefined) =>
- given && keys.add(answerKey(given.call, given.id));
- for (const event of events) if (event.kind === "user") add(event.payload.interaction);
- for (const message of queue) add(message.interaction);
- return keys;
- }, [events, queue]);
- const question = useMemo(() => openQuestion(events, answered), [events, answered]);
- const status = statusOf(assistant, active, stopping, idle);
-
- const collapse = () => {
- setPanel(false);
- setDraggedWidth(null);
- setExpanded(false);
- textarea.current?.blur();
- };
- const deliver = (
- message: string,
- interaction?: Interaction,
- restore = false,
- onSent?: () => void
- ) => {
- if (readOnly) return;
- const body = { cells: selected ? [selected.id] : [], interaction, text: message };
- const signature = JSON.stringify(body);
- if (request.current?.body !== signature)
- request.current = { body: signature, key: crypto.randomUUID() };
- send.mutate(
- { ...body, requestKey: request.current.key },
- {
- // Only an untouched composer gets its text back.
- onError: () => restore && setText((current) => current || message),
- onSuccess: () => {
- request.current = null;
- setSent((count) => count + 1);
- onSent?.();
- setPanel(true);
- setExpanded(true);
- },
- }
- );
- };
- const submit = guard(() => {
- const message = text.trim();
- if (!message || send.isPending || stopping || readOnly) return;
- setText("");
- const field = question?.node.fields[0].name;
- deliver(
- message,
- question && field
- ? { call: question.call, id: question.node.id, values: { [field]: message } }
- : undefined,
- true
- );
- });
- // The transcript re-renders when its actions change: these read the newest handlers
- // through a ref, so a keystroke in the composer changes nothing it sees.
- const handlers = useRef({ collapse, deliver, guard });
- handlers.current = { collapse, deliver, guard };
- const threadId = thread?.id;
- const sending = send.isPending;
- // Its own identity: an image loads again whenever this function changes.
- const loadImage = useCallback(
- (name: string) =>
- apiClient.assistantThreads.assistantThreadsImagesRetrieve({ id: threadId!, name }),
- [threadId]
- );
- const actions: ResultActions = useMemo(
- () => ({
- answered,
- loadImage,
- onAnswer: (message, interaction, onSent) =>
- handlers.current.guard(() =>
- handlers.current.deliver(message, interaction, false, onSent)
- )(),
- onCell: (cell, dataset) => {
- if (onSelectCell && (dataset === datasetId || cells.some((item) => item.id === cell))) {
- if (window.matchMedia(PHONE).matches) handlers.current.collapse();
- onSelectCell(cell);
- } else
- void navigate({
- params: { datasetId: dataset },
- search: { cell, projectId },
- to: "/datasets/$datasetId",
- });
- },
- onTrain: (dataset) =>
- void navigate({ search: { datasetId: dataset, projectId, train: true }, to: "/training" }),
- sending,
- }),
- [answered, cells, datasetId, loadImage, navigate, onSelectCell, projectId, sending]
- );
- const sendHint =
- readOnly ?? (stopping ? "Stopping" : active ? "Queue a follow-up" : "Send message");
-
- return (
- <Card
- aria-label={label}
- className="assistant-surface assistant-dock absolute bottom-3 z-20 flex min-h-0 flex-col gap-2 overflow-hidden bg-muted p-1.5"
- data-expanded={expanded}
- data-panel={panel}
- data-resizing={draggedWidth !== null}
- id={panelId}
- onBlurCapture={(event) => {
- if (
- !panel &&
- !event.currentTarget.contains(event.relatedTarget) &&
- !event.currentTarget.matches(":hover")
- )
- setExpanded(false);
- }}
- onFocusCapture={() => setExpanded(true)}
- onKeyDown={(event) => {
- // React sends keys from portaled menus here too, and a field's own Escape is not ours.
- const target = event.target as HTMLElement;
- const field = target !== textarea.current && target.matches("input, textarea, select");
- if (event.key !== "Escape" || field || !event.currentTarget.contains(target)) return;
- event.preventDefault();
- collapse();
- }}
- onMouseEnter={() => setExpanded(true)}
- onMouseLeave={(event) => {
- if (!panel && !event.currentTarget.contains(document.activeElement)) setExpanded(false);
- }}
- role="region"
- style={{ "--assistant-panel-width": `${draggedWidth ?? keptWidth}px` } as CSSProperties}
- >
- {panel && (
- <AssistantTranscript
- actions={actions}
- active={active}
- activity={active && !assistant.draft ? status : undefined}
- cells={cells}
- draft={assistant.draft}
- events={events}
- onSelectCell={(id) => {
- if (window.matchMedia(PHONE).matches) collapse();
- onSelectCell?.(id);
- }}
- sent={sent}
- teammates={teammates}
- />
- )}
- {expanded && assistant.error && (
- <Alert className="w-auto text-xs">
- {errorMessage(assistant.error, "The conversation is not available.")}
- </Alert>
- )}
- <div className="assistant-composer-stack flex min-w-0 shrink-0 flex-col gap-1">
- {expanded && (
- <AssistantQueue
- // A change in flight holds the revision the next one needs.
- disabled={stopping || assistant.changeQueued.isPending}
- messages={queue}
- onChange={guard((change) => assistant.changeQueued.mutate(change))}
- teammates={teammates}
- />
- )}
- <form
- aria-label="Message the assistant"
- className="assistant-chat-inner shrink-0 overflow-hidden border border-border bg-popover"
- onSubmit={(event) => {
- event.preventDefault();
- submit();
- }}
- >
- <span aria-hidden="true" className="assistant-prompt-mark">
- &gt;
- </span>
- <div className="assistant-dock-body" id={bodyId} inert={!expanded}>
- <div className="min-h-0 overflow-hidden">
- <textarea
- aria-label="Message"
- className="assistant-chat-input block max-h-24 min-h-10 w-full resize-none border-0 bg-transparent text-xs leading-4 outline-none"
- maxLength={MESSAGE_CHARS}
- onChange={(event) => setText(event.target.value)}
- onKeyDown={(event) => {
- const plain =
- !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey;
- if (event.nativeEvent.isComposing || !plain) return;
- const suggestion = question?.node.fields[0].placeholder;
- if (event.key === "Tab" && suggestion && !text) {
- event.preventDefault();
- setText(suggestion);
- }
- if (event.key === "Enter") {
- event.preventDefault();
- submit();
- }
- }}
- placeholder={
- question?.node.fields[0].placeholder ||
- (active ? "Queue a follow-up…" : placeholder)
- }
- ref={textarea}
- value={text}
- />
- {text.length >= MESSAGE_CHARS && <MessageLimit />}
- </div>
- </div>
- <div className="assistant-dock-footer flex min-w-0 items-center gap-2">
- {expanded ? (
- <>
- {panel && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- aria-label="Close full conversation"
- onClick={collapse}
- size="icon-xs"
- type="button"
- variant="ghost"
- >
- <Icon.collapse />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Minimize conversation</TooltipContent>
- </Tooltip>
- )}
- <div className="min-w-0 flex-1">
- {selected && (
- <Button
- className="max-w-full truncate px-0 text-xs text-muted-foreground no-underline hover:text-foreground"
- onClick={() => onSelectCell?.(selected.id)}
- size="xs"
- type="button"
- variant="link"
- >
- <Icon.dataset />
- {selected.title}
- </Button>
- )}
- </div>
- {active && thread && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- aria-label={stopping ? "Stopping…" : "Stop"}
- disabled={stopping}
- onClick={guard(() => stop.mutate())}
- size="icon-xs"
- type="button"
- variant="ghost"
- >
- {stopping ? <Spinner size="sm" /> : <Icon.stop />}
- </Button>
- </TooltipTrigger>
- <TooltipContent>Stop run</TooltipContent>
- </Tooltip>
- )}
- <Tooltip>
- <TooltipTrigger asChild>
- <span>
- <Button
- aria-label={active ? "Queue" : "Send"}
- className="px-1 no-underline"
- disabled={send.isPending || stopping || !!readOnly}
- size="xs"
- type="submit"
- variant="link"
- >
- {send.isPending ? <Spinner size="sm" /> : <Icon.send />}
- {!active && "Send"}
- </Button>
- </span>
- </TooltipTrigger>
- <TooltipContent>{sendHint}</TooltipContent>
- </Tooltip>
- </>
- ) : (
- <Button
- aria-controls={bodyId}
- aria-expanded={false}
- aria-label={`Expand ${label.toLowerCase()}`}
- className="min-w-0 flex-1 justify-start border-0 bg-transparent text-muted-foreground"
- onClick={() => {
- // The field is inert until the body is expanded in the DOM.
- flushSync(() => setExpanded(true));
- textarea.current?.focus();
- }}
- size="xs"
- type="button"
- variant="outline"
- >
- <span className="min-w-0 flex-1 truncate text-left" title={status}>
- {status}
- </span>
- </Button>
- )}
- {!panel && (
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- aria-label="Open full conversation"
- onClick={() => {
- setPanel(true);
- setExpanded(true);
- }}
- size="icon-xs"
- type="button"
- variant="ghost"
- >
- <Icon.expand />
- </Button>
- </TooltipTrigger>
- <TooltipContent>Open conversation</TooltipContent>
- </Tooltip>
- )}
- </div>
- </form>
- </div>
- {panel && (
- <PanelResize
- onCommit={keepWidth}
- onDrag={setDraggedWidth}
- panelId={panelId}
- width={draggedWidth ?? keptWidth}
- />
- )}
- </Card>
- );
-}
diff --git a/frontend/src/components/assistant/assistant-transcript.test.tsx b/frontend/src/components/assistant/assistant-transcript.test.tsx
new file mode 100644
index 00000000..3a472023
--- /dev/null
+++ b/frontend/src/components/assistant/assistant-transcript.test.tsx
@@ -0,0 +1,74 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, expect, it, vi } from "vitest";
+
+import { TooltipProvider } from "@/components/ui/tooltip";
+import type { ResultActions } from "./assistant-result";
+import { AssistantTranscript } from "./assistant-transcript";
+import type { AssistantEvent } from "./types";
+
+vi.mock("@tanstack/react-router", () => ({ useRouter: () => ({ history: { push: vi.fn() } }) }));
+
+beforeEach(() => {
+ vi.stubGlobal(
+ "ResizeObserver",
+ class {
+ observe() {}
+ disconnect() {}
+ }
+ );
+ vi.stubGlobal("matchMedia", () => ({ matches: true }));
+});
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const events: AssistantEvent[] = [
+ {
+ kind: "user",
+ payload: {
+ cells: [],
+ input: "i1",
+ interaction: null,
+ text: "How did [@Train](#node=train%201) do?",
+ user: 1,
+ },
+ sequence: 1,
+ },
+ { kind: "assistant", payload: { calls: [], text: "Loss fell to 0.2." }, sequence: 2 },
+];
+
+function show() {
+ const handlers = { onDraft: vi.fn(), onNode: vi.fn() };
+ render(
+ <TooltipProvider>
+ <AssistantTranscript
+ actions={{} as ResultActions}
+ active={false}
+ cells={[]}
+ draft={null}
+ events={events}
+ onSelectCell={vi.fn()}
+ sent={0}
+ teammates={new Map()}
+ {...handlers}
+ />
+ </TooltipProvider>
+ );
+ return handlers;
+}
+
+it("quotes a finished reply into the draft", async () => {
+ const { onDraft } = show();
+ await screen.findByText("Loss fell to 0.2.");
+ fireEvent.click(screen.getByRole("button", { name: "Quote in follow-up" }));
+ expect(onDraft).toHaveBeenCalledWith("> Loss fell to 0.2.\n\n");
+});
+
+it("shows the canvas step a message mentions", () => {
+ const { onNode } = show();
+ fireEvent.click(screen.getByRole("link", { name: "@Train" }));
+ expect(onNode).toHaveBeenCalledWith("train 1");
+});
diff --git a/frontend/src/components/assistant/assistant-transcript.tsx b/frontend/src/components/assistant/assistant-transcript.tsx
index 6195f761..7ebeb09a 100644
--- a/frontend/src/components/assistant/assistant-transcript.tsx
+++ b/frontend/src/components/assistant/assistant-transcript.tsx
@@ -1,29 +1,22 @@
-import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { type ReactNode, useMemo } from "react";
import { useRouter } from "@tanstack/react-router";
-import { ScriptCode } from "@/components/datasets/notebook/script-code";
+import { useCopy } from "@/components/ui/block-actions";
import { Button } from "@/components/ui/button";
-import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Icon } from "@/components/ui/icons";
import { MarkdownContent } from "@/components/ui/markdown";
-import { Spinner } from "@/components/ui/spinner";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
-import { writeClipboardText } from "@/lib/clipboard";
-import { cn } from "@/lib/utils";
import type { Cell } from "@/openapi";
import { AssistantResult, type ResultActions } from "./assistant-result";
-import type { AssistantEvent, Draft, Presentation, ToolCall } from "./types";
+import { ChatThread, type ChatTurn, UserBubble } from "./chat-thread";
+import { type CallState, ReplyActivity, type Step, stepLabel } from "./reply-activity";
+import { quoteReply, SelectionActions } from "./selection-actions";
+import type { AssistantEvent, Draft, Presentation } from "./types";
-type Result = Extract<AssistantEvent, { kind: "tool_result" }>["payload"];
-type Status = Extract<AssistantEvent, { kind: "status" }>["payload"];
-type CallState = "Running" | "Done" | "Failed" | "Interrupted";
+export { stepLabel };
-interface Step {
- call: ToolCall;
- state: CallState;
- result?: Result;
-}
+type Status = Extract<AssistantEvent, { kind: "status" }>["payload"];
type Segment =
| { kind: "text"; key: string; text: string }
@@ -97,31 +90,6 @@ export function turnsOf(events: AssistantEvent[], active: boolean): Turn[] {
return turns;
}
-function argumentsOf(call: ToolCall): Record<string, unknown> {
- try {
- const parsed = JSON.parse(call.raw);
- return parsed && typeof parsed === "object" ? parsed : {};
- } catch {
- return {};
- }
-}
-
-const STEP_LABELS: Record<string, string> = {
- open_toolset: "Opening more tools",
- present: "Showing the result",
- run_pipeline: "Running the transformation",
- run_python: "Running Python",
- stage_dataset: "Loading a dataset version",
-};
-
-/** What a call does, in the words the model wrote for the reader. */
-export function stepLabel(call: ToolCall): string {
- const { summary } = argumentsOf(call);
- if (typeof summary === "string" && summary.trim()) return summary.trim();
- const name = call.name.replaceAll("_", " ");
- return STEP_LABELS[call.name] ?? name.charAt(0).toUpperCase() + name.slice(1);
-}
-
/** The label of the call the run works on now, if it works on one. */
export function runningLabel(events: AssistantEvent[]): string | null {
const answered = new Set<string>();
@@ -136,118 +104,11 @@ export function runningLabel(events: AssistantEvent[]): string | null {
return null;
}
-function errorOf(result: Result | undefined): string {
- if (!result || result.ok) return "";
- const content = result.content as { error?: unknown } | null;
- const error = content?.error;
- if (typeof error === "string") return error;
- if (error && typeof error === "object" && "message" in error) return String(error.message);
- return "The call failed.";
-}
-
-function ToolRow({ step }: { step: Step }) {
- const { call, result, state } = step;
- const python = call.name === "run_python";
- const ToolIcon = python ? Icon.python : call.name === "present" ? Icon.chart : Icon.terminal;
- const { summary: _summary, ...args } = argumentsOf(call);
- const code = python ? String(args.code ?? "") : JSON.stringify(args, null, 2);
- const output = python ? String((result?.content as { output?: string })?.output ?? "") : "";
- const failure = errorOf(result);
- // A presented result shows itself; a failed one shows only why.
- const showCode = call.name !== "present" && code.trim() !== "{}";
- const hasDetails = showCode || !!failure;
- const Trigger = hasDetails ? CollapsibleTrigger : "div";
- return (
- <Collapsible className="assistant-tool-row group/tool">
- <Trigger className="flex w-full min-w-0 items-start gap-2 py-1.5 text-left text-xs text-muted-foreground outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring/60">
- <Tooltip>
- <TooltipTrigger asChild>
- <span className="flex shrink-0">
- <ToolIcon
- className={cn("size-4 shrink-0", call.name === "present" && "text-cat-4")}
- />
- </span>
- </TooltipTrigger>
- <TooltipContent>{python ? "Python" : call.name}</TooltipContent>
- </Tooltip>
- <span className="min-w-0 break-words">{stepLabel(call)}</span>
- <span
- className={cn(
- "sr-only",
- state === "Failed" && "not-sr-only text-error",
- state === "Interrupted" && "not-sr-only text-warning"
- )}
- >
- {state}
- </span>
- {hasDetails && (
- <Icon.chevronRight className="size-3 shrink-0 transition-transform group-data-[state=open]/tool:rotate-90" />
- )}
- </Trigger>
- {hasDetails && (
- <CollapsibleContent className="flex flex-col gap-2 pt-1 pb-2 ps-6">
- {showCode && <ScriptCode kind={python ? "python" : "shell"} source={code} />}
- {output && (
- <pre className="max-h-64 overflow-auto rounded-sm bg-wash-raised p-2 text-xs leading-relaxed">
- {output}
- </pre>
- )}
- {failure && <p className="break-words text-xs text-error">{failure}</p>}
- </CollapsibleContent>
- )}
- </Collapsible>
- );
-}
-
-function ToolGroup({ steps, active }: { steps: Step[]; active: boolean }) {
- const running = steps.some((step) => step.state === "Running");
- const failed = steps.some((step) => step.state === "Failed");
- const [open, setOpen] = useState<boolean>();
- const label = `${steps.length} tool ${steps.length === 1 ? "call" : "calls"}`;
- const status = running
- ? "Running"
- : failed
- ? "Failed"
- : steps.some((step) => step.state === "Interrupted")
- ? "Interrupted"
- : "Done";
- return (
- // A failure the run went on from stays in the list; only one it ended on opens it.
- <Collapsible
- onOpenChange={setOpen}
- open={open ?? (running || active || steps.at(-1)?.state === "Failed")}
- >
- <CollapsibleTrigger
- aria-label={`${label} ${status}`}
- className="group/trigger flex items-center gap-2 py-1.5 text-xs leading-none text-muted-foreground transition-colors hover:text-foreground"
- >
- {running && <Spinner size="sm" />}
- <span className="assistant-tool-count">{label}</span>
- <Icon.chevronDown className="size-3 shrink-0 -rotate-90 transition-transform group-data-[state=open]/trigger:rotate-0 motion-reduce:transition-none" />
- </CollapsibleTrigger>
- <CollapsibleContent className="ps-4">
- {steps.map((step) => (
- <ToolRow key={step.call.id} step={step} />
- ))}
- </CollapsibleContent>
- </Collapsible>
- );
-}
-
-const STATUS_NOTE = {
- continued: "text-muted-foreground",
- failed: "text-error",
- interrupted: "text-warning",
- resumed: "text-muted-foreground",
- stopped: "text-muted-foreground",
- waiting: "text-muted-foreground",
-};
-
-// A mention the composer wrote as a markdown link to a Console page.
-const MENTION = /\[((?:[^\]\\]|\\.)+)\]\((\/[^\s)]*)\)/g;
+// A mention the composer wrote as a markdown link to a Console page or a canvas node.
+const MENTION = /\[((?:[^\]\\]|\\.)+)\]\(((?:\/|#node=)[^\s)]*)\)/g;
/** A message's text with each mention shown as a link to the record it names. */
-export function MentionText({ text }: { text: string }) {
+export function MentionText({ text, onNode }: { text: string; onNode?: (id: string) => void }) {
const router = useRouter();
const parts: ReactNode[] = [];
let at = 0;
@@ -259,9 +120,13 @@ export function MentionText({ text }: { text: string }) {
href={match[2]}
key={match.index}
onClick={(event) => {
- if (event.metaKey || event.ctrlKey || event.shiftKey) return;
+ const node = match[2].startsWith("#node=")
+ ? decodeURIComponent(match[2].slice("#node=".length))
+ : null;
+ if (node === null && (event.metaKey || event.ctrlKey || event.shiftKey)) return;
event.preventDefault();
- router.history.push(match[2]);
+ if (node === null) router.history.push(match[2]);
+ else onNode?.(node);
}}
>
{match[1].replace(/\\(.)/g, "$1")}
@@ -273,202 +138,64 @@ export function MentionText({ text }: { text: string }) {
return <>{parts}</>;
}
-export function AssistantTranscript({
- events,
- draft,
- sent,
- active,
- activity,
- cells,
- teammates,
- actions,
- onSelectCell,
-}: {
- events: AssistantEvent[];
- /** Other members who wrote here, by user id. */
- teammates: ReadonlyMap<number, string>;
- draft: Draft | null;
- /** How many messages this reader sent from this page: each brings the end into view. A
- * teammate's message follows the reader's place like any other content. */
- sent: number;
- active: boolean;
- /** Shown while the run works and nothing else on screen says so. */
- activity?: string;
- cells: Cell[];
- actions: ResultActions;
- onSelectCell: (id: string) => void;
-}) {
- const turns = useMemo(() => turnsOf(events, active), [events, active]);
- const viewport = useRef<HTMLDivElement>(null);
- const [atEnd, setAtEnd] = useState(true);
- const follow = useRef(true);
- const seen = useRef({ client: 0, height: 0, top: 0 });
- const scrollToEnd = useCallback(
- () => viewport.current?.scrollTo({ top: viewport.current.scrollHeight }),
- []
- );
- // Follows new content only while the reader is at the end.
- // biome-ignore lint/correctness/useExhaustiveDependencies: scrolls when the content changes
- useEffect(() => {
- if (follow.current) scrollToEnd();
- }, [events, draft, scrollToEnd]);
- // A chart, a table or an image gets its height after it is in the list, and the panel
- // changes height while it opens: the end must stay in view through both.
- useEffect(() => {
- const node = viewport.current;
- if (!node) return;
- const resized = new ResizeObserver(() => follow.current && scrollToEnd());
- resized.observe(node);
- for (const child of node.children) resized.observe(child);
- return () => resized.disconnect();
- }, [scrollToEnd]);
+const STOPPED: Partial<Record<Status["state"], string>> = {
+ failed: "Response interrupted",
+ interrupted: "Response interrupted",
+ stopped: "Response stopped",
+};
- // biome-ignore lint/correctness/useExhaustiveDependencies: scrolls when a message is sent
- useEffect(() => {
- follow.current = true;
- scrollToEnd();
- }, [sent, scrollToEnd]);
+/** Why a reply ended early. */
+function InterruptedReply({ status }: { status: Status }) {
+ const label = STOPPED[status.state];
+ if (!label) return <p className="text-xs text-muted-foreground">{status.detail}</p>;
+ return (
+ <div className="min-w-0 space-y-1 text-xs" data-slot="interrupted-reply">
+ <output aria-live="polite" className="flex items-center gap-2 text-muted-foreground">
+ <Icon.warning aria-hidden className="size-3.5" />
+ {label}
+ </output>
+ {status.state === "failed" && status.detail && (
+ <p className="break-words whitespace-pre-wrap text-error">{status.detail}</p>
+ )}
+ </div>
+ );
+}
+function MessageActions({ text, onQuote }: { text: string; onQuote?: () => void }) {
+ const { copied, copy } = useCopy(text);
return (
- <div className="assistant-history relative flex min-h-0 flex-1 flex-col">
- <div
- className="assistant-conversation min-h-0 flex-1 overflow-y-auto overscroll-contain"
- onScroll={(event) => {
- const node = event.currentTarget;
- const distance = node.scrollHeight - node.scrollTop - node.clientHeight;
- const before = seen.current;
- // Only the reader's scroll up ends the follow. Content that grows and a panel
- // that resizes also fire this event, and the reader did not leave the end.
- const left =
- node.scrollTop < before.top &&
- node.scrollHeight === before.height &&
- node.clientHeight === before.client;
- if (distance < 48) follow.current = true;
- else if (left) follow.current = false;
- seen.current = {
- client: node.clientHeight,
- height: node.scrollHeight,
- top: node.scrollTop,
- };
- setAtEnd(distance < 48 || follow.current);
- }}
- ref={viewport}
- >
- <div>
- {turns.map((turn) =>
- turn.kind === "user" &&
- turn.event.payload.origin &&
- turn.event.payload.origin !== "user" ? (
- <article
- aria-label={turn.event.payload.origin === "run" ? "Run notice" : "Trigger notice"}
- className="assistant-message flex min-w-0 gap-2 text-xs text-muted-foreground"
- data-role="notice"
- key={turn.event.sequence}
- >
- <Icon.info className="mt-0.5 size-3.5 shrink-0" />
- <p className="min-w-0 whitespace-pre-wrap">{turn.event.payload.text}</p>
- </article>
- ) : turn.kind === "user" ? (
- <article
- aria-label={
- teammates.has(turn.event.payload.user)
- ? `Message from ${teammates.get(turn.event.payload.user)}`
- : "Your message"
- }
- className="assistant-message min-w-0"
- data-role="user"
- key={turn.event.sequence}
- >
- {teammates.has(turn.event.payload.user) && (
- <p
- className="mb-1 truncate text-right text-xs text-muted-foreground"
- title={teammates.get(turn.event.payload.user)}
- >
- {teammates.get(turn.event.payload.user)}
- </p>
- )}
- <div className="assistant-user-prompt text-sm leading-relaxed">
- <MentionText text={turn.event.payload.text} />
- </div>
- {turn.event.payload.cells.length > 0 && (
- <div className="mt-1 flex flex-wrap justify-end gap-x-3 gap-y-1">
- {turn.event.payload.cells.map((id) => {
- const cell = cells.find((item) => item.id === id);
- const named = turn.event.payload.datasets?.[id];
- const label = cell?.title ?? named?.name;
- return (
- <Button
- className="max-w-full justify-start text-muted-foreground"
- disabled={!label}
- key={id}
- onClick={() =>
- cell || !named ? onSelectCell(id) : actions.onCell(id, named.dataset)
- }
- size="xs"
- variant="secondary"
- >
- <Icon.dataset className="size-3 text-cat-2" />
- <span className="truncate" title={label}>
- {label ?? "Dataset version"}
- </span>
- </Button>
- );
- })}
- </div>
- )}
- </article>
- ) : (
- <RunTurn
- actions={actions}
- key={turn.key}
- last={turn === turns.at(-1) && active}
- segments={turn.segments}
- />
- )
- )}
- {draft && (draft.text || draft.steps.length > 0) && (
- <article aria-label="Overmind response" className="assistant-message min-w-0">
- <div className="flex min-w-0 flex-col gap-4">
- {draft.text && (
- <MarkdownContent className="break-words">{draft.text}</MarkdownContent>
- )}
- {draft.steps.length > 0 && (
- <p className="flex items-center gap-2 py-1.5 text-xs text-muted-foreground">
- <Spinner size="sm" />
- <span className="min-w-0 break-words">{draft.steps.at(-1) || "Working"}</span>
- </p>
- )}
- </div>
- </article>
- )}
- {activity && (
- <div
- aria-live="polite"
- className="flex items-center gap-2 px-3 py-3 text-xs text-muted-foreground"
- role="status"
+ <div
+ aria-label="Message actions"
+ className="mt-2 flex items-center gap-0.5 text-muted-foreground"
+ role="group"
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label={copied ? "Copied" : "Copy response"}
+ onClick={copy}
+ size="icon-xs"
+ variant="ghost"
+ >
+ {copied ? <Icon.success className="text-success" /> : <Icon.copy />}
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{copied ? "Copied" : "Copy response"}</TooltipContent>
+ </Tooltip>
+ {onQuote && (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-label="Quote in follow-up"
+ onClick={onQuote}
+ size="icon-xs"
+ variant="ghost"
>
- <Spinner size="sm" />
- <span>{activity}</span>
- </div>
- )}
- {!turns.length && !draft && !activity && (
- <p className="py-2 text-xs text-muted-foreground">No messages</p>
- )}
- </div>
- </div>
- {!atEnd && (
- <Button
- aria-label="Scroll to latest message"
- className="absolute right-3 bottom-2 z-10 rounded-md border border-border bg-popover"
- onClick={() => {
- follow.current = true;
- scrollToEnd();
- }}
- size="icon-xs"
- variant="ghost"
- >
- <Icon.arrowDown />
- </Button>
+ <Icon.session />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>Quote in follow-up</TooltipContent>
+ </Tooltip>
)}
</div>
);
@@ -478,27 +205,30 @@ function RunTurn({
segments,
last,
actions,
+ onDraft,
}: {
segments: Segment[];
+ /** The newest turn of a working thread. */
last: boolean;
actions: ResultActions;
+ onDraft?: (text: string) => void;
}) {
const text = segments
.flatMap((segment) => (segment.kind === "text" ? [segment.text] : []))
.join("\n\n");
return (
- <article aria-label="Overmind response" className="assistant-message min-w-0">
- <div className="flex min-w-0 flex-col gap-4">
+ <article aria-label="Overmind response" className="min-w-0" data-role="assistant">
+ <div className="flex min-w-0 flex-col gap-3">
{segments.map((segment) =>
segment.kind === "text" ? (
- <MarkdownContent className="break-words" key={segment.key}>
+ <MarkdownContent chat className="break-words" key={segment.key}>
{segment.text}
</MarkdownContent>
) : segment.kind === "tools" ? (
- <ToolGroup
- active={last && segment === segments.at(-1)}
+ <ReplyActivity
key={segment.key}
steps={segment.steps}
+ working={last && segment === segments.at(-1)}
/>
) : segment.kind === "result" ? (
<AssistantResult
@@ -512,29 +242,186 @@ function RunTurn({
{segment.text}
</p>
) : (
- <p className={cn("text-xs", STATUS_NOTE[segment.status.state])} key={segment.key}>
- {segment.status.detail}
- </p>
+ <InterruptedReply key={segment.key} status={segment.status} />
)
)}
</div>
{text && !last && (
- <div className="mt-2 flex items-center gap-1 text-muted-foreground">
- <Tooltip>
- <TooltipTrigger asChild>
+ <MessageActions onQuote={onDraft && (() => onDraft(quoteReply(text)))} text={text} />
+ )}
+ </article>
+ );
+}
+
+function UserTurn({
+ event,
+ teammates,
+ cells,
+ actions,
+ onSelectCell,
+ onNode,
+}: {
+ event: Extract<AssistantEvent, { kind: "user" }>;
+ teammates: ReadonlyMap<number, string>;
+ cells: Cell[];
+ actions: ResultActions;
+ onSelectCell: (id: string) => void;
+ onNode?: (id: string) => void;
+}) {
+ const { payload } = event;
+ if (payload.origin && payload.origin !== "user")
+ return (
+ <article
+ aria-label={payload.origin === "run" ? "Run notice" : "Trigger notice"}
+ className="flex min-w-0 gap-2 text-xs text-muted-foreground"
+ data-role="notice"
+ >
+ <Icon.info className="mt-0.5 size-3.5 shrink-0" />
+ <p className="min-w-0 whitespace-pre-wrap">{payload.text}</p>
+ </article>
+ );
+ const author = teammates.get(payload.user);
+ return (
+ <article
+ aria-label={author ? `Message from ${author}` : "Your message"}
+ className="min-w-0"
+ data-role="user"
+ >
+ <UserBubble author={author}>
+ <p className="chat-user-text">
+ <MentionText onNode={onNode} text={payload.text} />
+ </p>
+ </UserBubble>
+ {payload.cells.length > 0 && (
+ <div className="mt-2 flex flex-wrap justify-end gap-1">
+ {payload.cells.map((id) => {
+ const cell = cells.find((item) => item.id === id);
+ const named = payload.datasets?.[id];
+ const label = cell?.title ?? named?.name;
+ return (
<Button
- aria-label="Copy response"
- onClick={() => void writeClipboardText(text)}
- size="icon-xs"
- variant="ghost"
+ aria-label={`Show ${label ?? "dataset"} cell`}
+ className="max-w-full"
+ disabled={!label}
+ key={id}
+ onClick={() =>
+ cell || !named ? onSelectCell(id) : actions.onCell(id, named.dataset)
+ }
+ size="xs"
+ variant="secondary"
>
- <Icon.copy />
+ <Icon.dataset className="text-cat-2" />
+ <span className="truncate">{label ?? "Dataset version"}</span>
</Button>
- </TooltipTrigger>
- <TooltipContent>Copy response</TooltipContent>
- </Tooltip>
+ );
+ })}
</div>
)}
</article>
);
}
+
+/** The reply being written: its text so far, and what it does now. */
+function DraftReply({ draft }: { draft: Draft }) {
+ return (
+ <article aria-label="Overmind response" className="min-w-0" data-role="assistant">
+ <div className="flex min-w-0 flex-col gap-3">
+ {draft.text && (
+ <MarkdownContent chat className="break-words">
+ {draft.text}
+ </MarkdownContent>
+ )}
+ {(draft.steps.length > 0 || !draft.text) && (
+ <ReplyActivity label={draft.steps.at(-1) || undefined} steps={[]} working />
+ )}
+ </div>
+ </article>
+ );
+}
+
+export function AssistantTranscript({
+ events,
+ draft,
+ sent,
+ active,
+ activity,
+ cells,
+ teammates,
+ actions,
+ onSelectCell,
+ onDraft,
+ onNode,
+}: {
+ events: AssistantEvent[];
+ /** Other members who wrote here, by user id. */
+ teammates: ReadonlyMap<number, string>;
+ draft: Draft | null;
+ /** How many messages this reader sent from this page. */
+ sent: number;
+ active: boolean;
+ /** Shown while the run works and nothing else on screen says so. */
+ activity?: string;
+ cells: Cell[];
+ actions: ResultActions;
+ onSelectCell: (id: string) => void;
+ /** Puts text into the composer's draft. */
+ onDraft?: (text: string) => void;
+ /** Shows a mentioned canvas node. */
+ onNode?: (id: string) => void;
+}) {
+ const turns = useMemo(() => turnsOf(events, active), [events, active]);
+ const chat: ChatTurn[] = [];
+ for (const turn of turns) {
+ const opens = turn.kind === "user";
+ if (opens || !chat.length)
+ chat.push({
+ children: [],
+ key: String(turn.kind === "user" ? turn.event.sequence : turn.key),
+ sent: opens && (turn.event.payload.origin ?? "user") === "user",
+ });
+ const content =
+ turn.kind === "user" ? (
+ <UserTurn
+ actions={actions}
+ cells={cells}
+ event={turn.event}
+ key={turn.event.sequence}
+ onNode={onNode}
+ onSelectCell={onSelectCell}
+ teammates={teammates}
+ />
+ ) : (
+ <RunTurn
+ actions={actions}
+ key={turn.key}
+ last={turn === turns.at(-1) && active}
+ onDraft={onDraft}
+ segments={turn.segments}
+ />
+ );
+ (chat.at(-1)!.children as ReactNode[]).push(content);
+ }
+ const working = (() => {
+ const last = turns.at(-1);
+ return (
+ last?.kind === "run" &&
+ last.segments.some(
+ (segment) =>
+ segment.kind === "tools" && segment.steps.some((step) => step.state === "Running")
+ )
+ );
+ })();
+ const footer =
+ draft && (draft.text || draft.steps.length) ? (
+ <DraftReply draft={draft} />
+ ) : activity && !working ? (
+ <ReplyActivity label={activity} steps={[]} working />
+ ) : !turns.length ? (
+ <p className="py-2 text-xs text-muted-foreground">No messages</p>
+ ) : null;
+ return (
+ <SelectionActions onDraft={onDraft}>
+ <ChatThread footer={footer} sent={sent} turns={chat} />
+ </SelectionActions>
+ );
+}
diff --git a/frontend/src/components/assistant/chat-thread.tsx b/frontend/src/components/assistant/chat-thread.tsx
new file mode 100644
index 00000000..e0d13b0a
--- /dev/null
+++ b/frontend/src/components/assistant/chat-thread.tsx
@@ -0,0 +1,224 @@
+import { type ReactNode, useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
+
+import { Icon } from "@/components/ui/icons";
+import { cn } from "@/lib/utils";
+
+const PAD_TOP = 8;
+const PAD_BOTTOM = 20;
+const STICK = 8;
+const AWAY = 96;
+const AUTO_SCROLL_MS = 1000;
+const FOLD_OVER = 320;
+const FOLD_TO = 216;
+
+const lessMotion = () => window.matchMedia("(prefers-reduced-motion: reduce)").matches;
+
+export interface ChatTurn {
+ key: string;
+ /** The turn opens with a message the reader sent. */
+ sent: boolean;
+ children: ReactNode;
+}
+
+/** A person's message, folded past a few lines with a Show more toggle. */
+export function UserBubble({ children, author }: { children: ReactNode; author?: string }) {
+ const body = useRef<HTMLDivElement>(null);
+ const [folds, setFolds] = useState(false);
+ const [open, setOpen] = useState(false);
+ useLayoutEffect(() => {
+ if (body.current) setFolds(body.current.scrollHeight > FOLD_OVER);
+ });
+ const folded = folds && !open;
+ return (
+ <div className="flex min-w-0 flex-col items-end gap-1.5">
+ {author && (
+ <p className="max-w-full truncate text-xs text-muted-foreground" title={author}>
+ {author}
+ </p>
+ )}
+ <div
+ className="chat-user-bubble min-w-0 bg-accent text-card-foreground"
+ data-slot="chat-user"
+ >
+ <div
+ className={cn("min-w-0", folded && "chat-user-folded overflow-hidden")}
+ ref={body}
+ style={folded ? { maxHeight: FOLD_TO } : undefined}
+ >
+ {children}
+ </div>
+ {folds && (
+ <button
+ aria-expanded={open}
+ className="mt-1 cursor-pointer rounded-sm bg-control px-2 py-1 text-xs font-medium text-card-foreground transition-colors hover:bg-control-hover focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none"
+ onClick={() => setOpen(!open)}
+ type="button"
+ >
+ {open ? "Show less" : "Show more"}
+ </button>
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** The conversation's scroller. It follows new content while the reader is at the end, and
+ * a message the reader just sent moves to the top with the reply written into the space
+ * below it. Scrolled away, a button returns to the end. */
+export function ChatThread({
+ turns,
+ sent,
+ label = "Conversation",
+ footer,
+}: {
+ turns: ChatTurn[];
+ /** How many messages the reader sent from this page. */
+ sent: number;
+ label?: string;
+ /** Shown after the newest turn. */
+ footer?: ReactNode;
+}) {
+ const scroller = useRef<HTMLDivElement>(null);
+ const content = useRef<HTMLDivElement>(null);
+ const follow = useRef(true);
+ const auto = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const [away, setAway] = useState(false);
+ const [anchor, setAnchor] = useState<string | null>(null);
+
+ const measure = useCallback(() => {
+ const node = scroller.current;
+ if (!node) return 0;
+ const gap = node.scrollHeight - node.scrollTop - node.clientHeight;
+ // Not while the thread scrolls itself: the button would flash on the way.
+ setAway(gap > AWAY && auto.current === null);
+ return gap;
+ }, []);
+ const endAuto = useCallback(() => {
+ if (auto.current !== null) clearTimeout(auto.current);
+ auto.current = null;
+ }, []);
+ const startAuto = useCallback(() => {
+ endAuto();
+ auto.current = setTimeout(() => {
+ auto.current = null;
+ measure();
+ }, AUTO_SCROLL_MS);
+ }, [endAuto, measure]);
+
+ useLayoutEffect(() => {
+ const node = scroller.current;
+ const inner = content.current;
+ if (!node || !inner) return;
+ const resized = () => {
+ node.style.setProperty("--chat-thread-view", `${node.clientHeight}px`);
+ if (follow.current) node.scrollTop = node.scrollHeight;
+ measure();
+ };
+ resized();
+ const observer = new ResizeObserver(resized);
+ observer.observe(node);
+ observer.observe(inner);
+ return () => {
+ observer.disconnect();
+ endAuto();
+ };
+ }, [endAuto, measure]);
+
+ // A send waits for its message to arrive in the thread, then holds that turn at the top.
+ const newest = turns.at(-1);
+ const counted = useRef(sent);
+ const before = useRef<string | null>(null);
+ useEffect(() => {
+ if (sent !== counted.current) {
+ counted.current = sent;
+ before.current = newest?.key ?? "";
+ }
+ if (before.current !== null && newest?.sent && newest.key !== before.current) {
+ before.current = null;
+ setAnchor(newest.key);
+ }
+ }, [sent, newest]);
+ useLayoutEffect(() => {
+ const node = scroller.current;
+ if (!node || anchor === null) return;
+ const turn = [...node.querySelectorAll<HTMLElement>("[data-turn]")].find(
+ (item) => item.dataset.turn === anchor
+ );
+ if (!turn) return;
+ follow.current = false;
+ startAuto();
+ node.scrollTo({ behavior: lessMotion() ? "auto" : "smooth", top: turn.offsetTop - PAD_TOP });
+ }, [anchor, startAuto]);
+
+ const toEnd = () => {
+ const node = scroller.current;
+ if (!node) return;
+ follow.current = true;
+ if (lessMotion()) {
+ node.scrollTop = node.scrollHeight;
+ return;
+ }
+ startAuto();
+ node.scrollTo({ behavior: "smooth", top: node.scrollHeight });
+ };
+
+ return (
+ <div className="relative flex min-h-0 min-w-0 flex-1 flex-col" data-slot="chat-thread">
+ <div
+ aria-label={label}
+ className="chat-thread-scroller relative flex min-h-0 flex-1 flex-col overflow-x-hidden overflow-y-auto overscroll-contain scroll-fade-y outline-none"
+ onKeyDown={endAuto}
+ onPointerDown={endAuto}
+ onScroll={() => {
+ const gap = measure();
+ // Reaching the end by hand follows along again; leaving it stops that.
+ if (auto.current === null) follow.current = gap <= STICK;
+ }}
+ onTouchStart={endAuto}
+ onWheel={endAuto}
+ ref={scroller}
+ role="region"
+ // biome-ignore lint/a11y/noNoninteractiveTabindex: keyboard users scroll the conversation
+ tabIndex={0}
+ >
+ <div
+ className="mx-auto flex w-full max-w-[46rem] flex-col gap-6 px-3 pt-2 pb-5"
+ ref={content}
+ role="log"
+ >
+ {turns.map((turn) => (
+ <div
+ className="flex min-w-0 flex-col gap-4"
+ data-turn={turn.key}
+ key={turn.key}
+ style={
+ turn.key === anchor && turn === newest
+ ? { minHeight: `calc(var(--chat-thread-view) - ${PAD_TOP + PAD_BOTTOM}px)` }
+ : undefined
+ }
+ >
+ {turn.children}
+ {turn === newest && footer}
+ </div>
+ ))}
+ {!turns.length && footer}
+ </div>
+ </div>
+ <button
+ aria-label="Scroll to latest message"
+ className={cn(
+ "absolute bottom-3 left-1/2 z-10 inline-flex size-8 -translate-x-1/2 cursor-pointer items-center justify-center rounded-sm bg-card text-card-foreground transition-[opacity,scale,translate] ease-out focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none active:scale-[0.96] motion-reduce:transition-none",
+ away
+ ? "translate-y-0 scale-100 opacity-100 duration-200"
+ : "pointer-events-none translate-y-1 scale-95 opacity-0 duration-100"
+ )}
+ inert={!away}
+ onClick={toEnd}
+ title="Scroll to latest message"
+ type="button"
+ >
+ <Icon.arrowDown aria-hidden className="size-4" />
+ </button>
+ </div>
+ );
+}
diff --git a/frontend/src/components/assistant/ghost-completion.test.ts b/frontend/src/components/assistant/ghost-completion.test.ts
new file mode 100644
index 00000000..f371e59a
--- /dev/null
+++ b/frontend/src/components/assistant/ghost-completion.test.ts
@@ -0,0 +1,22 @@
+// covers: console-logic
+import { describe, expect, it } from "vitest";
+
+import { completionFor } from "./ghost-completion";
+
+const suggestions = ["Summarize progress and flag anything that needs my input."];
+
+describe("completionFor", () => {
+ it("offers the first suggestion whole for an empty draft", () => {
+ expect(completionFor("", suggestions)).toBe(suggestions[0]);
+ });
+
+ it("completes a draft that starts a suggestion, whatever its case", () => {
+ expect(completionFor("summ", suggestions)).toBe(suggestions[0].slice(4));
+ });
+
+ it("offers nothing for a short draft, a mention or a second line", () => {
+ expect(completionFor("Su", suggestions)).toBe("");
+ expect(completionFor("Summarize @", suggestions)).toBe("");
+ expect(completionFor("Summarize\nprogress", suggestions)).toBe("");
+ });
+});
diff --git a/frontend/src/components/assistant/ghost-completion.tsx b/frontend/src/components/assistant/ghost-completion.tsx
new file mode 100644
index 00000000..87e2a1c0
--- /dev/null
+++ b/frontend/src/components/assistant/ghost-completion.tsx
@@ -0,0 +1,112 @@
+import { type KeyboardEvent, type SyntheticEvent, useEffect, useId, useState } from "react";
+
+import { Kbd } from "@/components/ui/kbd";
+import { cn } from "@/lib/utils";
+
+/** The rest of the first suggestion the draft starts, or the first suggestion for an empty
+ * draft. A mention or a second line ends suggesting. */
+export function completionFor(value: string, suggestions: readonly string[]) {
+ if (value === "") return suggestions[0] ?? "";
+ if (value.trim().length < 3 || value.includes("@") || value.includes("\n")) return "";
+ const lower = value.toLowerCase();
+ const match = suggestions.find(
+ (item) => item.length > value.length && item.toLowerCase().startsWith(lower)
+ );
+ return match ? match.slice(value.length) : "";
+}
+
+const plain = (event: KeyboardEvent) =>
+ !event.shiftKey && !event.altKey && !event.ctrlKey && !event.metaKey;
+
+/** A suggested ending drawn after the caret: Tab takes it, Alt or Ctrl with Right takes one
+ * word, Escape hides it until the draft changes. It shows only while the caret is at the
+ * end of a focused field and the draft has rested. */
+export function useGhostCompletion(
+ value: string,
+ onChange: (value: string) => void,
+ suggestions: readonly string[]
+) {
+ const [rested, setRested] = useState(value);
+ const [dismissed, setDismissed] = useState<string | null>(null);
+ const [atEnd, setAtEnd] = useState(false);
+ const [composing, setComposing] = useState(false);
+ const [scroll, setScroll] = useState({ left: 0, top: 0 });
+ const hintId = useId();
+ useEffect(() => {
+ const timer = setTimeout(() => setRested(value), 350);
+ return () => clearTimeout(timer);
+ }, [value]);
+ const suffix =
+ atEnd && !composing && rested === value && dismissed !== value
+ ? completionFor(value, suggestions)
+ : "";
+ const track = (event: SyntheticEvent<HTMLTextAreaElement>) => {
+ const field = event.currentTarget;
+ const end = field.value.length;
+ setAtEnd(
+ document.activeElement === field && field.selectionStart === end && field.selectionEnd === end
+ );
+ };
+ const accept = (field: HTMLTextAreaElement, next: string) => {
+ setRested(next);
+ onChange(next);
+ requestAnimationFrame(() => field.setSelectionRange(next.length, next.length));
+ };
+ return {
+ hint: suffix ? (
+ <span className="sr-only" id={hintId}>
+ Suggestion: {suffix}. Tab accepts it, Alt Right accepts one word, Escape hides it.
+ </span>
+ ) : null,
+ inputProps: {
+ "aria-describedby": suffix ? hintId : undefined,
+ onBlur: () => setAtEnd(false),
+ onCompositionEnd: (event: SyntheticEvent<HTMLTextAreaElement>) => {
+ setComposing(false);
+ track(event);
+ },
+ onCompositionStart: () => setComposing(true),
+ onFocus: track,
+ onKeyDownCapture: (event: KeyboardEvent<HTMLTextAreaElement>) => {
+ if (!suffix || event.nativeEvent.isComposing) return;
+ const field = event.currentTarget;
+ if (event.key === "Escape") {
+ event.preventDefault();
+ event.stopPropagation();
+ setDismissed(value);
+ } else if (event.key === "Tab" && plain(event)) {
+ event.preventDefault();
+ event.stopPropagation();
+ accept(field, value + suffix);
+ } else if (
+ event.key === "ArrowRight" &&
+ (event.altKey || event.ctrlKey) &&
+ !event.shiftKey &&
+ !event.metaKey
+ ) {
+ event.preventDefault();
+ event.stopPropagation();
+ accept(field, value + (/^\s*\S+/.exec(suffix)?.[0] ?? suffix));
+ }
+ },
+ onScroll: (event: SyntheticEvent<HTMLTextAreaElement>) =>
+ setScroll({ left: event.currentTarget.scrollLeft, top: event.currentTarget.scrollTop }),
+ onSelect: track,
+ },
+ /** Drawn over the field with the field's own padding and type. */
+ layer: (className: string) =>
+ suffix ? (
+ <div aria-hidden="true" className="pointer-events-none absolute inset-0 overflow-hidden">
+ <div
+ className={cn(className, "whitespace-pre-wrap break-words")}
+ style={{ transform: `translate(${-scroll.left}px, ${-scroll.top}px)` }}
+ >
+ <span className="invisible">{value}</span>
+ <span className="text-muted-foreground">{suffix}</span>
+ <Kbd className="ml-1 align-middle">Tab</Kbd>
+ </div>
+ </div>
+ ) : null,
+ suffix,
+ };
+}
diff --git a/frontend/src/components/assistant/mention-textarea.tsx b/frontend/src/components/assistant/mention-textarea.tsx
index 69629c61..5f753685 100644
--- a/frontend/src/components/assistant/mention-textarea.tsx
+++ b/frontend/src/components/assistant/mention-textarea.tsx
@@ -1,5 +1,6 @@
import {
type ComponentProps,
+ type ReactNode,
type Ref,
useId,
useImperativeHandle,
@@ -59,10 +60,15 @@ function Mirror({
);
}
+export type LocalMention = MentionEntity & { icon: ReactNode };
+
/** A textarea where `@` searches the project's evaluations, benchmarks, datasets and
- * capabilities; a picked record is kept as a mention of that exact record. */
+ * capabilities, or the given records instead; a picked record is kept as a mention of that
+ * exact record. */
export function MentionTextarea({
projectId,
+ local,
+ overlay,
references,
onReferencesChange,
onMention,
@@ -75,6 +81,10 @@ export function MentionTextarea({
}: Omit<ComponentProps<"textarea">, "ref" | "value" | "onChange"> & {
ref?: Ref<HTMLTextAreaElement>;
projectId: string;
+ /** Records to mention in place of the project's, filtered here by label. */
+ local?: LocalMention[];
+ /** Drawn over the field, inside its box. */
+ overlay?: ReactNode;
value: string;
onValueChange: (text: string) => void;
references: MentionRange[];
@@ -102,7 +112,23 @@ export function MentionTextarea({
!!match &&
start !== dismissed &&
!references.some((r) => start >= r.start && start < r.end);
- const catalogue = useMentionEntities(projectId, open && match ? match[1] : null);
+ const query = open && match ? match[1] : null;
+ const searched = useMentionEntities(projectId, local ? null : query);
+ const catalogue = local
+ ? {
+ loading: false,
+ sections: [
+ {
+ error: false,
+ group: local[0]?.group ?? "",
+ items: local
+ .filter((item) => item.label.toLowerCase().includes((query ?? "").toLowerCase()))
+ .slice(0, 8),
+ },
+ ],
+ }
+ : searched;
+ const icons = new Map(local?.map((item) => [item.id, item.icon]));
const rows = catalogue.sections.flatMap((section) => section.items);
const selected = Math.max(0, Math.min(active, rows.length - 1));
useLayoutEffect(() => {
@@ -214,11 +240,13 @@ export function MentionTextarea({
onSelect={(event) => {
const node = event.currentTarget;
setCaret(node.selectionStart === node.selectionEnd ? node.selectionStart : null);
+ props.onSelect?.(event);
}}
ref={field}
role="combobox"
value={value}
/>
+ {overlay}
{open &&
createPortal(
<div
@@ -237,6 +265,7 @@ export function MentionTextarea({
{section.items.map((entity) => {
const index = rows.indexOf(entity);
const Glyph = ICONS[entity.group] ?? Icon.link;
+ const icon = icons.get(entity.id);
return (
<button
aria-selected={selected === index}
@@ -252,9 +281,11 @@ export function MentionTextarea({
tabIndex={-1}
type="button"
>
- <Glyph className="size-4 shrink-0 text-info" />
+ {icon ?? <Glyph className="size-4 shrink-0 text-info" />}
<span className="min-w-0 flex-1 truncate">{entity.label}</span>
- <span className="text-muted-foreground">{entity.id.slice(0, 8)}</span>
+ {!local && (
+ <span className="text-muted-foreground">{entity.id.slice(0, 8)}</span>
+ )}
</button>
);
})}
diff --git a/frontend/src/components/assistant/panel-resize.tsx b/frontend/src/components/assistant/panel-resize.tsx
deleted file mode 100644
index 2eaf0367..00000000
--- a/frontend/src/components/assistant/panel-resize.tsx
+++ /dev/null
@@ -1,68 +0,0 @@
-import { useRef } from "react";
-
-export const PANEL_WIDTH = { default: 416, max: 800, min: 320 };
-const KEY_STEP = 16;
-
-/** The panel's right edge: drag, arrow keys, Home and End resize it; a double click resets.
- * A drag reports each width and ends with `null`; only `onCommit` is a kept width. */
-export function PanelResize({
- panelId,
- width,
- onDrag,
- onCommit,
-}: {
- panelId: string;
- width: number;
- onDrag: (width: number | null) => void;
- onCommit: (width: number) => void;
-}) {
- const origin = useRef<{ x: number; width: number } | null>(null);
- const dragged = useRef(width);
- const clamp = (value: number) =>
- Math.round(Math.min(PANEL_WIDTH.max, Math.max(PANEL_WIDTH.min, value)));
- const end = () => {
- if (!origin.current) return;
- origin.current = null;
- onCommit(dragged.current);
- onDrag(null);
- };
- return (
- <div
- aria-controls={panelId}
- aria-label="Resize conversation"
- aria-orientation="vertical"
- aria-valuemax={PANEL_WIDTH.max}
- aria-valuemin={PANEL_WIDTH.min}
- aria-valuenow={width}
- className="assistant-resize-handle"
- onDoubleClick={() => onCommit(PANEL_WIDTH.default)}
- onKeyDown={(event) => {
- const next = {
- ArrowLeft: width - KEY_STEP,
- ArrowRight: width + KEY_STEP,
- End: PANEL_WIDTH.max,
- Home: PANEL_WIDTH.min,
- }[event.key];
- if (next === undefined) return;
- event.preventDefault();
- onCommit(clamp(next));
- }}
- onLostPointerCapture={end}
- onPointerCancel={end}
- onPointerDown={(event) => {
- event.currentTarget.setPointerCapture(event.pointerId);
- origin.current = { width, x: event.clientX };
- dragged.current = width;
- onDrag(width);
- }}
- onPointerMove={(event) => {
- if (!origin.current) return;
- dragged.current = clamp(origin.current.width + event.clientX - origin.current.x);
- onDrag(dragged.current);
- }}
- onPointerUp={end}
- role="separator"
- tabIndex={0}
- />
- );
-}
diff --git a/frontend/src/components/assistant/reply-activity.tsx b/frontend/src/components/assistant/reply-activity.tsx
new file mode 100644
index 00000000..7f599d4f
--- /dev/null
+++ b/frontend/src/components/assistant/reply-activity.tsx
@@ -0,0 +1,298 @@
+import { type ReactNode, useState } from "react";
+
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+
+import { ScriptCode } from "@/components/datasets/notebook/script-code";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Icon } from "@/components/ui/icons";
+import { Spinner } from "@/components/ui/spinner";
+import { cn } from "@/lib/utils";
+import type { AssistantEvent, ToolCall } from "./types";
+
+type Result = Extract<AssistantEvent, { kind: "tool_result" }>["payload"];
+export type CallState = "Running" | "Done" | "Failed" | "Interrupted";
+
+export interface Step {
+ call: ToolCall;
+ state: CallState;
+ result?: Result;
+}
+
+const EASE = [0.4, 0, 0.2, 1] as const;
+
+const STEP_LABELS: Record<string, string> = {
+ open_toolset: "Opening more tools",
+ present: "Showing the result",
+ run_pipeline: "Running the transformation",
+ run_python: "Running Python",
+ stage_dataset: "Loading a dataset version",
+};
+
+function argumentsOf(call: ToolCall): Record<string, unknown> {
+ try {
+ const parsed = JSON.parse(call.raw);
+ return parsed && typeof parsed === "object" ? parsed : {};
+ } catch {
+ return {};
+ }
+}
+
+/** What a call does, in the words the model wrote for the reader. */
+export function stepLabel(call: ToolCall): string {
+ const { summary } = argumentsOf(call);
+ if (typeof summary === "string" && summary.trim()) return summary.trim();
+ const name = call.name.replaceAll("_", " ");
+ return STEP_LABELS[call.name] ?? name.charAt(0).toUpperCase() + name.slice(1);
+}
+
+function errorOf(result: Result | undefined): string {
+ if (!result || result.ok) return "";
+ const error = (result.content as { error?: unknown } | null)?.error;
+ if (typeof error === "string") return error;
+ if (error && typeof error === "object" && "message" in error) return String(error.message);
+ return "The call failed.";
+}
+
+const toolIcon = (name: string) =>
+ name === "run_python" ? Icon.python : name === "present" ? Icon.chart : Icon.terminal;
+
+/** The eye blinks while the reply is being written. */
+function Eye({ blinking }: { blinking: boolean }) {
+ return (
+ <img
+ alt=""
+ className="thinking-eye size-4 object-contain"
+ height={16}
+ src={blinking ? "/thinking-eye.gif" : "/favicon.png"}
+ width={16}
+ />
+ );
+}
+
+/** A label that rolls to its next text. */
+function Rolling({ label, shimmer }: { label: string; shimmer: boolean }) {
+ const reduce = useReducedMotion();
+ return (
+ <span className="relative inline-flex min-w-0">
+ <AnimatePresence initial={false} mode="popLayout">
+ <motion.span
+ animate={{ filter: "blur(0px)", opacity: 1, y: 0 }}
+ className={cn("block min-w-0 truncate", shimmer && "status-shimmer")}
+ exit={{ filter: "blur(3px)", opacity: 0, y: "-0.5em" }}
+ initial={{ filter: "blur(3px)", opacity: 0, y: "0.5em" }}
+ key={label}
+ transition={{ duration: reduce ? 0 : 0.28, ease: EASE }}
+ >
+ {label}
+ </motion.span>
+ </AnimatePresence>
+ </span>
+ );
+}
+
+/** What a call shows when opened: its code, its output and why it failed. */
+function detailsOf({ call, result }: Step) {
+ const python = call.name === "run_python";
+ const { summary: _summary, ...args } = argumentsOf(call);
+ const code = python ? String(args.code ?? "") : JSON.stringify(args, null, 2);
+ return {
+ // A presented result shows itself.
+ code: call.name !== "present" && code.trim() !== "{}" ? code : "",
+ failure: errorOf(result),
+ output: python ? String((result?.content as { output?: string })?.output ?? "") : "",
+ python,
+ };
+}
+
+function StepBody({ step }: { step: Step }) {
+ const { code, failure, output, python } = detailsOf(step);
+ return (
+ <div className="flex min-w-0 flex-col gap-1.5">
+ {code && <ScriptCode kind={python ? "python" : "shell"} source={code} />}
+ {output && (
+ <pre className="max-h-64 overflow-auto rounded-sm bg-wash-raised p-2 text-xs leading-relaxed">
+ {output}
+ </pre>
+ )}
+ {failure && (
+ <p
+ className={cn(
+ "text-xs break-words whitespace-pre-wrap",
+ step.state === "Interrupted" ? "text-muted-foreground" : "text-destructive"
+ )}
+ >
+ {failure}
+ </p>
+ )}
+ </div>
+ );
+}
+
+function StepRow({ step, first, last }: { step: Step; first: boolean; last: boolean }) {
+ const reduce = useReducedMotion();
+ const Glyph = toolIcon(step.call.name);
+ const details = detailsOf(step);
+ const hasBody = !!(details.code || details.output || details.failure);
+ const running = step.state === "Running";
+ const failed = step.state === "Failed";
+ const title = (
+ <>
+ <span
+ className={cn("min-w-0 flex-1 break-words", running && "status-shimmer")}
+ title={step.call.name}
+ >
+ {stepLabel(step.call)}
+ </span>
+ {step.state !== "Done" && (
+ <span className="shrink-0 text-muted-foreground">
+ {step.state === "Interrupted" ? "Stopped" : step.state}
+ </span>
+ )}
+ </>
+ );
+ const row = "flex min-h-6 w-full items-center gap-2 text-xs leading-5 text-card-foreground";
+ return (
+ <motion.li
+ animate={{
+ filter: "blur(0px)",
+ height: "auto",
+ opacity: 1,
+ transitionEnd: { overflow: "visible" },
+ }}
+ className="relative"
+ data-state={step.state}
+ initial={{ filter: "blur(4px)", height: 0, opacity: 0, overflow: "hidden" }}
+ transition={{ duration: reduce ? 0 : 0.3, ease: EASE }}
+ >
+ <div className="flex min-w-0 gap-2">
+ <span className="flex w-6 flex-none flex-col items-center">
+ <span
+ aria-hidden
+ className={cn("h-[3px] w-px shrink-0 bg-foreground/12", first && "invisible")}
+ />
+ <span className="relative flex size-5 items-center justify-center rounded-sm bg-wash-raised text-muted-foreground">
+ <Glyph aria-hidden className="size-3.5" />
+ {(running || failed) && (
+ <span className="absolute -right-1 -bottom-1 inline-flex size-3.5 items-center justify-center rounded-xs bg-card">
+ {running ? (
+ <Spinner size="sm" />
+ ) : (
+ <Icon.warning aria-hidden className="size-3.5 text-destructive" />
+ )}
+ </span>
+ )}
+ </span>
+ {!last && <span aria-hidden className="w-px flex-1 bg-foreground/12" />}
+ </span>
+ <div className={cn("flex min-w-0 flex-1 flex-col gap-1.5", !last && "pb-2.5")}>
+ {hasBody ? (
+ <Collapsible defaultOpen={running || failed}>
+ <CollapsibleTrigger
+ className={cn(
+ row,
+ "group rounded-sm text-left hover:text-foreground focus-visible:outline-2 focus-visible:outline-ring"
+ )}
+ >
+ {title}
+ <Icon.chevronDown
+ aria-hidden
+ className="size-3 shrink-0 -rotate-90 text-muted-foreground transition-transform group-data-[state=open]:rotate-0 motion-reduce:transition-none"
+ />
+ </CollapsibleTrigger>
+ <CollapsibleContent className="pt-1.5">
+ <StepBody step={step} />
+ </CollapsibleContent>
+ </Collapsible>
+ ) : (
+ <div className={row}>{title}</div>
+ )}
+ </div>
+ </div>
+ </motion.li>
+ );
+}
+
+/** A reply's work as one disclosure: the header names what happens now, or what was done,
+ * and opens the list of calls. */
+export function ReplyActivity({
+ steps,
+ working,
+ label,
+}: {
+ steps: Step[];
+ /** The reply is being written. */
+ working: boolean;
+ /** What the reply does now, when it says. */
+ label?: string;
+}): ReactNode {
+ const reduce = useReducedMotion();
+ const [open, setOpen] = useState<boolean>();
+ const running = steps.find((step) => step.state === "Running");
+ const failed = steps.filter((step) => step.state === "Failed").length;
+ const busy = working || !!running;
+ const heading = busy
+ ? (label ?? (running ? "Running tools" : "Thinking"))
+ : `Ran ${steps.length} ${steps.length === 1 ? "tool" : "tools"}${failed ? ` · ${failed} failed` : ""}`;
+ const shown = open ?? (busy || steps.at(-1)?.state === "Failed");
+ const RunningGlyph = running ? toolIcon(running.call.name) : null;
+ return (
+ <section
+ aria-label="Assistant activity"
+ className="flex w-full max-w-full min-w-0 animate-in flex-col text-card-foreground duration-300 ease-out fade-in-0 slide-in-from-bottom-2 fill-mode-both motion-reduce:animate-none"
+ data-status={busy ? "working" : failed ? "error" : "settled"}
+ >
+ <button
+ aria-expanded={steps.length ? shown : undefined}
+ className={cn(
+ "relative flex h-6 w-fit max-w-full min-w-0 items-center gap-2 rounded-md text-left after:absolute after:-inset-1.5 focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none",
+ steps.length ? "cursor-pointer" : "cursor-default"
+ )}
+ disabled={!steps.length}
+ onClick={() => setOpen(!shown)}
+ type="button"
+ >
+ <span className="inline-flex size-6 flex-none items-center justify-center rounded-md bg-muted">
+ {RunningGlyph ? (
+ <RunningGlyph aria-hidden className="size-4" />
+ ) : (
+ <Eye blinking={busy && !reduce} />
+ )}
+ </span>
+ <output aria-live="polite" className="flex min-w-0 flex-1 text-xs leading-5 font-medium">
+ <Rolling label={heading} shimmer={busy} />
+ </output>
+ {steps.length > 0 && (
+ <Icon.chevronDown
+ aria-hidden
+ className={cn(
+ "size-3 flex-none text-muted-foreground transition-transform duration-150 ease-out motion-reduce:transition-none",
+ shown ? "rotate-0" : "-rotate-90"
+ )}
+ />
+ )}
+ </button>
+ <AnimatePresence initial={false}>
+ {shown && steps.length > 0 && (
+ <motion.div
+ animate={{ height: "auto", opacity: 1 }}
+ className="overflow-hidden"
+ exit={{ height: 0, opacity: 0 }}
+ initial={{ height: 0, opacity: 0 }}
+ transition={{ duration: reduce ? 0 : 0.25, ease: EASE }}
+ >
+ <ul className="m-0 flex list-none flex-col p-0 pt-2">
+ {steps.map((step, index) => (
+ <StepRow
+ first={index === 0}
+ key={step.call.id}
+ last={index === steps.length - 1}
+ step={step}
+ />
+ ))}
+ </ul>
+ </motion.div>
+ )}
+ </AnimatePresence>
+ </section>
+ );
+}
diff --git a/frontend/src/components/assistant/selection-actions.tsx b/frontend/src/components/assistant/selection-actions.tsx
new file mode 100644
index 00000000..b84128df
--- /dev/null
+++ b/frontend/src/components/assistant/selection-actions.tsx
@@ -0,0 +1,227 @@
+import {
+ type FormEvent,
+ type ReactNode,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
+import { createPortal } from "react-dom";
+
+import { Icon } from "@/components/ui/icons";
+
+/** The passage as a Markdown quote, then the follow-up. */
+export function quoteReply(text: string, reply = "") {
+ const quote = text
+ .trim()
+ .split("\n")
+ .map((line) => `> ${line}`.trimEnd())
+ .join("\n");
+ return `${quote}\n\n${reply}`;
+}
+
+const GAP = 8;
+const EDGE = 8;
+const HIGHLIGHT = "chat-selection";
+const ACTION =
+ "h-6 flex-none cursor-pointer rounded-md px-2 text-xs leading-none font-medium whitespace-nowrap text-popover-foreground transition-[background-color,scale] duration-150 ease-out hover:bg-accent focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none active:scale-[0.96] motion-reduce:transition-none";
+
+interface Picked {
+ text: string;
+ range: Range;
+}
+
+function picked(root: HTMLElement | null): Picked | null {
+ const selection = document.getSelection();
+ if (!root || !selection || selection.isCollapsed || !selection.rangeCount) return null;
+ const range = selection.getRangeAt(0);
+ if (!root.contains(range.commonAncestorContainer)) return null;
+ const text = selection.toString().trim();
+ return text.length < 2 ? null : { range: range.cloneRange(), text };
+}
+
+/** Above the passage, or below it where there is no room or touch puts its own menu. */
+function place(toolbar: HTMLElement, range: Range, root: HTMLElement | null) {
+ const rect = range.getBoundingClientRect();
+ const bounds = root?.getBoundingClientRect();
+ const hidden =
+ rect.bottom < Math.max(0, bounds?.top ?? 0) ||
+ rect.top > Math.min(window.innerHeight, bounds?.bottom ?? window.innerHeight);
+ const coarse = window.matchMedia("(pointer: coarse)").matches;
+ const above = !coarse && rect.top - toolbar.offsetHeight - GAP >= EDGE;
+ const top = above ? rect.top - toolbar.offsetHeight - GAP : rect.bottom + GAP;
+ const left = Math.min(
+ Math.max(EDGE, rect.left + rect.width / 2 - toolbar.offsetWidth / 2),
+ Math.max(EDGE, window.innerWidth - toolbar.offsetWidth - EDGE)
+ );
+ toolbar.style.left = `${Math.round(left)}px`;
+ toolbar.style.top = `${Math.round(top)}px`;
+ toolbar.dataset.side = above ? "top" : "bottom";
+ toolbar.style.visibility = hidden ? "hidden" : "visible";
+}
+
+function AskField({ onSubmit }: { onSubmit: (question: string) => void }) {
+ const [value, setValue] = useState("");
+ const question = value.trim();
+ return (
+ <form
+ className="flex w-64 max-w-[calc(100vw-2rem)] animate-in items-center gap-1 duration-150 fade-in-0 motion-reduce:animate-none"
+ onSubmit={(event: FormEvent) => {
+ event.preventDefault();
+ if (question) onSubmit(question);
+ }}
+ >
+ <input
+ aria-label="Ask about the selection"
+ // biome-ignore lint/a11y/noAutofocus: the field opens on the reader's own click
+ autoFocus
+ className="h-6 min-w-0 flex-1 bg-transparent px-2 text-xs leading-4 text-popover-foreground outline-none placeholder:text-muted-foreground"
+ onChange={(event) => setValue(event.target.value)}
+ placeholder="Ask about this"
+ value={value}
+ />
+ <button
+ aria-label="Add question to draft"
+ className="flex size-6 flex-none cursor-pointer items-center justify-center rounded-sm bg-primary text-primary-foreground transition-opacity focus-visible:ring-2 focus-visible:ring-ring/50 focus-visible:outline-none disabled:cursor-default disabled:opacity-40"
+ disabled={!question}
+ type="submit"
+ >
+ <Icon.send aria-hidden className="size-3.5" />
+ </button>
+ </form>
+ );
+}
+
+/** Selected text in the conversation gets a toolbar: Ask, Quote and Explain each put the
+ * passage, quoted, into the draft. */
+export function SelectionActions({
+ children,
+ onDraft,
+}: {
+ children: ReactNode;
+ /** Absent while nothing can be drafted. */
+ onDraft?: (text: string) => void;
+}) {
+ const root = useRef<HTMLDivElement>(null);
+ const toolbar = useRef<HTMLDivElement>(null);
+ const dragging = useRef(false);
+ const [selected, setSelected] = useState<Picked | null>(null);
+ const [asking, setAsking] = useState(false);
+ const askingNow = useRef(false);
+ askingNow.current = asking;
+
+ useEffect(() => {
+ if (!onDraft) {
+ setSelected(null);
+ setAsking(false);
+ return;
+ }
+ // The Ask field takes the selection away with it; the picked passage stays.
+ const sync = () =>
+ !askingNow.current && setSelected(dragging.current ? null : picked(root.current));
+ const down = (event: PointerEvent) => {
+ if (event.target instanceof Node && toolbar.current?.contains(event.target)) return;
+ dragging.current = true;
+ setAsking(false);
+ setSelected(null);
+ };
+ const up = () => {
+ dragging.current = false;
+ // The selection settles after the pointer lifts.
+ setTimeout(sync, 0);
+ };
+ const key = (event: KeyboardEvent) => {
+ if (event.key !== "Escape") return;
+ setSelected(null);
+ setAsking(false);
+ };
+ document.addEventListener("selectionchange", sync);
+ document.addEventListener("pointerdown", down);
+ document.addEventListener("pointerup", up);
+ document.addEventListener("keydown", key);
+ return () => {
+ document.removeEventListener("selectionchange", sync);
+ document.removeEventListener("pointerdown", down);
+ document.removeEventListener("pointerup", up);
+ document.removeEventListener("keydown", key);
+ };
+ }, [onDraft]);
+
+ // The passage moves with scrolling, resizing and content streaming in above it.
+ useLayoutEffect(() => {
+ const element = toolbar.current;
+ if (!selected || !element) return;
+ let frame = 0;
+ const follow = () => {
+ place(element, selected.range, root.current);
+ frame = requestAnimationFrame(follow);
+ };
+ follow();
+ return () => cancelAnimationFrame(frame);
+ }, [selected]);
+
+ // While asking, the passage stays marked though the field holds the focus.
+ useEffect(() => {
+ if (!asking || !selected || typeof Highlight === "undefined" || !("highlights" in CSS)) return;
+ CSS.highlights.set(HIGHLIGHT, new Highlight(selected.range));
+ return () => {
+ CSS.highlights.delete(HIGHLIGHT);
+ };
+ }, [asking, selected]);
+
+ const finish = (message: string) => {
+ onDraft?.(message);
+ document.getSelection()?.removeAllRanges();
+ setSelected(null);
+ setAsking(false);
+ };
+ return (
+ <div className="flex min-h-0 flex-1 flex-col" ref={root}>
+ {children}
+ {selected &&
+ onDraft &&
+ createPortal(
+ <div
+ aria-label="Selection actions"
+ className="selection-toolbar fixed top-0 left-0 z-50 flex animate-in items-center gap-0.5 rounded-md border border-border bg-popover p-1 text-popover-foreground duration-150 fade-in-0 zoom-in-[0.97] data-[side=bottom]:slide-in-from-top-1 data-[side=top]:slide-in-from-bottom-1 motion-reduce:animate-none"
+ // A press must not clear the selection it acts on.
+ onPointerDown={(event) => {
+ if (!(event.target instanceof HTMLInputElement)) event.preventDefault();
+ }}
+ ref={toolbar}
+ role="toolbar"
+ style={{ visibility: "hidden" }}
+ >
+ {asking ? (
+ <AskField onSubmit={(question) => finish(quoteReply(selected.text, question))} />
+ ) : (
+ <>
+ <button className={ACTION} onClick={() => setAsking(true)} type="button">
+ Ask
+ </button>
+ <button
+ className={ACTION}
+ onClick={() => finish(quoteReply(selected.text))}
+ type="button"
+ >
+ Quote
+ </button>
+ <button
+ className={ACTION}
+ onClick={() =>
+ finish(
+ quoteReply(selected.text, "Explain this finding and the evidence behind it.")
+ )
+ }
+ type="button"
+ >
+ Explain
+ </button>
+ </>
+ )}
+ </div>,
+ document.body
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/capability-combobox.tsx b/frontend/src/components/capability-combobox.tsx
deleted file mode 100644
index a008d2b9..00000000
--- a/frontend/src/components/capability-combobox.tsx
+++ /dev/null
@@ -1,170 +0,0 @@
-import { useEffect, useState } from "react";
-
-import { useQuery } from "@tanstack/react-query";
-
-import apiClient from "@/client";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from "@/components/ui/command";
-import { formatSmart } from "@/components/ui/datetime";
-import { Icon } from "@/components/ui/icons";
-import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { cn } from "@/lib/utils";
-import type { CapabilityList } from "@/openapi";
-
-export type CapabilityComboboxOption = {
- value: string;
- label: string;
- hint?: string | null;
-};
-
-const capabilityHint = (capability: CapabilityList): string | null => {
- const parts: string[] = [];
- if (capability.traceCount != null && capability.traceCount > 0) {
- parts.push(`${capability.traceCount} trace${capability.traceCount === 1 ? "" : "s"}`);
- }
- if (capability.lastActivityAt) parts.push(`active ${formatSmart(capability.lastActivityAt)}`);
- return parts.length > 0 ? parts.join(" · ") : null;
-};
-
-const useDebouncedValue = (value: string, delayMs: number): string => {
- const [debounced, setDebounced] = useState(value);
- useEffect(() => {
- const t = setTimeout(() => setDebounced(value), delayMs);
- return () => clearTimeout(t);
- }, [value, delayMs]);
- return debounced;
-};
-
-export function CapabilityCombobox({
- value,
- onChange,
- projectId,
- options,
- excludeIds,
- placeholder = "Select a capability",
- searchPlaceholder = "Search capabilities…",
- ariaLabel = "Select capability",
- valueLabel,
- id,
- className,
- disabled,
-}: {
- value: string;
- onChange: (value: string, option?: CapabilityComboboxOption) => void;
- /** Server-search mode: options are fetched and `?search=` does the filtering. */
- projectId?: string;
- /** Static mode: caller-supplied options, filtered client-side by cmdk. */
- options?: CapabilityComboboxOption[];
- /** Server-search mode only. */
- excludeIds?: string[];
- placeholder?: string;
- searchPlaceholder?: string;
- ariaLabel?: string;
- /** Fallback label for the current value when it isn't in the fetched page. */
- valueLabel?: string;
- id?: string;
- className?: string;
- disabled?: boolean;
-}) {
- const [open, setOpen] = useState(false);
- const [search, setSearch] = useState("");
- const [pickedLabel, setPickedLabel] = useState<string | null>(null);
-
- const serverMode = !options;
- const query = useDebouncedValue(search, 250).trim();
-
- const capabilitiesQuery = useQuery({
- enabled: serverMode && !!projectId && open,
- queryFn: () =>
- apiClient.capabilities.capabilitiesList({
- ordering: "name",
- pageSize: 100,
- project: projectId!,
- search: query || undefined,
- }),
- queryKey: ["capability-combobox", projectId, query],
- });
-
- const fetched: CapabilityComboboxOption[] = (capabilitiesQuery.data?.results ?? [])
- .filter((a) => !excludeIds?.includes(a.id))
- .map((a) => ({
- hint: capabilityHint(a),
- label: a.name || a.slug,
- value: a.id,
- }));
-
- const items = options ?? fetched;
- const displayLabel = value
- ? (items.find((o) => o.value === value)?.label ?? pickedLabel ?? valueLabel ?? null)
- : null;
-
- const handleSelect = (option: CapabilityComboboxOption) => {
- onChange(option.value, option);
- setPickedLabel(option.label);
- setOpen(false);
- setSearch("");
- };
-
- return (
- <Popover onOpenChange={setOpen} open={open}>
- <PopoverTrigger asChild>
- <button
- aria-expanded={open}
- aria-label={ariaLabel}
- className={cn(
- "flex h-8 w-fit items-center justify-between gap-2 rounded-sm border border-transparent bg-control px-3 text-sm whitespace-nowrap transition-[color,box-shadow] outline-none",
- "hover:bg-control-hover focus-visible:ring-2 focus-visible:ring-ring/60 disabled:cursor-not-allowed disabled:opacity-50",
- className
- )}
- disabled={disabled}
- id={id}
- role="combobox"
- type="button"
- >
- <span className={cn("truncate", !displayLabel && "text-muted-foreground")}>
- {displayLabel ?? placeholder}
- </span>
- <Icon.chevronDown className="size-4 shrink-0 text-muted-foreground opacity-50" />
- </button>
- </PopoverTrigger>
- <PopoverContent align="start" className="w-(--radix-popover-trigger-width) min-w-64 p-0">
- <Command shouldFilter={!serverMode}>
- <CommandInput
- className="h-9"
- onValueChange={setSearch}
- placeholder={searchPlaceholder}
- value={search}
- />
- <CommandList>
- <CommandEmpty>
- {serverMode && capabilitiesQuery.isLoading ? "Loading…" : "No capabilities found."}
- </CommandEmpty>
- <CommandGroup>
- {items.map((option) => (
- <CommandItem
- key={option.value}
- onSelect={() => handleSelect(option)}
- value={serverMode ? option.value : `${option.label} ${option.value}`}
- >
- <Icon.success
- className={cn("size-3.5", value === option.value ? "opacity-100" : "opacity-0")}
- />
- <span className="min-w-0 flex-1 truncate">{option.label}</span>
- {option.hint ? (
- <span className="shrink-0 text-xs text-muted-foreground">{option.hint}</span>
- ) : null}
- </CommandItem>
- ))}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/frontend/src/components/datasets/attachment.tsx b/frontend/src/components/datasets/attachment.tsx
index 2ff4f2cb..dda4be83 100644
--- a/frontend/src/components/datasets/attachment.tsx
+++ b/frontend/src/components/datasets/attachment.tsx
@@ -24,6 +24,7 @@ export function Attachment({
disabled,
onRemove,
onRetry,
+ onPreview,
detailed = false,
compact = false,
}: {
@@ -31,6 +32,8 @@ export function Attachment({
disabled: boolean;
onRemove: () => void;
onRetry: () => void;
+ /** Opens the file's import review in place of the quick-look popover. */
+ onPreview?: () => void;
detailed?: boolean;
compact?: boolean;
}) {
@@ -85,7 +88,12 @@ export function Attachment({
layout={!reduce}
transition={{ duration: reduce ? 0 : 0.2, ease: [0.4, 0, 0.2, 1] }}
>
- <Popover>
+ <Popover
+ onOpenChange={(open) => {
+ if (open) onPreview?.();
+ }}
+ open={onPreview ? false : undefined}
+ >
<PopoverTrigger
aria-describedby={statusId}
aria-label={`View ${entry.file.name}`}
diff --git a/frontend/src/components/datasets/dataset-file-upload.tsx b/frontend/src/components/datasets/dataset-file-upload.tsx
index 1e4f67fe..76127201 100644
--- a/frontend/src/components/datasets/dataset-file-upload.tsx
+++ b/frontend/src/components/datasets/dataset-file-upload.tsx
@@ -1,13 +1,9 @@
-import { useRef, useState } from "react";
+import { useRef } from "react";
-import { AnimatePresence } from "motion/react";
-
-import { Attachment } from "@/components/datasets/attachment";
-import { Button } from "@/components/ui/button";
-import { Icon } from "@/components/ui/icons";
+import { FileImport, FileImportPicker, IMPORT_ACCEPT } from "@/components/datasets/file-import";
import type { useDatasetUploads } from "@/hooks/use-uploads";
-import { cn } from "@/lib/utils";
+/** Each chosen file as its review card, then "Add files"; with none, the import drop zone. */
export function DatasetFileUpload({
upload,
busy = false,
@@ -17,9 +13,8 @@ export function DatasetFileUpload({
busy?: boolean;
onError: (message: string | null) => void;
}) {
- const [dragging, setDragging] = useState(false);
- const fileInputRef = useRef<HTMLInputElement>(null);
- const addFiles = (files: File[]) => {
+ const input = useRef<HTMLInputElement>(null);
+ const add = (files: File[]) => {
if (busy) return;
if (upload.files.length + files.length > 100) {
onError("Choose up to 100 files.");
@@ -28,77 +23,44 @@ export function DatasetFileUpload({
onError(null);
upload.add(files);
};
+ if (upload.files.length === 0)
+ return <FileImportPicker disabled={busy} onError={onError} onFiles={add} />;
return (
- <section
- aria-label="Upload files"
- className={cn(
- "flex flex-col gap-3 rounded-md border border-dashed p-3 transition-colors",
- dragging ? "border-primary bg-accent" : "border-border"
- )}
- onDragLeave={(e) => {
- if (!e.currentTarget.contains(e.relatedTarget as Node | null)) setDragging(false);
- }}
- onDragOver={(e) => {
- e.preventDefault();
- e.stopPropagation();
- if (!busy) setDragging(true);
- }}
- onDrop={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDragging(false);
- addFiles(Array.from(e.dataTransfer.files));
- }}
- >
- {upload.files.length > 0 && (
- <ul aria-label="Selected files" className="flex flex-wrap gap-2">
- <AnimatePresence initial={false}>
- {upload.files.map((entry) => (
- <Attachment
- detailed
- disabled={busy}
- entry={entry}
- key={entry.id}
- onRemove={() => upload.remove(entry.id)}
- onRetry={() => upload.retry(entry)}
- />
- ))}
- </AnimatePresence>
- </ul>
- )}
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="flex min-w-0 flex-col gap-1">
- <p className="text-sm">
- {upload.files.length ? "Drop more files here" : "Drop files here"}
- </p>
- <p className="text-xs text-muted-foreground">
- Tables, documents, PNG, JPEG or WebP images
- </p>
- </div>
- <input
- accept=".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp"
- aria-label="Choose dataset files"
- className="hidden"
- disabled={busy}
- multiple
- onChange={(e) => {
- addFiles(Array.from(e.target.files ?? []));
- e.target.value = "";
- }}
- ref={fileInputRef}
- type="file"
+ <div className="flex min-w-0 flex-col gap-3">
+ {upload.files.map((entry) => (
+ <FileImport
+ busy={busy}
+ entry={entry}
+ key={entry.id}
+ onContinue={() => upload.confirm(entry.id)}
+ onRead={(options) => void upload.inspect(entry, options)}
+ onRemove={() => upload.remove(entry.id)}
+ onRetry={() =>
+ entry.uploadId ? void upload.inspect(entry, entry.options ?? {}) : upload.retry(entry)
+ }
/>
- <Button
- disabled={busy}
- onClick={() => fileInputRef.current?.click()}
- size="sm"
- type="button"
- variant="secondary"
- >
- <Icon.add />
- {upload.files.length ? "Add files" : "Choose files"}
- </Button>
- </div>
- </section>
+ ))}
+ <input
+ accept={IMPORT_ACCEPT}
+ aria-label="Choose dataset files"
+ className="hidden"
+ disabled={busy}
+ multiple
+ onChange={(event) => {
+ add(Array.from(event.target.files ?? []));
+ event.target.value = "";
+ }}
+ ref={input}
+ type="file"
+ />
+ <button
+ className="self-start text-xs text-muted-foreground underline underline-offset-2"
+ disabled={busy}
+ onClick={() => input.current?.click()}
+ type="button"
+ >
+ Add files
+ </button>
+ </div>
);
}
diff --git a/frontend/src/components/datasets/file-import.test.tsx b/frontend/src/components/datasets/file-import.test.tsx
new file mode 100644
index 00000000..2b3236f4
--- /dev/null
+++ b/frontend/src/components/datasets/file-import.test.tsx
@@ -0,0 +1,70 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { cleanup, fireEvent, render, screen, within } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import type { DatasetUpload } from "@/hooks/use-uploads";
+import { FileImport } from "./file-import";
+
+afterEach(cleanup);
+
+function entry(name: string, patch: Partial<DatasetUpload> = {}): DatasetUpload {
+ return {
+ file: new File(["a;b\n1;2\n"], name),
+ id: name,
+ inspection: {
+ bytes: 8,
+ columns: ["a", "b"],
+ filename: name,
+ options: { delimiter: "semicolon", encoding: "utf-8-sig", header: true },
+ preview: [{ a: "1", b: "2" }],
+ rows: 1,
+ sheets: [],
+ },
+ percent: 100,
+ reviewed: false,
+ rows: 1,
+ status: "ready",
+ uploadId: "upload",
+ ...patch,
+ };
+}
+
+function show(upload: DatasetUpload) {
+ const handlers = { onContinue: vi.fn(), onRead: vi.fn(), onRemove: vi.fn(), onRetry: vi.fn() };
+ render(<FileImport entry={upload} {...handlers} />);
+ return handlers;
+}
+
+it("previews the first rows and is continued once", () => {
+ const handlers = show(entry("menu.csv"));
+ const card = screen.getByRole("region", { name: "Import menu.csv" });
+ expect(within(card).getByRole("columnheader", { name: "a" })).toBeTruthy();
+ expect(within(card).getByText("1 rows")).toBeTruthy();
+ fireEvent.click(within(card).getByRole("button", { name: "Continue" }));
+ expect(handlers.onContinue).toHaveBeenCalledOnce();
+});
+
+it("rereads a delimited file with the chosen separator, keeping its other options", () => {
+ const handlers = show(entry("menu.csv"));
+ fireEvent.click(screen.getByRole("button", { name: "How the file is read: Semicolon · UTF-8" }));
+ fireEvent.click(screen.getByRole("radio", { name: "Pipe" }));
+ expect(handlers.onRead).toHaveBeenCalledWith({
+ delimiter: "pipe",
+ encoding: "utf-8-sig",
+ header: true,
+ });
+});
+
+it("reads every sheet of a workbook until one sheet is chosen", () => {
+ const book = entry("book.xlsx");
+ book.inspection = { ...book.inspection!, options: { header: true }, sheets: ["orders", "notes"] };
+ show(book);
+ expect(screen.getByRole("button", { name: "How the file is read: All sheets" })).toBeTruthy();
+});
+
+it("shows Ready instead of Continue once reviewed", () => {
+ show(entry("menu.csv", { reviewed: true }));
+ expect(screen.getByText("Ready")).toBeTruthy();
+ expect(screen.queryByRole("button", { name: "Continue" })).toBeNull();
+});
diff --git a/frontend/src/components/datasets/file-import.tsx b/frontend/src/components/datasets/file-import.tsx
new file mode 100644
index 00000000..e529ea3e
--- /dev/null
+++ b/frontend/src/components/datasets/file-import.tsx
@@ -0,0 +1,465 @@
+import { Fragment, type KeyboardEvent, useRef, useState } from "react";
+
+import { AnimatePresence, motion, useReducedMotion } from "motion/react";
+
+import { FileTypeIcon } from "@/components/file-type-icon";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icons";
+import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { Spinner } from "@/components/ui/spinner";
+import { Switch } from "@/components/ui/switch";
+import type { DatasetUpload } from "@/hooks/use-uploads";
+import { formatBytes } from "@/lib/formatters";
+import { cn } from "@/lib/utils";
+import type { DelimiterEnum, EncodingEnum, UploadReadOptionsRequest } from "@/openapi";
+
+export const IMPORT_ACCEPT =
+ ".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp";
+
+const SEPARATORS: { value: DelimiterEnum; label: string; mark: string }[] = [
+ { label: "Comma", mark: ",", value: "comma" },
+ { label: "Tab", mark: "Tab", value: "tab" },
+ { label: "Semicolon", mark: ";", value: "semicolon" },
+ { label: "Pipe", mark: "|", value: "pipe" },
+];
+const ENCODINGS: { value: EncodingEnum; label: string }[] = [
+ { label: "UTF-8", value: "utf-8-sig" },
+ { label: "UTF-16", value: "utf-16" },
+ { label: "Windows-1252", value: "windows-1252" },
+];
+// Radix Select needs a non-empty value for the choice that sends no sheet.
+const EVERY_SHEET = "*";
+
+/** One file's review: its first rows as the options read them, how it is read, and Continue. */
+export function FileImport({
+ entry,
+ busy = false,
+ onRemove,
+ onClose,
+ onRetry,
+ onContinue,
+ onRead,
+}: {
+ entry: DatasetUpload;
+ busy?: boolean;
+ onRemove: () => void;
+ onClose?: () => void;
+ onRetry: () => void;
+ onContinue: () => void;
+ onRead: (options: UploadReadOptionsRequest) => void;
+}) {
+ const reduce = useReducedMotion();
+ const inspection = entry.inspection;
+ const options = entry.options ?? inspection?.options ?? {};
+ const delimited = /\.(csv|tsv)(\.gz)?$/i.test(entry.file.name);
+ const workbook = /\.xlsx$/i.test(entry.file.name);
+ const working =
+ entry.status === "queued" || entry.status === "uploading" || entry.status === "counting";
+ const locked = busy || working;
+ const columns = inspection?.columns ?? [];
+ const rows = (inspection?.preview ?? []).slice(0, 5);
+ const sheets = inspection?.sheets ?? [];
+ const separator = SEPARATORS.find((item) => item.value === (options.delimiter ?? "comma"));
+ const encoding = ENCODINGS.find((item) => item.value === (options.encoding ?? "utf-8-sig"));
+ const reading = workbook
+ ? (options.sheet ?? (sheets.length > 1 ? "All sheets" : (sheets[0] ?? "Excel")))
+ : `${separator?.label ?? "Comma"} · ${encoding?.label ?? "UTF-8"}`;
+ const read = (patch: UploadReadOptionsRequest) => onRead({ ...options, ...patch });
+
+ return (
+ <section
+ aria-busy={working}
+ aria-label={`Import ${entry.file.name}`}
+ className="flex min-w-0 flex-col gap-3 text-foreground"
+ >
+ <header className="flex min-w-0 items-start gap-2">
+ <span className="inline-flex size-6 flex-none items-center justify-center rounded-md bg-info/10 text-info">
+ <FileTypeIcon className="size-3.5" filename={entry.file.name} />
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 pt-1">
+ <p className="truncate text-sm leading-4 font-medium">{entry.file.name}</p>
+ <p className="truncate text-xs leading-4 text-muted-foreground tabular-nums">
+ {[
+ entry.rows != null && `${entry.rows.toLocaleString()} rows`,
+ columns.length > 0 && `${columns.length.toLocaleString()} columns shown`,
+ formatBytes(entry.file.size),
+ ]
+ .filter(Boolean)
+ .map((fact, index) => (
+ <Fragment key={String(fact)}>
+ {index > 0 && ", "}
+ <span>{fact}</span>
+ </Fragment>
+ ))}
+ </p>
+ </div>
+ <Button
+ aria-label={onClose ? "Close" : `Remove ${entry.file.name}`}
+ className="text-muted-foreground"
+ disabled={busy}
+ onClick={onClose ?? onRemove}
+ size="icon-xs"
+ type="button"
+ variant="ghost"
+ >
+ <Icon.close className="size-3.5" />
+ </Button>
+ </header>
+ <AnimatePresence initial={false} mode="wait">
+ {columns.length > 0 ? (
+ <motion.div
+ animate={{ opacity: 1, y: 0 }}
+ className={cn(
+ "min-w-0 overflow-hidden rounded-sm bg-background",
+ working && "opacity-50"
+ )}
+ initial={{ opacity: 0, y: reduce ? 0 : 4 }}
+ key="preview"
+ >
+ <div className="overflow-x-auto overscroll-x-contain [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">
+ <table className="w-max min-w-full border-separate border-spacing-0 text-left text-xs leading-4">
+ <caption className="sr-only">
+ The first {rows.length} rows of {entry.file.name}
+ </caption>
+ <thead>
+ <tr>
+ {columns.map((column) => (
+ <th
+ className="max-w-48 truncate px-2.5 pt-2 pb-1.5 font-medium whitespace-nowrap"
+ key={column}
+ scope="col"
+ >
+ {column}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row, index) => (
+ <tr key={index}>
+ {columns.map((column) => (
+ <td
+ className="max-w-48 truncate border-t border-border/60 px-2.5 py-1.5 whitespace-nowrap text-muted-foreground tabular-nums"
+ key={column}
+ >
+ {row[column] ?? ""}
+ </td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </motion.div>
+ ) : working ? (
+ <motion.div
+ animate={{ opacity: 1 }}
+ className="flex min-h-36 items-center justify-center gap-2 rounded-sm bg-background text-sm text-muted-foreground"
+ initial={{ opacity: 0 }}
+ key="working"
+ >
+ <Spinner size="sm" />
+ {entry.status === "uploading"
+ ? `Uploading ${entry.percent}%`
+ : entry.status === "queued"
+ ? "Queued"
+ : "Reading file"}
+ </motion.div>
+ ) : entry.status === "error" ? null : (
+ <p className="m-0 text-xs text-muted-foreground" key="later">
+ Preview available after extraction.
+ </p>
+ )}
+ </AnimatePresence>
+ {entry.error && (
+ <p className="m-0 px-0.5 text-xs leading-4 text-destructive" role="alert">
+ {entry.error}
+ </p>
+ )}
+ <footer className="-mt-0.5 flex min-h-6 min-w-0 items-center justify-between gap-2">
+ {(delimited || workbook) && entry.uploadId ? (
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ aria-label={`How the file is read: ${reading}`}
+ className="inline-flex h-6 min-w-0 items-center gap-1.5 rounded-sm pr-1.5 pl-2 text-xs font-medium text-muted-foreground hover:bg-foreground/6 hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
+ type="button"
+ >
+ <span className="truncate">{reading}</span>
+ <Icon.chevronDown className="size-3 shrink-0" />
+ </button>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ aria-label="File settings"
+ className="flex w-72 flex-col gap-2.5 p-3"
+ sideOffset={6}
+ >
+ {delimited && (
+ <>
+ <Setting label="Separator">
+ <SeparatorPicker
+ disabled={locked}
+ onChange={(delimiter) => read({ delimiter })}
+ value={options.delimiter ?? "comma"}
+ />
+ </Setting>
+ <Setting label="Encoding">
+ <Select
+ disabled={locked}
+ onValueChange={(value) => read({ encoding: value as EncodingEnum })}
+ value={options.encoding ?? "utf-8-sig"}
+ >
+ <SelectTrigger aria-label="Encoding" size="xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {ENCODINGS.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Setting>
+ </>
+ )}
+ {workbook && sheets.length > 1 && (
+ <Setting label="Sheet">
+ <Select
+ disabled={locked}
+ onValueChange={(value) => {
+ const { sheet: _, ...rest } = options;
+ onRead(value === EVERY_SHEET ? rest : { ...rest, sheet: value });
+ }}
+ value={options.sheet ?? EVERY_SHEET}
+ >
+ <SelectTrigger aria-label="Sheet" size="xs">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value={EVERY_SHEET}>All sheets</SelectItem>
+ {sheets.map((sheet) => (
+ <SelectItem key={sheet} value={sheet}>
+ {sheet}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </Setting>
+ )}
+ <Setting label="Headers">
+ <span className="flex flex-1 items-center justify-between text-xs">
+ First row
+ <Switch
+ aria-label="First row is headers"
+ checked={options.header ?? true}
+ disabled={locked}
+ onCheckedChange={(header) => read({ header })}
+ size="sm"
+ />
+ </span>
+ </Setting>
+ </PopoverContent>
+ </Popover>
+ ) : (
+ <span />
+ )}
+ {entry.status === "error" ? (
+ <Button disabled={busy} onClick={onRetry} size="xs" type="button">
+ Retry
+ </Button>
+ ) : entry.reviewed ? (
+ <span className="text-xs text-success">Ready</span>
+ ) : (
+ <Button disabled={locked} onClick={onContinue} size="xs" type="button">
+ {working && <Spinner size="sm" />}
+ Continue
+ </Button>
+ )}
+ </footer>
+ </section>
+ );
+}
+
+function Setting({ label, children }: { label: string; children: React.ReactNode }) {
+ return (
+ <div className="flex items-center gap-2">
+ <span className="w-20 flex-none text-xs text-muted-foreground">{label}</span>
+ {children}
+ </div>
+ );
+}
+
+/** A four-way segmented control; arrow keys move the choice like a radio group. */
+function SeparatorPicker({
+ value,
+ disabled,
+ onChange,
+}: {
+ value: DelimiterEnum;
+ disabled: boolean;
+ onChange: (value: DelimiterEnum) => void;
+}) {
+ const index = Math.max(
+ 0,
+ SEPARATORS.findIndex((item) => item.value === value)
+ );
+ const step = (event: KeyboardEvent<HTMLButtonElement>) => {
+ const move = { ArrowLeft: -1, ArrowRight: 1 }[event.key];
+ if (!move) return;
+ event.preventDefault();
+ const next = (index + move + SEPARATORS.length) % SEPARATORS.length;
+ onChange(SEPARATORS[next].value);
+ event.currentTarget.parentElement?.querySelectorAll<HTMLElement>("[role=radio]")[next]?.focus();
+ };
+ return (
+ <div
+ aria-label="Separator"
+ className="relative grid h-6 flex-1 grid-cols-4 rounded-sm bg-foreground/6 p-0.5"
+ role="radiogroup"
+ >
+ <span
+ aria-hidden
+ className="absolute inset-y-0.5 left-0.5 w-[calc(25%-1px)] rounded-sm bg-card transition-transform duration-200 motion-reduce:transition-none"
+ style={{ transform: `translateX(${index * 100}%)` }}
+ />
+ {SEPARATORS.map((item) => {
+ const checked = item.value === value;
+ return (
+ <button
+ aria-checked={checked}
+ aria-label={item.label}
+ className={cn(
+ "relative rounded-sm leading-none font-medium focus-visible:ring-2 focus-visible:ring-ring",
+ item.value === "tab" ? "text-xs" : "font-mono text-sm",
+ checked ? "text-foreground" : "text-muted-foreground"
+ )}
+ disabled={disabled}
+ key={item.value}
+ onClick={() => onChange(item.value)}
+ onKeyDown={step}
+ role="radio"
+ tabIndex={checked ? 0 : -1}
+ type="button"
+ >
+ {item.mark}
+ </button>
+ );
+ })}
+ </div>
+ );
+}
+
+/** The empty state: drop files, choose them, or paste cells as a table. */
+export function FileImportPicker({
+ disabled = false,
+ onFiles,
+ onError,
+}: {
+ disabled?: boolean;
+ onFiles: (files: File[]) => void;
+ onError: (message: string) => void;
+}) {
+ const input = useRef<HTMLInputElement>(null);
+ // dragenter and dragleave fire for every child, so the hover state counts them.
+ const depth = useRef(0);
+ const [dragging, setDragging] = useState(false);
+ return (
+ <section
+ aria-label="Import"
+ className="flex min-w-0 flex-col gap-3"
+ onDragEnter={(event) => {
+ event.preventDefault();
+ if (disabled) return;
+ depth.current += 1;
+ setDragging(true);
+ }}
+ onDragLeave={() => {
+ depth.current = Math.max(0, depth.current - 1);
+ if (depth.current === 0) setDragging(false);
+ }}
+ onDragOver={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ }}
+ onDrop={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ depth.current = 0;
+ setDragging(false);
+ if (disabled) return;
+ const folder = Array.from(event.dataTransfer.items).some(
+ (item) => item.webkitGetAsEntry?.()?.isDirectory
+ );
+ if (folder) onError("Drop files, not folders.");
+ else onFiles(Array.from(event.dataTransfer.files));
+ }}
+ onPaste={(event) => {
+ if (
+ disabled ||
+ event.target instanceof HTMLInputElement ||
+ event.target instanceof HTMLTextAreaElement
+ )
+ return;
+ const text = event.clipboardData.getData("text/plain");
+ if (!text.trim()) return;
+ event.preventDefault();
+ const name = text.includes("\t") ? "Pasted cells.tsv" : "Pasted cells.csv";
+ onFiles([new File([text], name, { type: "text/plain" })]);
+ }}
+ >
+ <div className="flex items-center gap-2">
+ <span className="inline-flex size-6 items-center justify-center rounded-md bg-info/10 text-info">
+ <Icon.upload className="size-3.5" />
+ </span>
+ <span className="text-sm font-medium">Import</span>
+ </div>
+ <input
+ accept={IMPORT_ACCEPT}
+ aria-label="Choose dataset files"
+ className="hidden"
+ disabled={disabled}
+ multiple
+ onChange={(event) => {
+ onFiles(Array.from(event.target.files ?? []));
+ event.target.value = "";
+ }}
+ ref={input}
+ type="file"
+ />
+ <button
+ className={cn(
+ "group flex min-h-36 w-full cursor-pointer flex-col items-center justify-center gap-1 rounded-sm bg-background px-4 py-6 text-center outline-dashed outline-transparent transition-colors hover:bg-muted focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50",
+ dragging && "bg-info/10 outline-info"
+ )}
+ disabled={disabled}
+ onClick={() => input.current?.click()}
+ type="button"
+ >
+ <span className="mb-2 inline-flex size-8 items-center justify-center rounded-sm border border-border bg-card text-muted-foreground">
+ <Icon.upload className="size-4" />
+ </span>
+ <span className="text-sm font-medium">
+ {dragging ? (
+ "Drop to import"
+ ) : (
+ <>
+ Drop data, or <span className="underline underline-offset-2">choose a file</span>
+ </>
+ )}
+ </span>
+ <span className="text-xs leading-4 text-muted-foreground">
+ Tables, documents or images. You can paste cells too.
+ </span>
+ </button>
+ </section>
+ );
+}
diff --git a/frontend/src/components/datasets/new-dataset-dialog.test.tsx b/frontend/src/components/datasets/new-dataset-dialog.test.tsx
index 3f382abb..fe6c9d6c 100644
--- a/frontend/src/components/datasets/new-dataset-dialog.test.tsx
+++ b/frontend/src/components/datasets/new-dataset-dialog.test.tsx
@@ -59,6 +59,13 @@ function choose(label: string, option: string) {
fireEvent.click(screen.getByRole("option", { name: option }));
}
+async function review(filename: string) {
+ const card = await screen.findByRole("region", { name: `Import ${filename}` });
+ const button = within(card).getByRole("button", { name: "Continue" }) as HTMLButtonElement;
+ await waitFor(() => expect(button.disabled).toBe(false));
+ fireEvent.click(button);
+}
+
describe("dataset file dialog", () => {
it("creates before an intent is chosen and resets the choice when reopened", async () => {
const props = {
@@ -67,7 +74,7 @@ describe("dataset file dialog", () => {
projectId: "project",
};
const view = render(<NewDatasetDialog {...props} open />);
- await within(screen.getByRole("list", { name: "Selected files" })).findByText("7 rows");
+ await review("first.csv");
const create = screen.getByRole("button", { name: "Create dataset" }) as HTMLButtonElement;
expect(create.disabled).toBe(false);
expect(screen.getByRole("combobox", { name: "Intent" }).textContent).toBe("Not set");
@@ -76,10 +83,12 @@ describe("dataset file dialog", () => {
expect(create.disabled).toBe(false);
view.rerender(<NewDatasetDialog {...props} open={false} />);
view.rerender(<NewDatasetDialog {...props} open />);
+ expect(screen.queryByRole("button", { name: "Create dataset" })).toBeNull();
+ await review("first.csv");
expect(screen.getByRole("combobox", { name: "Intent" }).textContent).toBe("Not set");
expect(
(screen.getByRole("button", { name: "Create dataset" }) as HTMLButtonElement).disabled
- ).toBe(true);
+ ).toBe(false);
});
it.each([
@@ -95,7 +104,7 @@ describe("dataset file dialog", () => {
projectId="project"
/>
);
- await within(screen.getByRole("list", { name: "Selected files" })).findByText("7 rows");
+ await review("first.csv");
choose("Capability", "None");
choose("Intent", purpose);
fireEvent.click(
@@ -115,18 +124,16 @@ describe("dataset file dialog", () => {
const input = screen.getByLabelText("Choose dataset files") as HTMLInputElement;
expect(input.multiple).toBe(true);
fireEvent.change(input, { target: { files: [new File(["a"], "first.csv")] } });
- await within(screen.getByRole("list", { name: "Selected files" })).findByText("7 rows");
- fireEvent.change(input, { target: { files: [new File(["bb"], "second.jsonl")] } });
- await screen.findByText("15 rows");
- const list = screen.getByRole("list", { name: "Selected files" });
- expect(within(list).getAllByRole("listitem")).toHaveLength(2);
- expect(within(list).getByText("CSV")).toBeTruthy();
- expect(within(list).getByText("JSONL")).toBeTruthy();
- expect(within(list).getByText("2 B")).toBeTruthy();
+ await review("first.csv");
+ fireEvent.change(screen.getByLabelText("Choose dataset files"), {
+ target: { files: [new File(["bb"], "second.jsonl")] },
+ });
+ await review("second.jsonl");
+ expect(screen.getByRole("region", { name: "Import first.csv" })).toBeTruthy();
+ expect(screen.getByRole("region", { name: "Import second.jsonl" })).toBeTruthy();
fireEvent.change(screen.getByLabelText("Dataset name"), { target: { value: "Support data" } });
fireEvent.click(screen.getByRole("button", { name: "Remove first.csv" }));
- // The tile leaves through its exit animation.
- await waitFor(() => expect(within(list).queryByText("first.csv")).toBeNull());
+ expect(screen.queryByRole("region", { name: "Import first.csv" })).toBeNull();
expect((screen.getByLabelText("Dataset name") as HTMLInputElement).value).toBe("Support data");
choose("Capability", "Support");
choose("Intent", "Eval");
@@ -152,7 +159,8 @@ describe("dataset file dialog", () => {
projectId="project"
/>
);
- await screen.findByText("15 rows");
+ await review("first.csv");
+ await review("second.jsonl");
expect(screen.queryByRole("spinbutton", { name: "Data split" })).toBeNull();
choose("Intent", "Train + eval");
expect(screen.queryByLabelText("Group columns")).toBeNull();
@@ -191,7 +199,7 @@ describe("dataset file dialog", () => {
projectId="project"
/>
);
- await screen.findByText("1 row");
+ await review("one.csv");
choose("Intent", "Train + eval");
expect(screen.getByRole("alert").textContent).toContain("At least two rows");
const create = screen.getByRole("button", { name: "Create datasets" }) as HTMLButtonElement;
diff --git a/frontend/src/components/datasets/new-dataset-dialog.tsx b/frontend/src/components/datasets/new-dataset-dialog.tsx
index afe8f3f5..483154cd 100644
--- a/frontend/src/components/datasets/new-dataset-dialog.tsx
+++ b/frontend/src/components/datasets/new-dataset-dialog.tsx
@@ -140,7 +140,7 @@ export function NewDatasetDialog({
if (!upload.files.length) return { hint: "Choose files" };
if (upload.files.some((file) => file.status === "error"))
return { hint: "Remove or retry files with errors" };
- if (upload.files.some((file) => file.status !== "ready"))
+ if (upload.files.some((file) => file.status !== "ready" || file.reviewed !== true))
return { hint: "Uploading and counting rows" };
return {
rows: upload.files.every((file) => file.rows != null)
@@ -233,6 +233,20 @@ export function NewDatasetDialog({
}
};
+ // Files are reviewed one card each before the rest of the form shows.
+ if (sourceType === "file" && upload.files.some((file) => file.reviewed !== true)) {
+ return (
+ <Dialog onOpenChange={onOpenChange} open={open}>
+ <DialogContent className="overflow-y-auto" showCloseButton={false} size="md">
+ <DialogHeader className="sr-only">
+ <DialogTitle>Import data</DialogTitle>
+ </DialogHeader>
+ <DatasetFileUpload busy={busy} onError={setError} upload={upload} />
+ <DismissibleAlert message={error} variant="destructive" />
+ </DialogContent>
+ </Dialog>
+ );
+ }
return (
<Dialog onOpenChange={(next) => !busy && onOpenChange(next)} open={open}>
<DialogContent size="md">
diff --git a/frontend/src/components/datasets/notebook/source.tsx b/frontend/src/components/datasets/notebook/source.tsx
index bf333f13..20131974 100644
--- a/frontend/src/components/datasets/notebook/source.tsx
+++ b/frontend/src/components/datasets/notebook/source.tsx
@@ -1,10 +1,8 @@
-import { type ReactNode, useRef, useState } from "react";
-
-import { AnimatePresence } from "motion/react";
+import { type ReactNode, useState } from "react";
import apiClient from "@/client";
-import { Attachment } from "@/components/datasets/attachment";
import { SOURCE_KIND_LABEL } from "@/components/datasets/badges";
+import { DatasetFileUpload } from "@/components/datasets/dataset-file-upload";
import { FileTypeIcon } from "@/components/file-type-icon";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
@@ -153,20 +151,12 @@ export function SourceLanding({
landingStatus?: string;
actions?: ReactNode;
}) {
- const input = useRef<HTMLInputElement>(null);
const upload = useDatasetUploads();
const attach = useAttachDatasetSourceMutation(datasetId);
- const [error, setError] = useState("");
- const ready = upload.files.length > 0 && upload.files.every((file) => file.status === "ready");
- const add = (files: File[]) => {
- if (attach.isPending) return;
- if (upload.files.length + files.length > 100) {
- setError("Choose up to 100 files.");
- return;
- }
- setError("");
- upload.add(files);
- };
+ const [error, setError] = useState<string | null>(null);
+ const ready =
+ upload.files.length > 0 &&
+ upload.files.every((file) => file.status === "ready" && file.reviewed === true);
return (
<article aria-label="Source" className="m-3 rounded-sm border border-border">
<div className="flex flex-wrap items-center gap-2 border-b border-border/70 px-3 py-2 text-xs">
@@ -174,14 +164,7 @@ export function SourceLanding({
<span className="mr-auto">Source</span>
{actions}
</div>
- <div
- className="space-y-4 px-3 py-4"
- onDragOver={(event) => event.preventDefault()}
- onDrop={(event) => {
- event.preventDefault();
- add(Array.from(event.dataTransfer.files));
- }}
- >
+ <div className="space-y-4 px-3 py-4">
{brief && (
<p className="max-w-prose whitespace-pre-wrap text-sm leading-relaxed">{brief}</p>
)}
@@ -192,58 +175,18 @@ export function SourceLanding({
</p>
) : (
<>
- <p className="text-xs text-muted-foreground">
- Drop tables, documents, PNG, JPEG or WebP images here.
- </p>
+ <DatasetFileUpload busy={busy || attach.isPending} onError={setError} upload={upload} />
{upload.files.length > 0 && (
- <ul aria-label="Selected files" className="flex flex-wrap gap-2">
- <AnimatePresence initial={false}>
- {upload.files.map((file) => (
- <Attachment
- disabled={attach.isPending}
- entry={file}
- key={file.id}
- onRemove={() => upload.remove(file.id)}
- onRetry={() => upload.retry(file)}
- />
- ))}
- </AnimatePresence>
- </ul>
- )}
- <input
- accept=".csv,.tsv,.json,.jsonl,.ndjson,.parquet,.xlsx,.gz,.pdf,.docx,.md,.txt,.png,.jpg,.jpeg,.webp"
- aria-label="Attach source files"
- className="hidden"
- multiple
- onChange={(event) => {
- add(Array.from(event.target.files ?? []));
- event.target.value = "";
- }}
- ref={input}
- type="file"
- />
- <div className="flex gap-2">
<Button
- disabled={attach.isPending}
- onClick={() => input.current?.click()}
+ disabled={busy || !ready || attach.isPending}
+ onClick={() =>
+ attach.mutate({ uploads: upload.files.map((file) => file.uploadId!) })
+ }
size="sm"
- variant="secondary"
>
- <Icon.add />
- Add files
+ {attach.isPending && <Spinner className="size-3" />}Read source
</Button>
- {upload.files.length > 0 && (
- <Button
- disabled={busy || !ready || attach.isPending}
- onClick={() =>
- attach.mutate({ uploads: upload.files.map((file) => file.uploadId!) })
- }
- size="sm"
- >
- {attach.isPending && <Spinner className="size-3" />}Read source
- </Button>
- )}
- </div>
+ )}
</>
)}
{error && (
diff --git a/frontend/src/components/datasets/upload-review.tsx b/frontend/src/components/datasets/upload-review.tsx
new file mode 100644
index 00000000..e6c2b929
--- /dev/null
+++ b/frontend/src/components/datasets/upload-review.tsx
@@ -0,0 +1,62 @@
+import { useState } from "react";
+
+import { FileImport } from "@/components/datasets/file-import";
+import { Dialog, DialogBody, DialogContent, DialogTitle } from "@/components/ui/dialog";
+import type { useDatasetUploads } from "@/hooks/use-uploads";
+
+/** Opens on each file that is not reviewed yet, or on the one a person picked to look at. */
+export function UploadReview({
+ upload,
+ busy = false,
+}: {
+ upload: ReturnType<typeof useDatasetUploads>;
+ busy?: boolean;
+}) {
+ // Closing hides the review until another file arrives, not until the page reloads.
+ const [dismissed, setDismissed] = useState("");
+ const pending = upload.files.filter((file) => !file.reviewed);
+ const waiting = pending.map((file) => file.id).join(",");
+ const picked = upload.files.find((file) => file.id === upload.previewId);
+ const entry = picked ?? pending[0];
+ if (!entry) return null;
+ const close = () => {
+ setDismissed(waiting);
+ upload.setPreviewId(null);
+ };
+ return (
+ <Dialog
+ onOpenChange={(open) => {
+ if (!open) close();
+ }}
+ open={!!picked || (pending.length > 0 && dismissed !== waiting)}
+ >
+ <DialogContent
+ aria-describedby={undefined}
+ className="bg-card sm:w-xl"
+ showCloseButton={false}
+ >
+ <DialogTitle className="sr-only">Import data</DialogTitle>
+ <DialogBody className="p-3">
+ <FileImport
+ busy={busy}
+ entry={entry}
+ key={entry.id}
+ onClose={close}
+ onContinue={() => {
+ upload.confirm(entry.id);
+ upload.setPreviewId(null);
+ }}
+ onRead={(options) => void upload.inspect(entry, options)}
+ onRemove={() => {
+ upload.remove(entry.id);
+ upload.setPreviewId(null);
+ }}
+ onRetry={() =>
+ entry.uploadId ? void upload.inspect(entry, entry.options ?? {}) : upload.retry(entry)
+ }
+ />
+ </DialogBody>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/frontend/src/components/experiments/experiment-panel.test.tsx b/frontend/src/components/experiments/experiment-panel.test.tsx
new file mode 100644
index 00000000..1b6c220f
--- /dev/null
+++ b/frontend/src/components/experiments/experiment-panel.test.tsx
@@ -0,0 +1,57 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import type { ExperimentDetail } from "@/openapi";
+import { ProposalCards } from "./experiment-panel";
+
+const decide = vi.hoisted(() => vi.fn(() => Promise.resolve({})));
+vi.mock("@/client", () => ({ default: { experiments: { experimentsProposalsCreate: decide } } }));
+
+afterEach(cleanup);
+
+const detail = {
+ id: "experiment",
+ proposals: [
+ {
+ changes: [
+ {
+ after: 5,
+ afterLabel: null,
+ before: 3,
+ beforeLabel: null,
+ key: "epochs",
+ node: "train",
+ title: "Train",
+ },
+ ],
+ sequence: 7,
+ },
+ ],
+} as unknown as ExperimentDetail;
+
+it("dismisses a denied proposal and sends the reason to the agent", async () => {
+ const onDenied = vi.fn();
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <ProposalCards detail={detail} onDenied={onDenied} />
+ </QueryClientProvider>
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "Reason for denying" }), {
+ target: { value: "Keep three epochs." },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Deny" }));
+ await waitFor(() =>
+ expect(onDenied).toHaveBeenCalledWith(
+ "I denied your proposed change to Train. Keep three epochs."
+ )
+ );
+ expect(decide).toHaveBeenCalledWith({
+ id: "experiment",
+ proposalDecisionRequest: { apply: false },
+ sequence: "7",
+ });
+});
diff --git a/frontend/src/components/experiments/experiment-panel.tsx b/frontend/src/components/experiments/experiment-panel.tsx
index ddd4ba13..f42f770a 100644
--- a/frontend/src/components/experiments/experiment-panel.tsx
+++ b/frontend/src/components/experiments/experiment-panel.tsx
@@ -1,6 +1,7 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
import apiClient from "@/client";
+import { ApprovalCard } from "@/components/assistant/approval-card";
import { Button } from "@/components/ui/button";
import { CreditsAmount } from "@/components/ui/credits";
import { Icon } from "@/components/ui/icons";
@@ -16,11 +17,18 @@ const value = (raw: unknown) =>
? raw
: JSON.stringify(raw);
-/** The agent's change to settings a person chose: nothing changes until they apply it. */
-export function ProposalCards({ detail }: { detail: ExperimentDetail }) {
+/** The agent's change to settings a person chose: nothing changes until they approve it.
+ * Denying it with a reason sends the reason to the agent. */
+export function ProposalCards({
+ detail,
+ onDenied,
+}: {
+ detail: ExperimentDetail;
+ onDenied: (message: string) => void;
+}) {
const qc = useQueryClient();
const decide = useMutation({
- mutationFn: ({ proposal, apply }: { proposal: Proposal; apply: boolean }) =>
+ mutationFn: ({ proposal, apply }: { proposal: Proposal; apply: boolean; reason: string }) =>
apiClient.experiments.experimentsProposalsCreate({
id: detail.id,
proposalDecisionRequest: { apply },
@@ -28,44 +36,29 @@ export function ProposalCards({ detail }: { detail: ExperimentDetail }) {
}),
onError: (error) => notify.error(error, "The proposal could not be resolved"),
onSettled: () => invalidateExperiment(qc, detail.id),
+ onSuccess: (_, { apply, proposal, reason }) => {
+ if (apply || !reason) return;
+ const titles = [...new Set(proposal.changes.map((change) => change.title))].join(", ");
+ onDenied(`I denied your proposed change to ${titles}. ${reason}`);
+ },
});
if (!detail.proposals.length) return null;
return (
<div className="pointer-events-none absolute inset-x-0 top-3 z-10 flex flex-col items-center gap-2 px-14">
{detail.proposals.map((proposal) => (
- <section
- aria-label="The agent proposes a change"
- className="pointer-events-auto w-full max-w-lg space-y-2 rounded-md border border-border bg-card p-3 text-xs"
- key={proposal.sequence}
- >
- <p className="font-medium">The agent proposes a change to settings you chose</p>
- <ul className="space-y-1 text-muted-foreground">
- {proposal.changes.map((change) => (
- <li key={`${change.node}.${change.key}`}>
- <span className="text-foreground">{change.title}</span> · {change.key}:{" "}
- {change.beforeLabel ?? value(change.before)} →{" "}
- {change.afterLabel ?? value(change.after)}
- </li>
- ))}
- </ul>
- <div className="flex justify-end gap-2">
- <Button
- disabled={decide.isPending}
- onClick={() => decide.mutate({ apply: false, proposal })}
- size="xs"
- variant="secondary"
- >
- Dismiss
- </Button>
- <Button
- disabled={decide.isPending}
- onClick={() => decide.mutate({ apply: true, proposal })}
- size="xs"
- >
- Apply
- </Button>
- </div>
- </section>
+ <div className="pointer-events-auto flex w-full justify-center" key={proposal.sequence}>
+ <ApprovalCard
+ detail="The agent proposes a change to settings you chose."
+ disabled={decide.isPending}
+ fields={proposal.changes.map((change) => ({
+ label: `${change.title} · ${change.key}`,
+ value: `${change.beforeLabel ?? value(change.before)} → ${change.afterLabel ?? value(change.after)}`,
+ }))}
+ icon={<Icon.settings aria-hidden className="size-3.5" />}
+ onDecide={(apply, reason) => decide.mutateAsync({ apply, proposal, reason })}
+ title="Change settings"
+ />
+ </div>
))}
</div>
);
diff --git a/frontend/src/components/onboarding/data-project-form.test.tsx b/frontend/src/components/onboarding/data-project-form.test.tsx
index 9a6cdb42..81ff5513 100644
--- a/frontend/src/components/onboarding/data-project-form.test.tsx
+++ b/frontend/src/components/onboarding/data-project-form.test.tsx
@@ -30,6 +30,7 @@ beforeEach(() => {
file: new File(["input,output\na,b"], "source.csv"),
id: "file-1",
percent: 100,
+ reviewed: true,
rows: 1,
status: "ready",
uploadId: "upload-1",
diff --git a/frontend/src/components/onboarding/data-project-form.tsx b/frontend/src/components/onboarding/data-project-form.tsx
index 5a8c93ec..e00ac5f9 100644
--- a/frontend/src/components/onboarding/data-project-form.tsx
+++ b/frontend/src/components/onboarding/data-project-form.tsx
@@ -35,7 +35,9 @@ export function DataProjectForm({
const upload = useDatasetUploads();
const dataset = useCreateDatasetMutation();
const client = useQueryClient();
- const ready = upload.files.length > 0 && upload.files.every((file) => file.status === "ready");
+ const ready =
+ upload.files.length > 0 &&
+ upload.files.every((file) => file.status === "ready" && file.reviewed === true);
const create = useMutation({
mutationFn: async () => {
if ((!project && !projectRef.current && !name.trim()) || !ready)
diff --git a/frontend/src/components/traces/tool-detail.tsx b/frontend/src/components/traces/tool-detail.tsx
deleted file mode 100644
index 30ece860..00000000
--- a/frontend/src/components/traces/tool-detail.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-import { formatPayload } from "@/components/evaluations/payload-format";
-import type { IconName } from "@/components/ui/icons";
-import { cn } from "@/lib/utils";
-
-export const TOOL_ICONS: Record<string, IconName> = {
- add_cell: "code",
- diff: "diff",
- edit_cell: "code",
- inspect: "search",
- install: "tool",
- notebook_cell: "code",
- notebook_read: "code",
- notebook_write: "code",
- query: "search",
- set_intent: "target",
- status: "dataset",
- try_script: "code",
-};
-
-function IoBlock({ caption, text, failed }: { caption: string; text: string; failed?: boolean }) {
- return (
- <div className="space-y-0.5">
- <span className="text-xs font-medium text-muted-foreground">{caption}</span>
- <pre
- className={cn(
- "max-h-32 overflow-auto whitespace-pre-wrap font-mono text-xs leading-relaxed text-muted-foreground",
- failed && "text-destructive/90"
- )}
- >
- {text}
- </pre>
- </div>
- );
-}
-
-export function toolDetail(step: {
- summary?: string;
- preview?: string;
- ok?: boolean;
- input?: unknown;
- output?: unknown;
-}) {
- const inn = formatPayload(step.input) || formatPayload(step.summary);
- const out = formatPayload(step.output) || formatPayload(step.preview);
- if (!inn && !out) return undefined;
- return (
- <div className="space-y-1.5">
- {inn ? <IoBlock caption="In" text={inn} /> : null}
- {out ? <IoBlock caption="Out" failed={step.ok === false} text={out} /> : null}
- </div>
- );
-}
diff --git a/frontend/src/components/ui/button.tsx b/frontend/src/components/ui/button.tsx
index 5713d1a8..583d787f 100644
--- a/frontend/src/components/ui/button.tsx
+++ b/frontend/src/components/ui/button.tsx
@@ -38,6 +38,8 @@ const buttonVariants = cva(
outline: "border-border bg-transparent hover:bg-accent/50",
// The neutral control face — a fill, not an outline.
secondary: "bg-control text-foreground hover:bg-control-hover",
+ // The chat's send control: the one inverted face on a chat surface.
+ send: "bg-foreground text-background enabled:hover:bg-foreground/90 disabled:bg-control disabled:text-muted-foreground",
warning: "bg-warning text-warning-foreground hover:bg-warning/90",
},
},
diff --git a/frontend/src/components/ui/elbow-list.test.ts b/frontend/src/components/ui/elbow-list.test.ts
deleted file mode 100644
index 9e117740..00000000
--- a/frontend/src/components/ui/elbow-list.test.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-// covers: console-logic
-import { describe, expect, it } from "vitest";
-
-import { elbowHeightPx } from "./elbow-list";
-
-describe("elbowHeightPx", () => {
- it("keeps the shared start pad on the first row", () => {
- expect(elbowHeightPx(100, 100, 12)).toBe(12);
- });
-
- it("grows by the real distance between row centers", () => {
- // Expanded detail pushed the next header 48px further down.
- expect(elbowHeightPx(100, 100 + 32 + 48, 12)).toBe(92);
- });
-});
diff --git a/frontend/src/components/ui/elbow-list.tsx b/frontend/src/components/ui/elbow-list.tsx
deleted file mode 100644
index c58e48ea..00000000
--- a/frontend/src/components/ui/elbow-list.tsx
+++ /dev/null
@@ -1,285 +0,0 @@
-import { type CSSProperties, type ReactNode, useLayoutEffect, useRef, useState } from "react";
-
-import { Icon, type IconName } from "@/components/ui/icons";
-import { cn } from "@/lib/utils";
-
-/** Shared start sits this far above the first row center (matches app-sidebar). */
-const ELBOW_START_REM = 0.75;
-/** Fallback before the first measure — h-7 + gap-1 → 2rem (sidebar sub-items). */
-const ELBOW_ROW_PITCH = "2rem";
-
-export type ElbowItem = {
- id: string;
- icon: IconName;
- label: string;
- running?: boolean;
- failed?: boolean;
- heading?: boolean;
- detail?: ReactNode;
- defaultOpen?: boolean;
- trailing?: ReactNode;
-};
-
-/** Trunk height from shared start → this row's center. */
-export function elbowHeightPx(firstCenter: number, rowCenter: number, startPadPx: number): number {
- return Math.max(startPadPx, rowCenter - firstCenter + startPadPx);
-}
-
-function sameHeights(a: number[], b: number[]): boolean {
- return a.length === b.length && a.every((value, i) => Math.abs(value - b[i]) < 0.5);
-}
-
-function ElbowRow({
- item,
- index,
- elbowH,
- elbowRef,
- onExpandToggle,
-}: {
- item: ElbowItem;
- index: number;
- elbowH?: number;
- elbowRef: (el: HTMLDivElement | null) => void;
- onExpandToggle: () => void;
-}) {
- const [userOpen, setUserOpen] = useState<boolean | null>(null);
- const open = userOpen ?? item.defaultOpen ?? false;
- const expandable = Boolean(item.detail);
- const showDetail = expandable && open;
- const Glyph = Icon[item.icon];
- const Chevron = open ? Icon.chevronUp : Icon.chevronDown;
-
- const handleToggle = () => {
- setUserOpen(!open);
- onExpandToggle();
- };
-
- return (
- <li className="motion-safe:animate-in motion-safe:fade-in-0 motion-safe:slide-in-from-bottom-1 motion-safe:duration-200">
- <div
- className={cn("sidebar-elbow relative h-7", item.running && "z-10")}
- ref={elbowRef}
- style={
- {
- "--elbow-color": item.running ? "var(--foreground)" : "var(--border)",
- "--elbow-h":
- elbowH != null
- ? `${elbowH}px`
- : `calc(${index} * ${ELBOW_ROW_PITCH} + ${ELBOW_START_REM}rem)`,
- } as CSSProperties
- }
- >
- <div className="flex h-7 w-full items-center gap-2 px-2">
- {expandable ? (
- <button
- aria-expanded={open}
- className="group flex min-w-0 flex-1 items-center gap-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"
- onClick={handleToggle}
- type="button"
- >
- <span className="flex size-3.5 shrink-0 items-center justify-center">
- <Glyph
- aria-hidden="true"
- className={cn(
- "size-3.5",
- item.failed
- ? "text-destructive"
- : item.running || item.heading
- ? "text-foreground"
- : "text-muted-foreground"
- )}
- />
- </span>
- <span
- className={cn(
- "pixel-label min-w-0 truncate text-xs transition-colors group-hover:text-foreground",
- item.running
- ? "text-foreground motion-safe:animate-pulse"
- : item.failed
- ? "text-destructive"
- : item.heading
- ? "text-foreground"
- : "text-muted-foreground"
- )}
- >
- {item.label}
- </span>
- <Chevron aria-hidden="true" className="size-3 shrink-0 text-muted-foreground/70" />
- </button>
- ) : (
- <>
- <span className="flex size-3.5 shrink-0 items-center justify-center">
- <Glyph
- aria-hidden="true"
- className={cn(
- "size-3.5",
- item.failed
- ? "text-destructive"
- : item.running || item.heading
- ? "text-foreground"
- : "text-muted-foreground"
- )}
- />
- </span>
- <span
- className={cn(
- "pixel-label min-w-0 flex-1 truncate text-xs",
- item.running
- ? "text-foreground motion-safe:animate-pulse"
- : item.failed
- ? "text-destructive"
- : item.heading
- ? "text-foreground"
- : "text-muted-foreground"
- )}
- >
- {item.label}
- </span>
- </>
- )}
- {item.trailing}
- </div>
- </div>
- {showDetail ? (
- <div className="pb-1.5 pl-1 motion-safe:animate-in motion-safe:fade-in-0 motion-safe:duration-150">
- {item.detail}
- </div>
- ) : null}
- </li>
- );
-}
-
-export function ElbowGroupHeading({
- icon = "list",
- label,
- running,
- failed,
- trailing,
-}: {
- icon?: IconName;
- label: string;
- running?: boolean;
- failed?: boolean;
- trailing?: ReactNode;
-}) {
- const Glyph = Icon[icon];
- return (
- <div className="flex h-7 items-center gap-2 px-2">
- <span className="flex size-3.5 shrink-0 items-center justify-center">
- <Glyph
- aria-hidden="true"
- className={cn(
- "size-3.5",
- failed ? "text-destructive" : running ? "text-foreground" : "text-muted-foreground"
- )}
- />
- </span>
- <span
- className={cn(
- "pixel-label min-w-0 flex-1 truncate text-xs",
- running
- ? "text-foreground motion-safe:animate-pulse"
- : failed
- ? "text-destructive"
- : "text-foreground"
- )}
- >
- {label}
- </span>
- {trailing}
- </div>
- );
-}
-
-export function ElbowList({
- items,
- isStreaming = false,
- className,
- ariaLabel,
-}: {
- items: ElbowItem[];
- isStreaming?: boolean;
- className?: string;
- ariaLabel?: string;
-}) {
- const listRef = useRef<HTMLOListElement>(null);
- const elbowRefs = useRef<(HTMLDivElement | null)[]>([]);
- const measureRef = useRef<() => void>(() => {});
- const [elbowHs, setElbowHs] = useState<number[]>([]);
- const [layoutGen, setLayoutGen] = useState(0);
-
- useLayoutEffect(() => {
- const list = listRef.current;
- if (!list || items.length === 0) return;
-
- const measure = () => {
- const elbows = elbowRefs.current.slice(0, items.length);
- const first = elbows[0];
- if (!first) return;
- const rem = parseFloat(getComputedStyle(list).fontSize) || 16;
- const startPad = ELBOW_START_REM * rem;
- const firstRect = first.getBoundingClientRect();
- const firstCenter = firstRect.top + firstRect.height / 2;
- const next = elbows.map((el) => {
- if (!el) return startPad;
- const rect = el.getBoundingClientRect();
- return elbowHeightPx(firstCenter, rect.top + rect.height / 2, startPad);
- });
- for (let i = 0; i < next.length; i++) {
- elbows[i]?.style.setProperty("--elbow-h", `${next[i]}px`);
- }
- setElbowHs((prev) => (sameHeights(prev, next) ? prev : next));
- };
-
- measureRef.current = measure;
- measure();
-
- let raf = 0;
- const observer = new ResizeObserver(() => {
- cancelAnimationFrame(raf);
- raf = requestAnimationFrame(() => {
- measureRef.current();
- });
- });
- observer.observe(list);
- for (const el of elbowRefs.current.slice(0, items.length)) {
- const item = el?.parentElement;
- if (item) observer.observe(item);
- }
- return () => {
- cancelAnimationFrame(raf);
- observer.disconnect();
- };
- }, [items]);
-
- useLayoutEffect(() => {
- if (layoutGen === 0) return;
- measureRef.current();
- }, [layoutGen]);
-
- if (items.length === 0) return null;
-
- return (
- <ol
- aria-label={ariaLabel}
- // ml-[15px]: elbow ::before sits at left:-10px with a 2px trunk, so the
- // trunk center lands at 6px — the tip of the size-3 header chevron.
- className={cn("ml-[15px] flex list-none flex-col gap-1", className)}
- ref={listRef}
- role={isStreaming ? "status" : undefined}
- >
- {items.map((item, index) => (
- <ElbowRow
- elbowH={elbowHs[index]}
- elbowRef={(el) => {
- elbowRefs.current[index] = el;
- }}
- index={index}
- item={item}
- key={item.id}
- onExpandToggle={() => setLayoutGen((n) => n + 1)}
- />
- ))}
- </ol>
- );
-}
diff --git a/frontend/src/components/ui/icons/glyphs.ts b/frontend/src/components/ui/icons/glyphs.ts
index 2677d336..08c12ff1 100644
--- a/frontend/src/components/ui/icons/glyphs.ts
+++ b/frontend/src/components/ui/icons/glyphs.ts
@@ -253,6 +253,7 @@ export const glyphs = {
"settings-cog-2": [
"M6 22H4v-2h2v2Zm4-2h4v-2h4v2h-2v2H8v-2H6v-2h4v2Zm10 2h-2v-2h2v2ZM4 20H2v-2h2v2Zm18 0h-2v-2h2v2ZM6 10H4v4h2v4H4v-2H2V8h2V6h2v4Zm14-2h2v8h-2v2h-2v-4h2v-4h-2V6h2v2Zm-6 8h-4v-2h4v2Zm-4-2H8v-4h2v4Zm6 0h-2v-4h2v4Zm-2-4h-4V8h4v2ZM4 6H2V4h2v2Zm12-2h2v2h-4V4h-4v2H6V4h2V2h8v2Zm6 2h-2V4h2v2ZM6 4H4V2h2v2Zm14 0h-2V2h2v2Z",
],
+ sidebar: ["M4 4h16v2h-16zM2 6h2v12h-2zM8 6h2v14h-2zM20 6h2v12h-2zM4 18h4v2h-4zM10 18h10v2h-10z"],
skull: [
"M9 22H7v-2h2v2Zm4 0h-2v-2h2v2Zm4 0h-2v-2h2v2ZM7 20H5v-4H3v-2h4v6Zm4 0H9v-4h2v4Zm4 0h-2v-4h2v4Zm6-4h-2v4h-2v-6h4v2ZM3 14H1V4h2v10Zm20 0h-2V4h2v10Zm-13-3H8V7h2v4Zm6 0h-2V7h2v4Zm5-7H3V2h18v2Z",
],
diff --git a/frontend/src/components/ui/icons/index.ts b/frontend/src/components/ui/icons/index.ts
index 13459751..0a85f234 100644
--- a/frontend/src/components/ui/icons/index.ts
+++ b/frontend/src/components/ui/icons/index.ts
@@ -96,8 +96,6 @@ export const Icon = {
observability: glyph("eye"),
observabilityTitle: Eyeball,
overmind: OvermindEyeMono,
- panelLeftClose: glyph("arrow-bar-left"),
- panelLeftOpen: glyph("arrow-bar-right"),
pin: glyph("anchor"),
play: glyph("play"),
project: glyph("box"),
@@ -109,6 +107,7 @@ export const Icon = {
server: glyph("server"),
session: glyph("comment"),
settings: glyph("settings-2"), // the plain settings glyph — the workshop cog is `workshop`
+ sidebar: glyph("sidebar"),
skull: glyph("skull"),
sort: glyph("sort-vertical"),
sortable: glyph("chevrons-vertical"),
diff --git a/frontend/src/components/ui/markdown-content.test.tsx b/frontend/src/components/ui/markdown-content.test.tsx
new file mode 100644
index 00000000..26acca71
--- /dev/null
+++ b/frontend/src/components/ui/markdown-content.test.tsx
@@ -0,0 +1,28 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, expect, it, vi } from "vitest";
+
+import MarkdownContent from "./markdown-content";
+
+afterEach(() => {
+ cleanup();
+ vi.unstubAllGlobals();
+});
+
+const reply = "Run this:\n\n```python\nprint('hi')\n```\n";
+
+it("lets a chat reply's code block be copied without its trailing newline", () => {
+ const writeText = vi.fn(() => Promise.resolve());
+ vi.stubGlobal("navigator", { clipboard: { writeText } });
+ const { container } = render(<MarkdownContent chat>{reply}</MarkdownContent>);
+ expect(container.firstElementChild?.classList.contains("chat-prose")).toBe(true);
+ fireEvent.click(screen.getByRole("button", { name: "Copy code" }));
+ expect(writeText).toHaveBeenCalledWith("print('hi')");
+ expect(screen.getByRole("button", { name: "Copied" })).toBeTruthy();
+});
+
+it("keeps other Markdown without a copy button", () => {
+ render(<MarkdownContent>{reply}</MarkdownContent>);
+ expect(screen.queryByRole("button", { name: "Copy code" })).toBeNull();
+});
diff --git a/frontend/src/components/ui/markdown-content.tsx b/frontend/src/components/ui/markdown-content.tsx
index 6351d14f..eb0c719a 100644
--- a/frontend/src/components/ui/markdown-content.tsx
+++ b/frontend/src/components/ui/markdown-content.tsx
@@ -1,7 +1,11 @@
+import { isValidElement, type ReactNode } from "react";
import ReactMarkdown from "react-markdown";
import remarkGfm from "remark-gfm";
+import { useCopy } from "@/components/ui/block-actions";
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icons";
import { PROSE } from "@/lib/typography";
import { cn } from "@/lib/utils";
@@ -9,19 +13,54 @@ export interface MarkdownContentProps {
children: string;
compact?: boolean;
dividers?: boolean;
+ /** Chat replies: the larger chat type scale (styles.css `.chat-prose`) and copyable code. */
+ chat?: boolean;
className?: string;
}
+function textOf(node: ReactNode): string {
+ if (typeof node === "string" || typeof node === "number") return String(node);
+ if (Array.isArray(node)) return node.map(textOf).join("");
+ if (isValidElement<{ children?: ReactNode }>(node)) return textOf(node.props.children);
+ return "";
+}
+
+function CopyableBlock({ children }: { children: ReactNode }) {
+ const { copied, copy } = useCopy(textOf(children).replace(/\n$/u, ""));
+ return (
+ <div className="relative min-w-0 rounded-sm bg-muted">
+ <pre className="overflow-x-auto py-2.5 pr-11 pl-3 whitespace-pre">{children}</pre>
+ <Button
+ aria-label={copied ? "Copied" : "Copy code"}
+ className="absolute top-1.5 right-1.5 text-muted-foreground"
+ onClick={copy}
+ size="icon-xs"
+ type="button"
+ variant="ghost"
+ >
+ {copied ? <Icon.success className="size-3.5" /> : <Icon.copy className="size-3.5" />}
+ </Button>
+ </div>
+ );
+}
+
/** Import the wrapper in `markdown.tsx`, not this module, so react-markdown and
* remark-gfm stay out of the initial bundle. The default export is React.lazy's. */
export default function MarkdownContentImpl({
children,
compact = false,
dividers = true,
+ chat = false,
className,
}: MarkdownContentProps) {
return (
- <div className={cn(PROSE, compact ? "text-xs" : "text-sm leading-relaxed", className)}>
+ <div
+ className={cn(
+ PROSE,
+ chat ? "chat-prose" : compact ? "text-xs" : "text-sm leading-relaxed",
+ className
+ )}
+ >
<ReactMarkdown
components={{
a: ({ href, children }) => {
@@ -43,6 +82,16 @@ export default function MarkdownContentImpl({
),
code: ({ children, className }) => {
const isBlock = className?.includes("language-");
+ if (chat)
+ return (
+ <code
+ className={
+ isBlock ? undefined : "rounded-sm bg-foreground/6 px-1 py-px font-mono"
+ }
+ >
+ {children}
+ </code>
+ );
return isBlock ? (
<code className="block overflow-x-auto rounded-sm bg-muted px-3 py-2 font-mono text-xs">
{children}
@@ -92,16 +141,24 @@ export default function MarkdownContentImpl({
<ol className="mb-3 list-decimal pl-5 last:mb-0 space-y-0.5">{children}</ol>
),
p: ({ children }) => <p className="mb-2 last:mb-0">{children}</p>,
- pre: ({ children }) => (
- <pre className="mb-2 overflow-x-auto rounded-md bg-wash-raised px-3 py-2 last:mb-0">
- {children}
- </pre>
- ),
+ pre: ({ children }) =>
+ chat ? (
+ <CopyableBlock>{children}</CopyableBlock>
+ ) : (
+ <pre className="mb-2 overflow-x-auto rounded-md bg-wash-raised px-3 py-2 last:mb-0">
+ {children}
+ </pre>
+ ),
strong: ({ children }) => (
<strong className="font-semibold text-foreground">{children}</strong>
),
table: ({ children }) => (
- <div className="mb-2 overflow-x-auto last:mb-0">
+ <div
+ className={cn(
+ "mb-2 overflow-x-auto last:mb-0",
+ chat && "rounded-sm border border-border"
+ )}
+ >
<table className="w-full border-collapse text-xs">{children}</table>
</div>
),
diff --git a/frontend/src/components/workspace/chat-sidebar.tsx b/frontend/src/components/workspace/chat-sidebar.tsx
new file mode 100644
index 00000000..76c5c8e5
--- /dev/null
+++ b/frontend/src/components/workspace/chat-sidebar.tsx
@@ -0,0 +1,208 @@
+import {
+ type CSSProperties,
+ createContext,
+ type ReactNode,
+ type RefObject,
+ useContext,
+ useEffect,
+ useRef,
+ useState,
+} from "react";
+import { createPortal } from "react-dom";
+
+import { Button } from "@/components/ui/button";
+import { Icon } from "@/components/ui/icons";
+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
+import { usePersistedState } from "@/hooks/use-persisted-state";
+
+export const CHAT_WIDTH = { default: 384, min: 320 };
+const MAX_WIDTH = 720;
+// The canvas keeps at least this much beside the panel.
+const CANVAS_MIN = 376;
+const KEY_STEP = 16;
+
+const ChatHost = createContext<HTMLDivElement | null>(null);
+
+/** Renders a page's conversation into the shell's chat sidebar. */
+export function ChatPanel({ children }: { children: ReactNode }) {
+ const host = useContext(ChatHost);
+ return host ? createPortal(children, host) : null;
+}
+
+/** The chat sidebar's state for the current page: open unless closed on this page, and a
+ * kept width that the shell's own width bounds. */
+export function useChatSidebar(pathname: string, shell: RefObject<HTMLElement | null>) {
+ const available = /^\/experiments\/[^/]+\/?$/.test(pathname);
+ const [closedOn, setClosedOn] = useState<string | null>(null);
+ const [kept, keep] = usePersistedState("chat:panelWidth", CHAT_WIDTH.default);
+ const [dragged, setDragged] = useState<number | null>(null);
+ const [max, setMax] = useState(MAX_WIDTH);
+ const [host, setHost] = useState<HTMLDivElement | null>(null);
+ useEffect(() => {
+ const node = shell.current;
+ if (!node) return;
+ const measure = () => {
+ const width = node.getBoundingClientRect().width;
+ if (width > 0) setMax(Math.max(CHAT_WIDTH.min, Math.min(MAX_WIDTH, width - CANVAS_MIN)));
+ };
+ measure();
+ const observer = new ResizeObserver(measure);
+ observer.observe(node);
+ return () => observer.disconnect();
+ }, [shell]);
+ const open = available && closedOn !== pathname;
+ return {
+ available,
+ dragged,
+ host,
+ keep,
+ max,
+ open,
+ setDragged,
+ setHost,
+ toggle: () => setClosedOn(open ? pathname : null),
+ width: Math.max(CHAT_WIDTH.min, Math.min(max, dragged ?? kept)),
+ };
+}
+
+type Sidebar = ReturnType<typeof useChatSidebar>;
+
+export function ChatSidebarProvider({
+ sidebar,
+ children,
+}: {
+ sidebar: Sidebar;
+ children: ReactNode;
+}) {
+ return <ChatHost.Provider value={sidebar.host}>{children}</ChatHost.Provider>;
+}
+
+/** The canvas's top-right button that opens and closes the chat sidebar. */
+export function ChatToggle({
+ sidebar,
+ ref,
+}: {
+ sidebar: Sidebar;
+ ref?: RefObject<HTMLButtonElement | null>;
+}) {
+ if (!sidebar.available) return null;
+ const label = `${sidebar.open ? "Close" : "Open"} chat panel`;
+ return (
+ <div className="chat-toggle absolute top-3.5 right-3 z-30">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button
+ aria-controls="workspace-chat-panel"
+ aria-expanded={sidebar.open}
+ aria-label={label}
+ onClick={sidebar.toggle}
+ ref={ref}
+ size="icon-sm"
+ variant="send"
+ >
+ <Icon.sidebar className="rotate-180" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent>{label}</TooltipContent>
+ </Tooltip>
+ </div>
+ );
+}
+
+/** The divider that sets the sidebar's width, and the sidebar the page's chat renders into.
+ * Dragging left widens the panel; arrow keys, Home and End resize it; a double click resets. */
+export function ChatSidebar({
+ sidebar,
+ toggle,
+}: {
+ sidebar: Sidebar;
+ toggle: RefObject<HTMLButtonElement | null>;
+}) {
+ const { open, width, max } = sidebar;
+ const origin = useRef<{ x: number; width: number } | null>(null);
+ const resizing = open && sidebar.dragged !== null;
+ const clamp = (value: number) => Math.round(Math.min(max, Math.max(CHAT_WIDTH.min, value)));
+ const end = () => {
+ if (!origin.current) return;
+ origin.current = null;
+ sidebar.keep(width);
+ sidebar.setDragged(null);
+ };
+ return (
+ <>
+ <div
+ aria-hidden={!open}
+ className="workspace-chat-divider col-start-2 row-start-2 hidden sm:flex"
+ data-open={open}
+ data-resizing={resizing}
+ inert={!open}
+ >
+ <div
+ aria-controls="workspace-chat-panel"
+ aria-label="Chat panel width"
+ aria-orientation="vertical"
+ aria-valuemax={max}
+ aria-valuemin={CHAT_WIDTH.min}
+ aria-valuenow={width}
+ className="chat-resize-handle"
+ onDoubleClick={() => sidebar.keep(CHAT_WIDTH.default)}
+ onKeyDown={(event) => {
+ const next = {
+ ArrowLeft: width + KEY_STEP,
+ ArrowRight: width - KEY_STEP,
+ End: max,
+ Home: CHAT_WIDTH.min,
+ }[event.key];
+ if (next === undefined) return;
+ event.preventDefault();
+ sidebar.keep(clamp(next));
+ }}
+ onLostPointerCapture={end}
+ onPointerCancel={end}
+ onPointerDown={(event) => {
+ if (event.button !== 0) return;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ origin.current = { width, x: event.clientX };
+ sidebar.setDragged(width);
+ }}
+ onPointerMove={(event) => {
+ if (!origin.current) return;
+ sidebar.setDragged(clamp(origin.current.width - (event.clientX - origin.current.x)));
+ }}
+ onPointerUp={end}
+ role="separator"
+ tabIndex={0}
+ >
+ <span className="chat-resize-grip" />
+ </div>
+ </div>
+ <aside
+ aria-hidden={!open}
+ aria-label="Chat panel"
+ className="workspace-chat-panel col-start-3 row-start-2 flex min-h-0 min-w-0 shrink-0 flex-col overflow-hidden bg-sidebar text-sidebar-foreground"
+ data-open={open}
+ data-resizing={resizing}
+ id="workspace-chat-panel"
+ inert={!open}
+ style={{ "--chat-panel-width": `${width}px` } as CSSProperties}
+ >
+ <Button
+ aria-label="Close chat panel"
+ className="m-2 self-end sm:hidden"
+ onClick={() => {
+ sidebar.toggle();
+ requestAnimationFrame(() => toggle.current?.focus());
+ }}
+ size="icon-sm"
+ variant="send"
+ >
+ <Icon.sidebar className="rotate-180" />
+ </Button>
+ <div
+ className="workspace-chat-content flex min-h-0 flex-1 flex-col"
+ ref={sidebar.setHost}
+ />
+ </aside>
+ </>
+ );
+}
diff --git a/frontend/src/components/workspace/home-composer.test.tsx b/frontend/src/components/workspace/home-composer.test.tsx
index abf04a5e..3538163f 100644
--- a/frontend/src/components/workspace/home-composer.test.tsx
+++ b/frontend/src/components/workspace/home-composer.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
// covers: console-logic
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { TooltipProvider } from "@/components/ui/tooltip";
@@ -52,7 +52,12 @@ it("refuses data that lands as more datasets than a message takes", async () =>
fireEvent.change(screen.getByLabelText("Attach dataset files"), {
target: { files: [new File(["a,b\n1,2\n"], "rows.csv")] },
});
- const send = screen.getByRole("button", { name: "Send" });
+ // Each attached file opens its review; Send waits until it is continued.
+ const review = await screen.findByRole("region", { name: "Import rows.csv" });
+ const next = within(review).getByRole("button", { name: "Continue" });
+ await waitFor(() => expect(next.hasAttribute("disabled")).toBe(false));
+ fireEvent.click(next);
+ const send = await screen.findByRole("button", { name: "Send" });
await waitFor(() => expect(send.hasAttribute("disabled")).toBe(false));
fireEvent.click(send);
diff --git a/frontend/src/components/workspace/home-composer.tsx b/frontend/src/components/workspace/home-composer.tsx
index 02520b8b..1fff93c6 100644
--- a/frontend/src/components/workspace/home-composer.tsx
+++ b/frontend/src/components/workspace/home-composer.tsx
@@ -8,6 +8,7 @@ import { MentionTextarea } from "@/components/assistant/mention-textarea";
import { MessageLimit } from "@/components/assistant/message-limit";
import { MESSAGE_CHARS } from "@/components/assistant/types";
import { Attachment } from "@/components/datasets/attachment";
+import { UploadReview } from "@/components/datasets/upload-review";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Card } from "@/components/ui/card";
@@ -214,7 +215,8 @@ export function HomeComposer({
}));
const uploading = upload.files.some((file) => file.status !== "ready" && file.status !== "error");
- const ready = upload.files.filter((file) => file.status === "ready");
+ const unreviewed = upload.files.some((file) => file.status !== "ready" || file.reviewed !== true);
+ const ready = upload.files.filter((file) => file.status === "ready" && file.reviewed === true);
const start = useMutation({
mutationFn: async ({ message, name }: { message: string; name: string }) => {
const uploads = ready.map((file) => file.uploadId!);
@@ -302,17 +304,19 @@ export function HomeComposer({
: "Starting"
: uploading
? "Uploading"
- : attaching
- ? "Attaching"
- : tooMany
- ? `At most ${MAX_DATASETS} datasets`
- : empty
- ? "No message"
- : text.trim()
- ? "Send"
- : "Add data";
+ : unreviewed
+ ? "Review the attached files"
+ : attaching
+ ? "Attaching"
+ : tooMany
+ ? `At most ${MAX_DATASETS} datasets`
+ : empty
+ ? "No message"
+ : text.trim()
+ ? "Send"
+ : "Add data";
const submit = guard(() => {
- if (locked || uploading || attaching || tooMany || empty) return;
+ if (locked || uploading || unreviewed || attaching || tooMany || empty) return;
// The name reads as typed; the message carries each mention's link.
const name =
text.trim().split("\n")[0].slice(0, 120) ||
@@ -335,6 +339,7 @@ export function HomeComposer({
const addFiles = guard((files: File[]) => upload.add(files));
return (
<Card className="assistant-surface assistant-composer w-full p-1.5">
+ <UploadReview busy={locked} upload={upload} />
<form
aria-label="Start an experiment"
className="assistant-chat-inner overflow-hidden border border-border/70 bg-muted"
@@ -386,6 +391,7 @@ export function HomeComposer({
disabled={locked}
entry={entry}
key={entry.id}
+ onPreview={() => upload.setPreviewId(entry.id)}
onRemove={() => upload.remove(entry.id)}
onRetry={() => upload.retry(entry)}
/>
@@ -467,7 +473,7 @@ export function HomeComposer({
<span className="inline-flex">
<Button
aria-label="Send"
- disabled={locked || uploading || attaching || tooMany || empty}
+ disabled={locked || uploading || unreviewed || attaching || tooMany || empty}
size="icon-sm"
type="submit"
variant="secondary"
diff --git a/frontend/src/components/workspace/workspace-tabs.tsx b/frontend/src/components/workspace/workspace-tabs.tsx
index 8d6b6666..b8e109cd 100644
--- a/frontend/src/components/workspace/workspace-tabs.tsx
+++ b/frontend/src/components/workspace/workspace-tabs.tsx
@@ -239,7 +239,7 @@ export function WorkspaceTabs({
};
return (
- <div className="flex min-w-0 items-end border-b border-border bg-sidebar">
+ <div className="flex min-w-0 items-end">
<Button
aria-label="Open sidebar"
className="mb-1 shrink-0 md:hidden"
@@ -247,7 +247,7 @@ export function WorkspaceTabs({
size="icon-sm"
variant="ghost"
>
- <Icon.panelLeftOpen />
+ <Icon.sidebar />
</Button>
<Reorder.Group
aria-label="Workspace tabs"
diff --git a/frontend/src/components/workspace/workspace.module.css b/frontend/src/components/workspace/workspace.module.css
index f0277285..02140982 100644
--- a/frontend/src/components/workspace/workspace.module.css
+++ b/frontend/src/components/workspace/workspace.module.css
@@ -6,7 +6,6 @@
align-items: end;
min-width: 0;
padding: 8px 12px 0 0;
- margin-bottom: -1px;
overflow-x: auto;
scrollbar-width: none;
}
@@ -52,17 +51,14 @@
outline: 1px solid var(--foreground);
outline-offset: -1px;
}
-/* Taller to join the panel; the bottom padding keeps its title level with the others. */
+/* Detached chips: the active one inverts instead of joining the panel below. */
.tab[data-active="true"] {
- z-index: 1;
- height: 42px;
- padding-bottom: 8px;
- margin-bottom: 0;
- color: var(--foreground);
- background: var(--card);
- border: 1px solid var(--border);
- border-bottom-color: var(--card);
- border-radius: var(--radius-sm) var(--radius-sm) 0 0;
+ color: var(--background);
+ background: var(--foreground);
+}
+.tab[data-active="true"] .close:hover {
+ color: var(--background);
+ background: color-mix(in srgb, var(--background) 10%, transparent);
}
@media (prefers-reduced-motion: reduce) {
.tab {
diff --git a/frontend/src/hooks/use-activity.ts b/frontend/src/hooks/use-activity.ts
index 409186bb..cb8dca9f 100644
--- a/frontend/src/hooks/use-activity.ts
+++ b/frontend/src/hooks/use-activity.ts
@@ -11,6 +11,7 @@ import { useSearch } from "@tanstack/react-router";
import apiClient from "@/client";
import { useAuthContext } from "@/contexts/auth-context";
+import { whilePageVisible } from "@/lib/visible-stream";
import { type ActivityFeed, ActivityFeedFromJSON, type ActivitySeenRequest } from "@/openapi";
const activityQuery = (projectId: string | undefined, enabled: boolean) =>
@@ -106,74 +107,76 @@ function useLiveActivity(projectId: string | undefined, enabled: boolean) {
const client = useQueryClient();
useEffect(() => {
if (!enabled || !projectId) return;
- let stopped = false;
- let retry: ReturnType<typeof setTimeout> | undefined;
- let clear: ReturnType<typeof setTimeout> | undefined;
- let controller: AbortController;
- let previous: Map<string, number> | undefined;
- let delay = 1500;
- client.setQueryData(highlightKey, {});
- const apply = async (feed: ActivityFeed) => {
- const next = new Map(feed.results.map((event) => [event.id, event.updatedAt.getTime()]));
- const changes = previous
- ? feed.results.filter((event) => previous?.get(event.id) !== event.updatedAt.getTime())
- : [];
- const reconcileAssets = !previous || changes.length > 0;
- previous = next;
- await client.invalidateQueries({
- predicate: (query) =>
- query.queryKey[0] === "activity" ||
- query.queryKey[0] === "onboarding-milestones" ||
- (reconcileAssets && isLive(query.queryKey)),
- });
- if (stopped || !changes.length) return;
- const marks: Record<string, number> = {};
- for (const event of changes) {
- marks[`activity:${event.id}`] = Date.now();
- for (const asset of event.assets) marks[`${asset.kind}:${asset.id}`] = Date.now();
- }
- client.setQueryData(highlightKey, (old: Record<string, number> = {}) => ({
- ...old,
- ...marks,
- }));
- if (clear) clearTimeout(clear);
- clear = setTimeout(() => client.setQueryData(highlightKey, {}), 2400);
- };
- const connect = async () => {
- controller = new AbortController();
- try {
- const response = await apiClient.activity.activityEventsRetrieveRaw(
- { project: projectId },
- { signal: controller.signal }
- );
- const reader = response.raw.body?.getReader();
- if (!reader) throw new Error("Activity stream unavailable");
- const decoder = new TextDecoder();
- let buffer = "";
- while (!stopped) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const frames = buffer.split("\n\n");
- buffer = frames.pop() ?? "";
- for (const frame of frames) {
- if (!frame.startsWith("data: ")) continue;
- delay = 1500;
- await apply(ActivityFeedFromJSON(JSON.parse(frame.slice(6))));
+ return whilePageVisible(() => {
+ let stopped = false;
+ let retry: ReturnType<typeof setTimeout> | undefined;
+ let clear: ReturnType<typeof setTimeout> | undefined;
+ let controller: AbortController;
+ let previous: Map<string, number> | undefined;
+ let delay = 1500;
+ client.setQueryData(highlightKey, {});
+ const apply = async (feed: ActivityFeed) => {
+ const next = new Map(feed.results.map((event) => [event.id, event.updatedAt.getTime()]));
+ const changes = previous
+ ? feed.results.filter((event) => previous?.get(event.id) !== event.updatedAt.getTime())
+ : [];
+ const reconcileAssets = !previous || changes.length > 0;
+ previous = next;
+ await client.invalidateQueries({
+ predicate: (query) =>
+ query.queryKey[0] === "activity" ||
+ query.queryKey[0] === "onboarding-milestones" ||
+ (reconcileAssets && isLive(query.queryKey)),
+ });
+ if (stopped || !changes.length) return;
+ const marks: Record<string, number> = {};
+ for (const event of changes) {
+ marks[`activity:${event.id}`] = Date.now();
+ for (const asset of event.assets) marks[`${asset.kind}:${asset.id}`] = Date.now();
+ }
+ client.setQueryData(highlightKey, (old: Record<string, number> = {}) => ({
+ ...old,
+ ...marks,
+ }));
+ if (clear) clearTimeout(clear);
+ clear = setTimeout(() => client.setQueryData(highlightKey, {}), 2400);
+ };
+ const connect = async () => {
+ controller = new AbortController();
+ try {
+ const response = await apiClient.activity.activityEventsRetrieveRaw(
+ { project: projectId },
+ { signal: controller.signal }
+ );
+ const reader = response.raw.body?.getReader();
+ if (!reader) throw new Error("Activity stream unavailable");
+ const decoder = new TextDecoder();
+ let buffer = "";
+ while (!stopped) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const frames = buffer.split("\n\n");
+ buffer = frames.pop() ?? "";
+ for (const frame of frames) {
+ if (!frame.startsWith("data: ")) continue;
+ delay = 1500;
+ await apply(ActivityFeedFromJSON(JSON.parse(frame.slice(6))));
+ }
}
+ } catch {
+ delay = Math.min(delay * 2, 60_000);
}
- } catch {
- delay = Math.min(delay * 2, 60_000);
- }
- if (!stopped) retry = setTimeout(connect, delay);
- };
- void connect();
- return () => {
- stopped = true;
- controller?.abort();
- if (retry) clearTimeout(retry);
- if (clear) clearTimeout(clear);
- client.setQueryData(highlightKey, {});
- };
+ if (!stopped) retry = setTimeout(connect, delay);
+ };
+ void connect();
+ return () => {
+ stopped = true;
+ controller?.abort();
+ if (retry) clearTimeout(retry);
+ if (clear) clearTimeout(clear);
+ client.setQueryData(highlightKey, {});
+ };
+ });
}, [client, enabled, projectId]);
}
diff --git a/frontend/src/hooks/use-capabilities.test.ts b/frontend/src/hooks/use-capabilities.test.ts
deleted file mode 100644
index efc69428..00000000
--- a/frontend/src/hooks/use-capabilities.test.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-// covers: console-logic
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-vi.mock("@/client", () => ({
- default: {
- capabilities: {
- capabilitiesList: vi.fn(),
- },
- },
-}));
-
-import apiClient from "@/client";
-import { fetchAllCapabilities } from "./use-capabilities";
-
-const list = apiClient.capabilities.capabilitiesList as ReturnType<typeof vi.fn>;
-
-describe("fetchAllCapabilities", () => {
- beforeEach(() => {
- list.mockReset();
- });
-
- it("walks every DRF page until results cover count", async () => {
- list
- .mockResolvedValueOnce({
- count: 130,
- next: "http://example/api/capabilities/?page=2",
- previous: null,
- results: Array.from({ length: 100 }, (_, i) => ({ id: `p1-${i}` })),
- })
- .mockResolvedValueOnce({
- count: 130,
- next: null,
- previous: "http://example/api/capabilities/?page=1",
- results: Array.from({ length: 30 }, (_, i) => ({ id: `p2-${i}` })),
- });
-
- const data = await fetchAllCapabilities("proj-1");
-
- expect(list).toHaveBeenCalledTimes(2);
- expect(list).toHaveBeenNthCalledWith(2, {
- page: 2,
- pageSize: 100,
- project: "proj-1",
- });
- expect(data.results).toHaveLength(130);
- expect(data.next).toBeNull();
- });
-});
diff --git a/frontend/src/hooks/use-capabilities.ts b/frontend/src/hooks/use-capabilities.ts
deleted file mode 100644
index 901e6932..00000000
--- a/frontend/src/hooks/use-capabilities.ts
+++ /dev/null
@@ -1,28 +0,0 @@
-import apiClient from "@/client";
-import type { CapabilityList, PaginatedCapabilityListList } from "@/openapi";
-
-/** DRF max_page_size for the capabilities list (see api/config.py PageNumberPagination). */
-const CAPABILITIES_API_PAGE_SIZE = 100;
-const CAPABILITIES_MAX_PAGES = 50;
-
-export const fetchAllCapabilities = async (
- projectId: string
-): Promise<PaginatedCapabilityListList> => {
- const results: CapabilityList[] = [];
- let page = 1;
- let count = 0;
-
- while (page <= CAPABILITIES_MAX_PAGES) {
- const data = await apiClient.capabilities.capabilitiesList({
- page,
- pageSize: CAPABILITIES_API_PAGE_SIZE,
- project: projectId,
- });
- count = data.count;
- results.push(...data.results);
- if (!data.next || results.length >= count || data.results.length === 0) break;
- page += 1;
- }
-
- return { count, next: null, previous: null, results };
-};
diff --git a/frontend/src/hooks/use-entity-siblings.ts b/frontend/src/hooks/use-entity-siblings.ts
deleted file mode 100644
index 39addb08..00000000
--- a/frontend/src/hooks/use-entity-siblings.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-import apiClient from "@/client";
-
-export interface EntitySibling {
- id: string;
- label: string;
-}
-
-// Traces and jobs are excluded on purpose: high-cardinality, paginated,
-// filter-driven lists that a flat dropdown suits poorly.
-export const SWITCHABLE_KINDS = new Set(["capabilities", "projects", "datasets"]);
-
-export function useEntitySiblings(kind: string | undefined, projectId: string | undefined) {
- const scopedToProject = kind === "capabilities" || kind === "datasets";
- return useQuery<EntitySibling[]>({
- enabled: !!kind && SWITCHABLE_KINDS.has(kind) && (!scopedToProject || !!projectId),
- queryFn: async (): Promise<EntitySibling[]> => {
- switch (kind) {
- case "capabilities": {
- const res = await apiClient.capabilities.capabilitiesList({ project: projectId });
- return (res.results ?? []).map((a) => ({ id: a.id, label: a.name }));
- }
- case "projects": {
- const res = await apiClient.projects.projectsList({});
- return (res.results ?? []).map((p) => ({ id: p.id, label: p.name }));
- }
- case "datasets": {
- const res = await apiClient.datasets.datasetsList({
- pageSize: 200,
- project: projectId,
- });
- return (res.results ?? []).map((d) => ({
- id: d.id,
- label: d.name?.trim() || `Dataset ${d.id.slice(0, 8)}`,
- }));
- }
- default:
- return [];
- }
- },
- queryKey: ["entity-siblings", kind, projectId],
- staleTime: 30_000,
- });
-}
diff --git a/frontend/src/hooks/use-event-stream.ts b/frontend/src/hooks/use-event-stream.ts
index 46b6c910..837667cd 100644
--- a/frontend/src/hooks/use-event-stream.ts
+++ b/frontend/src/hooks/use-event-stream.ts
@@ -1,6 +1,7 @@
-import { useEffect, useRef, useState } from "react";
+import { useEffect, useRef } from "react";
import { fetchWithAuth } from "@/client";
+import { whilePageVisible } from "@/lib/visible-stream";
export interface StreamEvent {
type: string;
@@ -19,61 +20,57 @@ export function useEventStream<T extends StreamEvent>(
useEffect(() => {
onEventRef.current = onEvent;
});
- const [visible, setVisible] = useState(() => document.visibilityState === "visible");
- useEffect(() => {
- const update = () => setVisible(document.visibilityState === "visible");
- document.addEventListener("visibilitychange", update);
- return () => document.removeEventListener("visibilitychange", update);
- }, []);
const connections = useRef(0);
useEffect(() => {
- if (!path || !visible) return;
- let cancelled = false;
- let timer: ReturnType<typeof setTimeout> | undefined;
- let controller: AbortController | null = null;
+ if (!path) return;
+ return whilePageVisible(() => {
+ let cancelled = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let controller: AbortController | null = null;
- const consume = (line: string) => {
- if (!line.startsWith("data: ")) return;
- try {
- const event = JSON.parse(line.slice(6)) as T;
- if (event.type === "connected") {
- connections.current += 1;
- onEventRef.current({ ...event, again: connections.current > 1 });
- } else onEventRef.current(event);
- } catch {
- // A malformed frame carries nothing worth surfacing.
- }
- };
+ const consume = (line: string) => {
+ if (!line.startsWith("data: ")) return;
+ try {
+ const event = JSON.parse(line.slice(6)) as T;
+ if (event.type === "connected") {
+ connections.current += 1;
+ onEventRef.current({ ...event, again: connections.current > 1 });
+ } else onEventRef.current(event);
+ } catch {
+ // A malformed frame carries nothing worth surfacing.
+ }
+ };
- const connect = async () => {
- if (cancelled) return;
- controller = new AbortController();
- let buffer = "";
- try {
- const res = await fetchWithAuth(path, { signal: controller.signal });
- if (!res.ok || !res.body) throw new Error(`events ${res.status}`);
- const reader = res.body.getReader();
- const decoder = new TextDecoder();
- while (true) {
- const { done, value } = await reader.read();
- if (done) break;
- buffer += decoder.decode(value, { stream: true });
- const lines = buffer.split("\n");
- buffer = lines.pop() ?? "";
- for (const line of lines) consume(line.trimEnd());
+ const connect = async () => {
+ if (cancelled) return;
+ controller = new AbortController();
+ let buffer = "";
+ try {
+ const res = await fetchWithAuth(path, { signal: controller.signal });
+ if (!res.ok || !res.body) throw new Error(`events ${res.status}`);
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buffer += decoder.decode(value, { stream: true });
+ const lines = buffer.split("\n");
+ buffer = lines.pop() ?? "";
+ for (const line of lines) consume(line.trimEnd());
+ }
+ } catch {
+ // Aborted or dropped — reconnect below.
}
- } catch {
- // Aborted or dropped — reconnect below.
- }
- if (!cancelled) timer = setTimeout(connect, 3_000);
- };
+ if (!cancelled) timer = setTimeout(connect, 3_000);
+ };
- void connect();
- return () => {
- cancelled = true;
- controller?.abort();
- if (timer) clearTimeout(timer);
- };
- }, [path, visible]);
+ void connect();
+ return () => {
+ cancelled = true;
+ controller?.abort();
+ if (timer) clearTimeout(timer);
+ };
+ });
+ }, [path]);
}
diff --git a/frontend/src/hooks/use-uploads.test.ts b/frontend/src/hooks/use-uploads.test.ts
index cf1bda1e..31e10609 100644
--- a/frontend/src/hooks/use-uploads.test.ts
+++ b/frontend/src/hooks/use-uploads.test.ts
@@ -52,7 +52,7 @@ describe("dataset uploads", () => {
await waitFor(() => expect(result.current.files[1].status).toBe("ready"));
expect(result.current.files.map((file) => file.uploadId)).toEqual(["two.jsonl", "three.csv"]);
expect(api.uploadsInspectCreate).toHaveBeenCalledWith(
- { id: "three.csv", inspectUploadRequest: { size: 1 } },
+ { id: "three.csv", inspectUploadRequest: { options: undefined, preview: true, size: 1 } },
{ signal: expect.any(AbortSignal) }
);
});
@@ -124,3 +124,28 @@ describe("dataset uploads", () => {
expect(api.uploadsChunkUpdate).not.toHaveBeenCalled();
});
});
+
+it("waits for a review and rereads the same uploaded bytes with new options", async () => {
+ const { result } = renderHook(() => useDatasetUploads());
+ act(() => result.current.add([new File(["a;b\n1;2"], "review.csv")]));
+ await waitFor(() => expect(result.current.files[0].status).toBe("ready"));
+ expect(result.current.files[0].reviewed).toBe(false);
+ act(() => result.current.confirm(result.current.files[0].id));
+ expect(result.current.files[0].reviewed).toBe(true);
+ await act(async () =>
+ result.current.inspect(result.current.files[0], { delimiter: "semicolon", header: false })
+ );
+ expect(result.current.files[0].reviewed).toBe(false);
+ expect(api.uploadsCreate).toHaveBeenCalledTimes(1);
+ expect(api.uploadsInspectCreate).toHaveBeenLastCalledWith(
+ {
+ id: "review.csv",
+ inspectUploadRequest: {
+ options: { delimiter: "semicolon", header: false },
+ preview: true,
+ size: 7,
+ },
+ },
+ { signal: expect.any(AbortSignal) }
+ );
+});
diff --git a/frontend/src/hooks/use-uploads.ts b/frontend/src/hooks/use-uploads.ts
index e2615d41..05b797d0 100644
--- a/frontend/src/hooks/use-uploads.ts
+++ b/frontend/src/hooks/use-uploads.ts
@@ -3,7 +3,12 @@ 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 type {
+ UploadInspection,
+ UploadReadOptionsRequest,
+ UploadReserved,
+ UploadState,
+} from "@/openapi";
export interface UploadProgress {
sent: number;
@@ -79,10 +84,16 @@ export interface DatasetUpload {
uploadId?: string;
rows?: number | null;
error?: string;
+ /** The first rows, their columns and a workbook's sheets, as the options read them. */
+ inspection?: UploadInspection;
+ options?: UploadReadOptionsRequest;
+ /** A person looked at the preview and chose Continue; sending waits for it. */
+ reviewed?: boolean;
}
export function useDatasetUploads() {
const [files, setFiles] = useState<DatasetUpload[]>([]);
+ const [previewId, setPreviewId] = useState<string | null>(null);
const controllers = useRef(new Map<string, AbortController>());
const queue = useRef(Promise.resolve());
@@ -91,6 +102,7 @@ export function useDatasetUploads() {
controllers.current.clear();
queue.current = Promise.resolve();
setFiles([]);
+ setPreviewId(null);
}, []);
useEffect(() => reset, [reset]);
@@ -117,15 +129,9 @@ export function useDatasetUploads() {
controller.signal
);
if (controller.signal.aborted) return;
- update({ status: "counting" });
- const inspected = await apiClient.uploads.uploadsInspectCreate(
- {
- id: uploadId,
- inspectUploadRequest: { size: entry.file.size },
- },
- { signal: controller.signal }
- );
- update({ rows: inspected.rows, status: "ready", uploadId });
+ update({ status: "counting", uploadId });
+ const inspection = await inspectUpload(uploadId, entry, controller.signal);
+ update({ inspection, rows: inspection.rows, status: "ready", uploadId });
} catch (err) {
if (!controller.signal.aborted) {
const error = await uploadError(err);
@@ -143,6 +149,7 @@ export function useDatasetUploads() {
file,
id: crypto.randomUUID(),
percent: 0,
+ reviewed: false,
status: "queued",
}));
setFiles((previous) => [...previous, ...entries]);
@@ -166,5 +173,54 @@ export function useDatasetUploads() {
[enqueue]
);
- return { add, files, remove, reset, retry };
+ /** Read an uploaded file again with other options; it needs a fresh review. */
+ const inspect = useCallback(async (entry: DatasetUpload, options: UploadReadOptionsRequest) => {
+ const uploadId = entry.uploadId;
+ if (!uploadId) return;
+ controllers.current.get(entry.id)?.abort();
+ const controller = new AbortController();
+ controllers.current.set(entry.id, controller);
+ const update = (patch: Partial<DatasetUpload>) => {
+ if (!controller.signal.aborted)
+ setFiles((previous) =>
+ previous.map((file) => (file.id === entry.id ? { ...file, ...patch } : file))
+ );
+ };
+ update({ error: undefined, options, reviewed: false, status: "counting" });
+ try {
+ const inspection = await inspectUpload(uploadId, { ...entry, options }, controller.signal);
+ update({ inspection, rows: inspection.rows, status: "ready" });
+ } catch (err) {
+ if (!controller.signal.aborted)
+ update({ error: (await uploadError(err)).message, status: "error" });
+ } finally {
+ if (controllers.current.get(entry.id) === controller) controllers.current.delete(entry.id);
+ }
+ }, []);
+
+ const confirm = useCallback(
+ (id: string) =>
+ setFiles((previous) =>
+ previous.map((file) =>
+ file.id === id && file.status === "ready" ? { ...file, reviewed: true } : file
+ )
+ ),
+ []
+ );
+
+ return { add, confirm, files, inspect, previewId, remove, reset, retry, setPreviewId };
+}
+
+function inspectUpload(
+ uploadId: string,
+ entry: DatasetUpload,
+ signal: AbortSignal
+): Promise<UploadInspection> {
+ return apiClient.uploads.uploadsInspectCreate(
+ {
+ id: uploadId,
+ inspectUploadRequest: { options: entry.options, preview: true, size: entry.file.size },
+ },
+ { signal }
+ );
}
diff --git a/frontend/src/lib/visible-stream.test.ts b/frontend/src/lib/visible-stream.test.ts
new file mode 100644
index 00000000..0ce16077
--- /dev/null
+++ b/frontend/src/lib/visible-stream.test.ts
@@ -0,0 +1,52 @@
+// @vitest-environment jsdom
+// covers: console-logic
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { whilePageVisible } from "./visible-stream";
+
+let state: DocumentVisibilityState = "visible";
+Object.defineProperty(document, "visibilityState", { configurable: true, get: () => state });
+
+const show = (next: DocumentVisibilityState) => {
+ state = next;
+ document.dispatchEvent(new Event("visibilitychange"));
+};
+
+describe("whilePageVisible", () => {
+ afterEach(() => {
+ state = "visible";
+ });
+
+ it("closes the stream while the tab is hidden and opens one when it shows again", () => {
+ const stop = vi.fn();
+ const start = vi.fn(() => stop);
+ const release = whilePageVisible(start);
+ expect(start).toHaveBeenCalledTimes(1);
+
+ show("hidden");
+ expect(stop).toHaveBeenCalledTimes(1);
+ show("hidden");
+ expect(stop).toHaveBeenCalledTimes(1);
+
+ show("visible");
+ expect(start).toHaveBeenCalledTimes(2);
+ show("visible");
+ expect(start).toHaveBeenCalledTimes(2);
+
+ release();
+ expect(stop).toHaveBeenCalledTimes(2);
+ show("hidden");
+ show("visible");
+ expect(start).toHaveBeenCalledTimes(2);
+ });
+
+ it("opens nothing for a tab that starts hidden", () => {
+ state = "hidden";
+ const start = vi.fn(() => () => {});
+ const release = whilePageVisible(start);
+ expect(start).not.toHaveBeenCalled();
+ show("visible");
+ expect(start).toHaveBeenCalledTimes(1);
+ release();
+ });
+});
diff --git a/frontend/src/lib/visible-stream.ts b/frontend/src/lib/visible-stream.ts
new file mode 100644
index 00000000..1e871da7
--- /dev/null
+++ b/frontend/src/lib/visible-stream.ts
@@ -0,0 +1,19 @@
+/** Runs `start` while the tab is visible and calls the stop it returns when the tab hides.
+ * A hidden tab must release its HTTP/1 connection so ordinary API reads can proceed. */
+export function whilePageVisible(start: () => () => void) {
+ let stop: (() => void) | undefined;
+ const update = () => {
+ if (document.visibilityState === "hidden") {
+ stop?.();
+ stop = undefined;
+ } else if (!stop) {
+ stop = start();
+ }
+ };
+ document.addEventListener("visibilitychange", update);
+ update();
+ return () => {
+ document.removeEventListener("visibilitychange", update);
+ stop?.();
+ };
+}
diff --git a/frontend/src/openapi/.openapi-generator/FILES b/frontend/src/openapi/.openapi-generator/FILES
index bb0f29e0..5e9b0e84 100644
--- a/frontend/src/openapi/.openapi-generator/FILES
+++ b/frontend/src/openapi/.openapi-generator/FILES
@@ -171,9 +171,11 @@ models/DedicatedUsageBreakdown.ts
models/DedicatedUsagePoint.ts
models/DedicatedWriteRequest.ts
models/DefinitionSourceEnum.ts
+models/DelimiterEnum.ts
models/DeployedModel.ts
models/DeployedModelStatusEnum.ts
models/DeploymentProgress.ts
+models/EncodingEnum.ts
models/EvalCriterion.ts
models/EvalCriterionRequest.ts
models/EvalJudgeModelEnum.ts
@@ -477,6 +479,8 @@ models/TransferInputRequest.ts
models/TransferReadiness.ts
models/TriggerEnum.ts
models/UploadInspection.ts
+models/UploadReadOptions.ts
+models/UploadReadOptionsRequest.ts
models/UploadReserved.ts
models/UploadState.ts
models/UserMe.ts
diff --git a/frontend/src/openapi/apis/UploadsApi.ts b/frontend/src/openapi/apis/UploadsApi.ts
index a8e77318..585bac79 100644
--- a/frontend/src/openapi/apis/UploadsApi.ts
+++ b/frontend/src/openapi/apis/UploadsApi.ts
@@ -187,7 +187,7 @@ export class UploadsApi extends runtime.BaseAPI {
/**
* Parsers must stay declared on the class: ``@action`` initkwargs only apply through the router, so an action-level parser silently reverts elsewhere.
- * Validate an uploaded file and count its rows
+ * Validate an uploaded file, count its rows and preview them
*/
async uploadsInspectCreateRaw(requestParameters: UploadsInspectCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<UploadInspection>> {
if (requestParameters['id'] == null) {
@@ -247,7 +247,7 @@ export class UploadsApi extends runtime.BaseAPI {
/**
* Parsers must stay declared on the class: ``@action`` initkwargs only apply through the router, so an action-level parser silently reverts elsewhere.
- * Validate an uploaded file and count its rows
+ * Validate an uploaded file, count its rows and preview them
*/
async uploadsInspectCreate(requestParameters: UploadsInspectCreateRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<UploadInspection> {
const response = await this.uploadsInspectCreateRaw(requestParameters, initOverrides);
diff --git a/frontend/src/openapi/models/DelimiterEnum.ts b/frontend/src/openapi/models/DelimiterEnum.ts
new file mode 100644
index 00000000..5b230a65
--- /dev/null
+++ b/frontend/src/openapi/models/DelimiterEnum.ts
@@ -0,0 +1,57 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+
+/**
+ * * `comma` - comma
+ * * `tab` - tab
+ * * `semicolon` - semicolon
+ * * `pipe` - pipe
+ * @export
+ */
+export const DelimiterEnum = {
+ comma: 'comma',
+ tab: 'tab',
+ semicolon: 'semicolon',
+ pipe: 'pipe'
+} as const;
+export type DelimiterEnum = typeof DelimiterEnum[keyof typeof DelimiterEnum];
+
+
+export function instanceOfDelimiterEnum(value: any): boolean {
+ for (const key in DelimiterEnum) {
+ if (Object.prototype.hasOwnProperty.call(DelimiterEnum, key)) {
+ if (DelimiterEnum[key as keyof typeof DelimiterEnum] === value) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+export function DelimiterEnumFromJSON(json: any): DelimiterEnum {
+ return DelimiterEnumFromJSONTyped(json, false);
+}
+
+export function DelimiterEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): DelimiterEnum {
+ return json as DelimiterEnum;
+}
+
+export function DelimiterEnumToJSON(value?: DelimiterEnum | null): any {
+ return value as any;
+}
+
+export function DelimiterEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): DelimiterEnum {
+ return value as DelimiterEnum;
+}
diff --git a/frontend/src/openapi/models/EncodingEnum.ts b/frontend/src/openapi/models/EncodingEnum.ts
new file mode 100644
index 00000000..345b4a25
--- /dev/null
+++ b/frontend/src/openapi/models/EncodingEnum.ts
@@ -0,0 +1,55 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+
+/**
+ * * `utf-8-sig` - utf-8-sig
+ * * `utf-16` - utf-16
+ * * `windows-1252` - windows-1252
+ * @export
+ */
+export const EncodingEnum = {
+ utf_8_sig: 'utf-8-sig',
+ utf_16: 'utf-16',
+ windows_1252: 'windows-1252'
+} as const;
+export type EncodingEnum = typeof EncodingEnum[keyof typeof EncodingEnum];
+
+
+export function instanceOfEncodingEnum(value: any): boolean {
+ for (const key in EncodingEnum) {
+ if (Object.prototype.hasOwnProperty.call(EncodingEnum, key)) {
+ if (EncodingEnum[key as keyof typeof EncodingEnum] === value) {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+export function EncodingEnumFromJSON(json: any): EncodingEnum {
+ return EncodingEnumFromJSONTyped(json, false);
+}
+
+export function EncodingEnumFromJSONTyped(json: any, ignoreDiscriminator: boolean): EncodingEnum {
+ return json as EncodingEnum;
+}
+
+export function EncodingEnumToJSON(value?: EncodingEnum | null): any {
+ return value as any;
+}
+
+export function EncodingEnumToJSONTyped(value: any, ignoreDiscriminator: boolean): EncodingEnum {
+ return value as EncodingEnum;
+}
diff --git a/frontend/src/openapi/models/ExperimentStep.ts b/frontend/src/openapi/models/ExperimentStep.ts
index c3ac52f0..b3c28146 100644
--- a/frontend/src/openapi/models/ExperimentStep.ts
+++ b/frontend/src/openapi/models/ExperimentStep.ts
@@ -81,6 +81,12 @@ export interface ExperimentStep {
* @memberof ExperimentStep
*/
error: string;
+ /**
+ * Once ended: tool, action, duration_seconds and, unless it completed, failure {code, retryable, exception}.
+ * @type {any}
+ * @memberof ExperimentStep
+ */
+ report: any | null;
/**
*
* @type {string}
@@ -120,6 +126,7 @@ export function instanceOfExperimentStep(value: object): value is ExperimentStep
if (!('receipts' in value) || value['receipts'] === undefined) return false;
if (!('calls' in value) || value['calls'] === undefined) return false;
if (!('error' in value) || value['error'] === undefined) return false;
+ if (!('report' in value) || value['report'] === undefined) return false;
if (!('reusedFrom' in value) || value['reusedFrom'] === undefined) return false;
if (!('startedAt' in value) || value['startedAt'] === undefined) return false;
if (!('endedAt' in value) || value['endedAt'] === undefined) return false;
@@ -146,6 +153,7 @@ export function ExperimentStepFromJSONTyped(json: any, ignoreDiscriminator: bool
'receipts': json['receipts'],
'calls': json['calls'],
'error': json['error'],
+ 'report': json['report'],
'reusedFrom': json['reused_from'],
'startedAt': (json['started_at'] == null ? null : new Date(json['started_at'])),
'endedAt': (json['ended_at'] == null ? null : new Date(json['ended_at'])),
@@ -173,6 +181,7 @@ export function ExperimentStepToJSONTyped(value?: ExperimentStep | null, ignoreD
'receipts': value['receipts'],
'calls': value['calls'],
'error': value['error'],
+ 'report': value['report'],
'reused_from': value['reusedFrom'],
'started_at': value['startedAt'] == null ? value['startedAt'] : value['startedAt'].toISOString(),
'ended_at': value['endedAt'] == null ? value['endedAt'] : value['endedAt'].toISOString(),
diff --git a/frontend/src/openapi/models/InspectUploadRequest.ts b/frontend/src/openapi/models/InspectUploadRequest.ts
index f9b7635c..307eea92 100644
--- a/frontend/src/openapi/models/InspectUploadRequest.ts
+++ b/frontend/src/openapi/models/InspectUploadRequest.ts
@@ -13,6 +13,14 @@
*/
import { mapValues } from '../runtime';
+import type { UploadReadOptionsRequest } from './UploadReadOptionsRequest';
+import {
+ UploadReadOptionsRequestFromJSON,
+ UploadReadOptionsRequestFromJSONTyped,
+ UploadReadOptionsRequestToJSON,
+ UploadReadOptionsRequestToJSONTyped,
+} from './UploadReadOptionsRequest';
+
/**
*
* @export
@@ -25,6 +33,18 @@ export interface InspectUploadRequest {
* @memberof InspectUploadRequest
*/
size: number;
+ /**
+ * Also return the first rows, their columns and the sheets.
+ * @type {boolean}
+ * @memberof InspectUploadRequest
+ */
+ preview?: boolean;
+ /**
+ *
+ * @type {UploadReadOptionsRequest}
+ * @memberof InspectUploadRequest
+ */
+ options?: UploadReadOptionsRequest;
}
/**
@@ -46,6 +66,8 @@ export function InspectUploadRequestFromJSONTyped(json: any, ignoreDiscriminator
return {
'size': json['size'],
+ 'preview': json['preview'] == null ? undefined : json['preview'],
+ 'options': json['options'] == null ? undefined : UploadReadOptionsRequestFromJSON(json['options']),
};
}
@@ -61,5 +83,7 @@ export function InspectUploadRequestToJSONTyped(value?: InspectUploadRequest | n
return {
'size': value['size'],
+ 'preview': value['preview'],
+ 'options': UploadReadOptionsRequestToJSON(value['options']),
};
}
diff --git a/frontend/src/openapi/models/UploadInspection.ts b/frontend/src/openapi/models/UploadInspection.ts
index 32b40086..74ba6367 100644
--- a/frontend/src/openapi/models/UploadInspection.ts
+++ b/frontend/src/openapi/models/UploadInspection.ts
@@ -13,6 +13,14 @@
*/
import { mapValues } from '../runtime';
+import type { UploadReadOptions } from './UploadReadOptions';
+import {
+ UploadReadOptionsFromJSON,
+ UploadReadOptionsFromJSONTyped,
+ UploadReadOptionsToJSON,
+ UploadReadOptionsToJSONTyped,
+} from './UploadReadOptions';
+
/**
*
* @export
@@ -37,6 +45,30 @@ export interface UploadInspection {
* @memberof UploadInspection
*/
rows: number | null;
+ /**
+ *
+ * @type {UploadReadOptions}
+ * @memberof UploadInspection
+ */
+ options?: UploadReadOptions;
+ /**
+ *
+ * @type {Array<string>}
+ * @memberof UploadInspection
+ */
+ sheets?: Array<string>;
+ /**
+ *
+ * @type {Array<string>}
+ * @memberof UploadInspection
+ */
+ columns?: Array<string>;
+ /**
+ *
+ * @type {Array<{ [key: string]: string; }>}
+ * @memberof UploadInspection
+ */
+ preview?: Array<{ [key: string]: string; }>;
}
/**
@@ -62,6 +94,10 @@ export function UploadInspectionFromJSONTyped(json: any, ignoreDiscriminator: bo
'filename': json['filename'],
'bytes': json['bytes'],
'rows': json['rows'],
+ 'options': json['options'] == null ? undefined : UploadReadOptionsFromJSON(json['options']),
+ 'sheets': json['sheets'] == null ? undefined : json['sheets'],
+ 'columns': json['columns'] == null ? undefined : json['columns'],
+ 'preview': json['preview'] == null ? undefined : json['preview'],
};
}
@@ -79,5 +115,9 @@ export function UploadInspectionToJSONTyped(value?: UploadInspection | null, ign
'filename': value['filename'],
'bytes': value['bytes'],
'rows': value['rows'],
+ 'options': UploadReadOptionsToJSON(value['options']),
+ 'sheets': value['sheets'],
+ 'columns': value['columns'],
+ 'preview': value['preview'],
};
}
diff --git a/frontend/src/openapi/models/UploadReadOptions.ts b/frontend/src/openapi/models/UploadReadOptions.ts
new file mode 100644
index 00000000..6f204494
--- /dev/null
+++ b/frontend/src/openapi/models/UploadReadOptions.ts
@@ -0,0 +1,105 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+import type { DelimiterEnum } from './DelimiterEnum';
+import {
+ DelimiterEnumFromJSON,
+ DelimiterEnumFromJSONTyped,
+ DelimiterEnumToJSON,
+ DelimiterEnumToJSONTyped,
+} from './DelimiterEnum';
+import type { EncodingEnum } from './EncodingEnum';
+import {
+ EncodingEnumFromJSON,
+ EncodingEnumFromJSONTyped,
+ EncodingEnumToJSON,
+ EncodingEnumToJSONTyped,
+} from './EncodingEnum';
+
+/**
+ *
+ * @export
+ * @interface UploadReadOptions
+ */
+export interface UploadReadOptions {
+ /**
+ *
+ * @type {DelimiterEnum}
+ * @memberof UploadReadOptions
+ */
+ delimiter?: DelimiterEnum;
+ /**
+ *
+ * @type {EncodingEnum}
+ * @memberof UploadReadOptions
+ */
+ encoding?: EncodingEnum;
+ /**
+ * Whether the first row holds the column names.
+ * @type {boolean}
+ * @memberof UploadReadOptions
+ */
+ header?: boolean;
+ /**
+ * One workbook sheet; absent reads every sheet.
+ * @type {string}
+ * @memberof UploadReadOptions
+ */
+ sheet?: string;
+}
+
+
+
+/**
+ * Check if a given object implements the UploadReadOptions interface.
+ */
+export function instanceOfUploadReadOptions(value: object): value is UploadReadOptions {
+ return true;
+}
+
+export function UploadReadOptionsFromJSON(json: any): UploadReadOptions {
+ return UploadReadOptionsFromJSONTyped(json, false);
+}
+
+export function UploadReadOptionsFromJSONTyped(json: any, ignoreDiscriminator: boolean): UploadReadOptions {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'delimiter': json['delimiter'] == null ? undefined : DelimiterEnumFromJSON(json['delimiter']),
+ 'encoding': json['encoding'] == null ? undefined : EncodingEnumFromJSON(json['encoding']),
+ 'header': json['header'] == null ? undefined : json['header'],
+ 'sheet': json['sheet'] == null ? undefined : json['sheet'],
+ };
+}
+
+export function UploadReadOptionsToJSON(json: any): UploadReadOptions {
+ return UploadReadOptionsToJSONTyped(json, false);
+}
+
+export function UploadReadOptionsToJSONTyped(value?: UploadReadOptions | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'delimiter': DelimiterEnumToJSON(value['delimiter']),
+ 'encoding': EncodingEnumToJSON(value['encoding']),
+ 'header': value['header'],
+ 'sheet': value['sheet'],
+ };
+}
diff --git a/frontend/src/openapi/models/UploadReadOptionsRequest.ts b/frontend/src/openapi/models/UploadReadOptionsRequest.ts
new file mode 100644
index 00000000..d55c8cdc
--- /dev/null
+++ b/frontend/src/openapi/models/UploadReadOptionsRequest.ts
@@ -0,0 +1,105 @@
+/* tslint:disable */
+/* eslint-disable */
+/**
+ * Overbae API
+ * Backend API for the Overclaw / Overmind platform.
+ *
+ * The version of the OpenAPI document: 2.0.0
+ *
+ *
+ * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
+ * https://openapi-generator.tech
+ * Do not edit the class manually.
+ */
+
+import { mapValues } from '../runtime';
+import type { DelimiterEnum } from './DelimiterEnum';
+import {
+ DelimiterEnumFromJSON,
+ DelimiterEnumFromJSONTyped,
+ DelimiterEnumToJSON,
+ DelimiterEnumToJSONTyped,
+} from './DelimiterEnum';
+import type { EncodingEnum } from './EncodingEnum';
+import {
+ EncodingEnumFromJSON,
+ EncodingEnumFromJSONTyped,
+ EncodingEnumToJSON,
+ EncodingEnumToJSONTyped,
+} from './EncodingEnum';
+
+/**
+ *
+ * @export
+ * @interface UploadReadOptionsRequest
+ */
+export interface UploadReadOptionsRequest {
+ /**
+ *
+ * @type {DelimiterEnum}
+ * @memberof UploadReadOptionsRequest
+ */
+ delimiter?: DelimiterEnum;
+ /**
+ *
+ * @type {EncodingEnum}
+ * @memberof UploadReadOptionsRequest
+ */
+ encoding?: EncodingEnum;
+ /**
+ * Whether the first row holds the column names.
+ * @type {boolean}
+ * @memberof UploadReadOptionsRequest
+ */
+ header?: boolean;
+ /**
+ * One workbook sheet; absent reads every sheet.
+ * @type {string}
+ * @memberof UploadReadOptionsRequest
+ */
+ sheet?: string;
+}
+
+
+
+/**
+ * Check if a given object implements the UploadReadOptionsRequest interface.
+ */
+export function instanceOfUploadReadOptionsRequest(value: object): value is UploadReadOptionsRequest {
+ return true;
+}
+
+export function UploadReadOptionsRequestFromJSON(json: any): UploadReadOptionsRequest {
+ return UploadReadOptionsRequestFromJSONTyped(json, false);
+}
+
+export function UploadReadOptionsRequestFromJSONTyped(json: any, ignoreDiscriminator: boolean): UploadReadOptionsRequest {
+ if (json == null) {
+ return json;
+ }
+ return {
+
+ 'delimiter': json['delimiter'] == null ? undefined : DelimiterEnumFromJSON(json['delimiter']),
+ 'encoding': json['encoding'] == null ? undefined : EncodingEnumFromJSON(json['encoding']),
+ 'header': json['header'] == null ? undefined : json['header'],
+ 'sheet': json['sheet'] == null ? undefined : json['sheet'],
+ };
+}
+
+export function UploadReadOptionsRequestToJSON(json: any): UploadReadOptionsRequest {
+ return UploadReadOptionsRequestToJSONTyped(json, false);
+}
+
+export function UploadReadOptionsRequestToJSONTyped(value?: UploadReadOptionsRequest | null, ignoreDiscriminator: boolean = false): any {
+ if (value == null) {
+ return value;
+ }
+
+ return {
+
+ 'delimiter': DelimiterEnumToJSON(value['delimiter']),
+ 'encoding': EncodingEnumToJSON(value['encoding']),
+ 'header': value['header'],
+ 'sheet': value['sheet'],
+ };
+}
diff --git a/frontend/src/openapi/models/index.ts b/frontend/src/openapi/models/index.ts
index b4e908d2..d3997ef2 100644
--- a/frontend/src/openapi/models/index.ts
+++ b/frontend/src/openapi/models/index.ts
@@ -126,9 +126,11 @@ export * from './DedicatedUsageBreakdown';
export * from './DedicatedUsagePoint';
export * from './DedicatedWriteRequest';
export * from './DefinitionSourceEnum';
+export * from './DelimiterEnum';
export * from './DeployedModel';
export * from './DeployedModelStatusEnum';
export * from './DeploymentProgress';
+export * from './EncodingEnum';
export * from './EvalCriterion';
export * from './EvalCriterionRequest';
export * from './EvalJudgeModelEnum';
@@ -432,6 +434,8 @@ export * from './TransferInputRequest';
export * from './TransferReadiness';
export * from './TriggerEnum';
export * from './UploadInspection';
+export * from './UploadReadOptions';
+export * from './UploadReadOptionsRequest';
export * from './UploadReserved';
export * from './UploadState';
export * from './UserMe';
diff --git a/frontend/src/routes/_auth.tsx b/frontend/src/routes/_auth.tsx
index b0a81282..779ce472 100644
--- a/frontend/src/routes/_auth.tsx
+++ b/frontend/src/routes/_auth.tsx
@@ -15,6 +15,12 @@ import { ConnectionScene } from "@/components/connection-scene";
import { WorkshopSidebar } from "@/components/datasets/workshop-sidebar";
import { CreateAccountDialog } from "@/components/guest/create-account-dialog";
import { AuthenticationLoadingState } from "@/components/route-error";
+import {
+ ChatSidebar,
+ ChatSidebarProvider,
+ ChatToggle,
+ useChatSidebar,
+} from "@/components/workspace/chat-sidebar";
import { type HomeSearch, HomeWorkspace } from "@/components/workspace/home-workspace";
import { WorkspaceTabs } from "@/components/workspace/workspace-tabs";
import { useAuthContext } from "@/contexts/auth-context";
@@ -283,6 +289,9 @@ function RootLayout() {
const flowFull = useRouterState({
select: (s) => (s.location.search as { flowFull?: boolean }).flowFull === true,
});
+ const shell = useRef<HTMLDivElement>(null);
+ const chatToggle = useRef<HTMLButtonElement>(null);
+ const chat = useChatSidebar(pathname, shell);
return (
<WorkshopSidebarContext.Provider
@@ -295,64 +304,74 @@ function RootLayout() {
},
}}
>
- <SidebarProvider defaultOpen={false}>
- <AppSidebar onSearchOpen={() => setCmdOpen(true)} />
- <CommandPalette onOpenChange={setCmdOpen} open={cmdOpen} />
- <SidebarInset className="min-w-0 bg-sidebar">
- <div className="flex h-svh min-w-0 flex-col p-2" data-workspace-shell>
- <WorkspaceTabs
- key={projectId ?? "no-project"}
- onClosed={homes.close}
- title={crumbs.at(-1)?.label ?? "Workspace"}
- />
+ <ChatSidebarProvider sidebar={chat}>
+ <SidebarProvider defaultOpen={false}>
+ <AppSidebar onSearchOpen={() => setCmdOpen(true)} />
+ <CommandPalette onOpenChange={setCmdOpen} open={cmdOpen} />
+ <SidebarInset className="min-w-0 bg-sidebar">
<div
- className={cn(
- "grid min-h-0 flex-1 min-w-0 overflow-clip rounded-b-md border border-t-0 border-border transition-[grid-template-columns] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
- workshopOpen
- ? "grid-cols-[minmax(0,1fr)_0px] duration-300 md:grid-cols-[248px_minmax(0,1fr)]"
- : "grid-cols-[0px_minmax(0,1fr)] duration-200"
- )}
+ className="relative grid h-svh min-w-0 grid-cols-[minmax(0,1fr)_auto_auto] grid-rows-[auto_minmax(0,1fr)] p-2"
+ data-workspace-shell
+ ref={shell}
>
- <WorkshopSidebar open={workshopOpen} />
+ <div className="col-span-3 min-w-0">
+ <WorkspaceTabs
+ key={projectId ?? "no-project"}
+ onClosed={homes.close}
+ title={crumbs.at(-1)?.label ?? "Workspace"}
+ />
+ </div>
<div
- aria-hidden={mobile && workshopOpen ? true : undefined}
className={cn(
- "flex min-h-0 min-w-0 flex-col bg-card",
- mobile && workshopOpen && "invisible"
+ "relative col-start-1 row-start-2 grid min-h-0 min-w-0 overflow-clip rounded-md border border-border transition-[grid-template-columns] ease-[cubic-bezier(0.22,1,0.36,1)] motion-reduce:transition-none",
+ workshopOpen
+ ? "grid-cols-[minmax(0,1fr)_0px] duration-300 md:grid-cols-[248px_minmax(0,1fr)]"
+ : "grid-cols-[0px_minmax(0,1fr)] duration-200"
)}
- inert={mobile && workshopOpen}
>
- {/* relative: absolute descendants (e.g. sr-only spans in pagination
- buttons) must resolve their containing block inside this clipper —
- otherwise they escape to the ICB, extend the hidden-overflow body,
- and any focus/scrollIntoView shoves the whole shell off screen. */}
+ <ChatToggle ref={chatToggle} sidebar={chat} />
+ <WorkshopSidebar open={workshopOpen} />
<div
- aria-label={crumbs.at(-1)?.label ?? "Workspace"}
+ aria-hidden={mobile && workshopOpen ? true : undefined}
className={cn(
- "relative flex min-h-0 flex-1 flex-col",
- flowFull || pathname === "/" || pathname.startsWith("/experiments/")
- ? "overflow-hidden p-0"
- : "overflow-y-auto scroll-fade-y p-4 md:p-6"
+ "flex min-h-0 min-w-0 flex-col bg-card",
+ mobile && workshopOpen && "invisible"
)}
- id="workspace-panel"
- role="tabpanel"
+ inert={mobile && workshopOpen}
>
- {homes.homes.map((home) => (
- <div
- className={home.active ? "flex min-h-0 flex-1 flex-col" : "hidden"}
- inert={!home.active}
- key={home.key}
- >
- <HomeWorkspace active={home.active} search={home.search} />
- </div>
- ))}
- <Outlet />
+ {/* relative: absolute descendants (e.g. sr-only spans in pagination
+ buttons) must resolve their containing block inside this clipper —
+ otherwise they escape to the ICB, extend the hidden-overflow body,
+ and any focus/scrollIntoView shoves the whole shell off screen. */}
+ <div
+ aria-label={crumbs.at(-1)?.label ?? "Workspace"}
+ className={cn(
+ "relative flex min-h-0 flex-1 flex-col",
+ flowFull || pathname === "/" || pathname.startsWith("/experiments/")
+ ? "overflow-hidden p-0"
+ : "overflow-y-auto scroll-fade-y p-4 md:p-6"
+ )}
+ id="workspace-panel"
+ role="tabpanel"
+ >
+ {homes.homes.map((home) => (
+ <div
+ className={home.active ? "flex min-h-0 flex-1 flex-col" : "hidden"}
+ inert={!home.active}
+ key={home.key}
+ >
+ <HomeWorkspace active={home.active} search={home.search} />
+ </div>
+ ))}
+ <Outlet />
+ </div>
</div>
</div>
+ <ChatSidebar sidebar={chat} toggle={chatToggle} />
</div>
- </div>
- </SidebarInset>
- </SidebarProvider>
+ </SidebarInset>
+ </SidebarProvider>
+ </ChatSidebarProvider>
</WorkshopSidebarContext.Provider>
);
}
diff --git a/frontend/src/routes/_auth/experiments.$experimentId.tsx b/frontend/src/routes/_auth/experiments.$experimentId.tsx
index 619ab2d8..1ece652d 100644
--- a/frontend/src/routes/_auth/experiments.$experimentId.tsx
+++ b/frontend/src/routes/_auth/experiments.$experimentId.tsx
@@ -5,7 +5,7 @@ import { createFileRoute, useBlocker } from "@tanstack/react-router";
import z from "zod";
import apiClient from "@/client";
-import { AssistantDock } from "@/components/assistant/assistant-dock";
+import { AssistantChat } from "@/components/assistant/assistant-chat";
import { NotesAndSpend, ProposalCards } from "@/components/experiments/experiment-panel";
import {
asFlow,
@@ -16,6 +16,8 @@ import {
newNodeId,
removeNode,
runLabel,
+ STAGE_COLORS,
+ STAGE_ICONS,
} from "@/components/experiments/flow";
import { FlowInterface } from "@/components/experiments/flow-interface";
import { RunFlow } from "@/components/experiments/run-flow";
@@ -33,6 +35,7 @@ import { EmptyState } from "@/components/ui/empty-state";
import { Icon } from "@/components/ui/icons";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { LoadingState } from "@/components/ui/spinner";
+import { ChatPanel } from "@/components/workspace/chat-sidebar";
import { type AssistantStreamEvent, useAssistantThread } from "@/hooks/use-assistant-thread";
import { useEventStream } from "@/hooks/use-event-stream";
import {
@@ -45,7 +48,8 @@ import {
} from "@/hooks/use-experiments";
import { errorMessage } from "@/lib/notify";
import { projectIdSearchSchema } from "@/lib/schemas";
-import type { ExperimentDetail, PinnedDataset } from "@/openapi";
+import { cn } from "@/lib/utils";
+import type { ExperimentDetail, ExperimentRunSummary, PinnedDataset } from "@/openapi";
export const Route = createFileRoute("/_auth/experiments/$experimentId")({
component: ExperimentPage,
@@ -58,6 +62,16 @@ export const Route = createFileRoute("/_auth/experiments/$experimentId")({
const sameFlow = (a: FlowDocument, b: FlowDocument) => JSON.stringify(a) === JSON.stringify(b);
+/** What the chat offers to ask, from where the shown run stands. */
+function chatSuggestions(run: ExperimentRunSummary | undefined) {
+ if (!run) return ["Review this experiment plan and suggest the next step."];
+ if (run.state === "running" || run.state === "stopping")
+ return ["Summarize progress and flag anything that needs my input."];
+ if (run.state === "completed")
+ return ["Summarize the experiment outcome and suggest the next step."];
+ return ["Explain what stopped this experiment and suggest the next step."];
+}
+
function ExperimentPage() {
const { experimentId } = Route.useParams();
const { projectId } = Route.useSearch();
@@ -305,7 +319,12 @@ function ExperimentEditor({ detail }: { detail: ExperimentDetail }) {
</Alert>
)}
<div className="relative flex min-h-0 flex-1">
- <ProposalCards detail={detail} />
+ <ProposalCards
+ detail={detail}
+ onDenied={(text) =>
+ assistant.send.mutate({ cells: [], requestKey: crypto.randomUUID(), text })
+ }
+ />
{draft.nodes.length ? (
<StageCanvas
below={renderBelow}
@@ -323,7 +342,7 @@ function ExperimentEditor({ detail }: { detail: ExperimentDetail }) {
/>
)}
</div>
- <div className="absolute top-3 right-3 z-10 flex gap-1.5" hidden={!!focusedNode}>
+ <div className="absolute top-3 right-12 z-10 flex gap-1.5" hidden={!!focusedNode}>
<NotesAndSpend detail={detail} />
<Popover>
<PopoverTrigger asChild>
@@ -522,14 +541,34 @@ function ExperimentEditor({ detail }: { detail: ExperimentDetail }) {
))}
</DialogContent>
</Dialog>
- <AssistantDock
- assistant={assistant}
- idle="Ask about the experiment or describe a change…"
- label="Experiment chat"
- placeholder="Ask about the experiment or describe a change…"
- projectId={detail.project}
- readOnly={locked ? "Return to the latest revision to send a message" : undefined}
- />
+ <ChatPanel>
+ <AssistantChat
+ assistant={assistant}
+ label="Experiment chat"
+ nodes={draft.nodes.map((node) => {
+ const Glyph = STAGE_ICONS[node.kind] ?? Icon.code;
+ const group = catalog.get(node.kind)?.group ?? "";
+ return {
+ group: "Steps",
+ href: `#node=${encodeURIComponent(node.id)}`,
+ icon: (
+ <Glyph
+ className={cn(
+ "size-4 shrink-0",
+ STAGE_COLORS[group] ?? "text-muted-foreground"
+ )}
+ />
+ ),
+ id: node.id,
+ label: node.title,
+ };
+ })}
+ onNode={select}
+ projectId={detail.project}
+ readOnly={locked ? "Return to the latest revision to send a message" : undefined}
+ suggestions={chatSuggestions(shownRun)}
+ />
+ </ChatPanel>
</div>
<ConfirmDialog
confirmLabel="Load latest"
diff --git a/frontend/src/styles.css b/frontend/src/styles.css
index ab7a9545..77004641 100644
--- a/frontend/src/styles.css
+++ b/frontend/src/styles.css
@@ -765,219 +765,248 @@ body:has(
/* In the components layer, so a utility on the same element wins. */
@layer components {
- /* Assistant chat: a bar at the bottom of the canvas that opens into a panel on the left. */
- .assistant-dock {
- interpolate-size: allow-keywords;
- left: 50%;
- width: min(48rem, calc(100% - 1.5rem));
- max-height: calc(100% - 1.5rem);
- transform: translateX(-50%);
- transition:
- left 560ms cubic-bezier(0.16, 1, 0.3, 1),
- width 560ms cubic-bezier(0.16, 1, 0.3, 1),
- transform 560ms cubic-bezier(0.16, 1, 0.3, 1),
- height 560ms cubic-bezier(0.16, 1, 0.3, 1);
- }
-
- .assistant-dock[data-panel="true"] {
- left: 0.75rem;
- width: min(var(--assistant-panel-width, 26rem), calc(100% - 1.5rem));
- height: calc(100% - 1.5rem);
- transform: translateX(0);
+ .assistant-chat-inner {
+ position: relative;
+ border-radius: var(--radius-sm);
+ transition: border-color 140ms ease;
}
- .assistant-dock[data-resizing="true"] {
- user-select: none;
- transition: none;
+ .assistant-chat-inner:focus-within {
+ border-color: var(--input);
}
- .assistant-dock-body {
- display: grid;
- grid-template-rows: 0fr;
+ /* Chat sidebar: beside the canvas from 640px, over the shell below it. */
+ .workspace-chat-panel {
+ position: absolute;
+ inset: 0;
+ z-index: 30;
+ pointer-events: none;
+ border: 0 solid var(--border);
+ border-radius: var(--radius);
opacity: 0;
+ filter: blur(4px);
+ transform: translateX(8px);
transition:
- grid-template-rows 420ms cubic-bezier(0.16, 1, 0.3, 1),
- opacity 180ms ease;
+ width 280ms cubic-bezier(0.22, 1, 0.36, 1),
+ opacity 200ms ease,
+ filter 200ms ease,
+ transform 280ms cubic-bezier(0.22, 1, 0.36, 1);
}
- .assistant-dock[data-expanded="true"] .assistant-dock-body {
- grid-template-rows: 1fr;
+ .workspace-chat-panel[data-open="true"] {
+ pointer-events: auto;
+ border-width: 1px;
opacity: 1;
+ filter: blur(0);
+ transform: translateX(0);
}
- .assistant-dock-footer {
- padding: 0.125rem 0.25rem;
+ .workspace-chat-divider {
+ flex: none;
+ width: 0;
+ overflow: hidden;
+ opacity: 0;
+ transition:
+ width 280ms cubic-bezier(0.22, 1, 0.36, 1),
+ opacity 200ms ease;
}
- .assistant-dock[data-panel="true"] .assistant-dock-footer {
- padding: 0.25rem 0.625rem 0.375rem;
+ .workspace-chat-divider[data-open="true"] {
+ width: 0.625rem;
+ opacity: 1;
}
- .assistant-dock[data-panel="true"] .assistant-composer-stack {
- margin: 0 0.375rem 0.375rem;
+ @media (min-width: 640px) {
+ .workspace-chat-panel {
+ position: static;
+ width: 0;
+ transform: none;
+ }
+ .workspace-chat-panel[data-open="true"] {
+ width: var(--chat-panel-width);
+ }
+ /* The content keeps its width while the panel opens and closes around it. */
+ .workspace-chat-content {
+ width: calc(var(--chat-panel-width) - 2px);
+ }
}
- .assistant-resize-handle {
- position: absolute;
- inset: 0 0 0 auto;
- z-index: 1;
- width: 0.5rem;
+ .workspace-chat-panel[data-resizing="true"],
+ .workspace-chat-divider[data-resizing="true"] {
+ user-select: none;
+ transition: none;
+ }
+
+ .chat-resize-handle {
+ display: grid;
+ place-items: center;
+ width: 0.625rem;
+ height: 100%;
touch-action: none;
cursor: col-resize;
+ user-select: none;
outline: none;
}
- .assistant-resize-handle::after {
- position: absolute;
- top: calc(50% - 1rem);
- right: 0;
+ .chat-resize-grip {
width: 2px;
- height: 2rem;
- content: "";
- background: var(--border);
- border-radius: var(--radius-sm);
- }
-
- .assistant-resize-handle:is(:hover, :focus-visible)::after,
- .assistant-dock[data-resizing="true"] .assistant-resize-handle::after {
- background: var(--primary);
+ height: 1.5rem;
+ background: var(--muted-foreground);
+ border-radius: 9999px;
+ opacity: 0;
+ transition: opacity 150ms ease;
}
- .assistant-conversation {
- padding: 0.75rem 1rem 3.5rem;
- scroll-padding-block: 1rem 3.5rem;
- scrollbar-width: thin;
+ .workspace-chat-divider:is(:hover, :focus-within, [data-resizing="true"]) .chat-resize-grip {
+ opacity: 1;
}
- /* The transcript fades into the dock surface at both ends. */
- .assistant-history::before,
- .assistant-history::after {
- position: absolute;
- pointer-events: none;
- content: "";
- backdrop-filter: blur(3px);
+ .chat-resize-handle:focus-visible .chat-resize-grip {
+ outline: 1px solid var(--ring);
+ outline-offset: 1px;
}
- .assistant-history::before {
- inset: 0 0 auto;
- z-index: 1;
- height: 1.5rem;
- background: linear-gradient(to bottom, var(--muted), transparent);
- mask-image: linear-gradient(to bottom, black, transparent);
+ .chat-thread-scroller {
+ scrollbar-gutter: stable both-edges;
+ scrollbar-color: var(--border) transparent;
+ scrollbar-width: thin;
}
- .assistant-history::after {
- inset: auto 0 0;
- height: 3.5rem;
- background: linear-gradient(to bottom, transparent, var(--muted) 90%);
- mask-image: linear-gradient(to bottom, transparent, black 85%);
+ .chat-user-bubble {
+ max-width: 92%;
+ padding: 8px 10px;
}
- .assistant-message + .assistant-message {
- margin-block-start: 1.5rem;
+ .chat-user-folded {
+ mask-image: linear-gradient(to bottom, black calc(100% - 3rem), transparent);
}
- .assistant-user-prompt {
- width: fit-content;
- max-width: 92%;
- padding: 0.5rem 0.75rem;
- margin-inline-start: auto;
+ /* The sidebar's type: 14px messages, 15px headings, 13px code and tables. */
+ .chat-user-text {
+ margin: 0;
+ font-size: 14px;
+ line-height: 1.45;
overflow-wrap: anywhere;
white-space: pre-wrap;
- background: var(--wash-raised);
- border: 1px solid var(--border);
- border-inline-end: 2px solid var(--input);
- border-radius: var(--radius-sm);
+ }
+ .chat-composer-stack {
+ gap: 8px;
+ padding: 8px 12px;
}
- .assistant-chat-inner {
- position: relative;
- border-radius: var(--radius-sm);
+ .chat-composer {
+ gap: 8px;
+ padding: 10px;
+ background: var(--background);
+ border: 1px solid var(--border);
+ border-radius: var(--radius);
transition: border-color 140ms ease;
}
- .assistant-chat-inner:focus-within {
- border-color: var(--input);
+ .chat-composer:focus-within {
+ border-color: var(--ring);
}
- .assistant-prompt-mark {
- position: absolute;
- top: 0.625rem;
- left: 0.625rem;
- font-size: 0.75rem;
- line-height: 1rem;
- color: var(--muted-foreground);
- pointer-events: none;
+ .chat-composer-input {
+ min-height: 56px;
+ max-height: 160px;
+ font-size: 14px;
+ line-height: 1.45;
+ caret-color: var(--foreground);
+ field-sizing: content;
}
- .assistant-dock[data-expanded="false"] .assistant-prompt-mark {
- display: none;
+ .chat-composer-footer {
+ gap: 4px;
}
- .assistant-chat-inner:focus-within .assistant-prompt-mark {
- color: var(--foreground);
+ .chat-composer-footer > :last-child {
+ margin-left: auto;
}
- .assistant-chat-input {
- padding: 0.625rem 0.75rem 0.25rem 1.75rem;
- caret-color: var(--foreground);
- caret-shape: block;
+ .thinking-eye {
+ image-rendering: pixelated;
}
- .assistant-tool-count {
- font-size: 0.625rem;
- text-transform: uppercase;
- letter-spacing: 0.08em;
+ @media (prefers-reduced-motion: reduce) {
+ .workspace-chat-panel,
+ .workspace-chat-divider {
+ filter: none;
+ transform: none;
+ transition: none;
+ }
+ .chat-resize-grip {
+ transition: none;
+ }
}
- /* The elbow that joins each tool call to its group. */
- .assistant-tool-row {
- position: relative;
+ .assistant-surface pre {
+ font-variant-numeric: tabular-nums;
}
- .assistant-tool-row::before {
- position: absolute;
- inset-inline-start: -0.875rem;
- top: -0.25rem;
- bottom: -0.25rem;
- pointer-events: none;
- content: "";
- border-inline-start: 1px solid var(--border);
+ /* Chat replies: 15px body, 1.6 line height, 12px between blocks, headings at 1.3em and
+ 1.15em, code and tables at 0.86em. Element rules out-rank the renderer's spacing utilities. */
+ .chat-prose {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ font-size: 15px;
+ line-height: 1.6;
+ overflow-wrap: anywhere;
}
-
- .assistant-tool-row::after {
- position: absolute;
- inset-inline-start: -0.875rem;
- top: 0.25rem;
- width: 0.625rem;
- height: 0.625rem;
- pointer-events: none;
- content: "";
- border-block-end: 1px solid var(--border);
- border-inline-start: 1px solid var(--border);
- border-end-start-radius: 0.625rem;
+ .chat-prose :is(p, ul, ol, blockquote, h1, h2, h3, h4, h5, h6, hr) {
+ margin: 0;
}
-
- .assistant-tool-row:last-child::before {
- bottom: auto;
- height: 0.5rem;
+ .chat-prose :is(h1, h2, h3, h4, h5, h6) {
+ padding: 0;
+ font-weight: 600;
+ line-height: 1.35;
+ text-wrap: balance;
+ border: 0;
+ }
+ .chat-prose h1 {
+ font-size: 1.3em;
+ }
+ .chat-prose h2 {
+ font-size: 1.15em;
+ }
+ .chat-prose :is(h3, h4, h5, h6) {
+ font-size: 1em;
+ }
+ .chat-prose :is(code, table) {
+ font-size: 0.86em;
+ }
+ .chat-prose table {
+ line-height: 1.45;
}
- .assistant-surface pre {
- font-variant-numeric: tabular-nums;
+ .workspace-chat-panel .chat-prose {
+ font-size: 14px;
+ line-height: 1.45;
+ }
+ .workspace-chat-panel .chat-prose :is(h1, h2) {
+ margin-top: 4px;
+ font-size: 15px;
+ line-height: 1.4;
+ }
+ .workspace-chat-panel .chat-prose :is(h3, h4, h5, h6) {
+ margin-top: 4px;
+ font-size: 14px;
+ }
+ .workspace-chat-panel .chat-prose :is(ul, ol) {
+ padding-left: 22px;
+ }
+ .workspace-chat-panel .chat-prose :is(code, table, pre) {
+ font-size: 13px;
+ }
+ .workspace-chat-panel .chat-prose pre code {
+ font-size: inherit;
}
.assistant-result {
font-size: 0.8125rem;
}
- @media (prefers-reduced-motion: reduce) {
- .assistant-dock,
- .assistant-dock-body {
- transition: none;
- }
- }
-
/* Datasets landing: the composer over the star field, the dataset list as a sheet below. */
.assistant-stage {
--assistant-inset: 1rem;
@@ -1030,16 +1059,6 @@ body:has(
animation: blink 1.1s step-end infinite;
}
- .assistant-composer .assistant-prompt-mark {
- top: 1rem;
- left: 0.875rem;
- line-height: 1.25rem;
- }
-
- .assistant-composer .assistant-chat-input {
- padding: 1rem 1rem 1rem 2rem;
- }
-
.assistant-attachments {
scrollbar-width: thin;
}
@@ -1062,26 +1081,6 @@ body:has(
border-color: var(--input);
}
- /* The landing composer becomes the canvas dock across the navigation. */
- .assistant-surface {
- view-transition-name: assistant-chat;
- }
-
- ::view-transition-group(assistant-chat) {
- overflow: clip;
- border-radius: var(--radius-md);
- animation-duration: 700ms;
- animation-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
- }
-
- ::view-transition-old(assistant-chat),
- ::view-transition-new(assistant-chat) {
- height: 100%;
- object-fit: none;
- object-position: bottom;
- animation-duration: 350ms;
- }
-
@media (prefers-reduced-motion: reduce) {
.assistant-datasets,
.assistant-dataset-handle {
@@ -1090,11 +1089,6 @@ body:has(
.assistant-cursor {
animation: none;
}
- ::view-transition-group(assistant-chat),
- ::view-transition-old(assistant-chat),
- ::view-transition-new(assistant-chat) {
- animation-duration: 1ms;
- }
}
}
@@ -1190,3 +1184,34 @@ body:has(
animation: none;
}
}
+
+/* Text the chat's selection toolbar acts on stays marked while its field holds the focus. */
+::highlight(chat-selection) {
+ color: HighlightText;
+ background-color: Highlight;
+}
+
+/* A working label sweeps light across its text. */
+@media (prefers-reduced-motion: no-preference) and (forced-colors: none) {
+ .status-shimmer {
+ color: transparent;
+ background-image: linear-gradient(
+ 110deg,
+ var(--muted-foreground) 40%,
+ var(--foreground) 50%,
+ var(--muted-foreground) 60%
+ );
+ background-clip: text;
+ background-size: 250% 100%;
+ animation: status-shimmer 2s linear infinite;
+ }
+}
+
+@keyframes status-shimmer {
+ from {
+ background-position: 100% center;
+ }
+ to {
+ background-position: 0% center;
+ }
+}
diff --git a/modal_shared/training_monitoring.py b/modal_shared/training_monitoring.py
index 9428cb49..9d8b22a2 100644
--- a/modal_shared/training_monitoring.py
+++ b/modal_shared/training_monitoring.py
@@ -334,6 +334,11 @@ class MonitoringSchedule:
elif mode == "steps":
candidate = interval = self.policy["interval_steps"]
adaptation = "explicit_interval"
+ if mode == "adaptive":
+ # The overhead fraction is a target; a short run still gets intermediate checks.
+ run_length_interval = max(1, self.total_steps // min(6, self.policy["max_checks"]))
+ if interval > run_length_interval:
+ interval, adaptation = run_length_interval, "run_length_cadence"
self.interval_steps = interval
self.next_step, stop_reason = step + interval, None
conflicts = []
diff --git a/overbae/api/experiments.py b/overbae/api/experiments.py
index 91258c97..9dcc4685 100644
--- a/overbae/api/experiments.py
+++ b/overbae/api/experiments.py
@@ -120,6 +120,10 @@ class ExperimentStepSerializer(serializers.Serializer):
receipts = serializers.JSONField()
calls = serializers.JSONField()
error = serializers.CharField(allow_blank=True)
+ report = serializers.JSONField(
+ help_text="Once ended: tool, action, duration_seconds and, unless it completed, "
+ "failure {code, retryable, exception}."
+ )
reused_from = serializers.UUIDField(allow_null=True)
started_at = serializers.DateTimeField(allow_null=True)
ended_at = serializers.DateTimeField(allow_null=True)
diff --git a/overbae/api/serializers.py b/overbae/api/serializers.py
index 73f2dba5..bd55b6cc 100644
--- a/overbae/api/serializers.py
+++ b/overbae/api/serializers.py
@@ -330,27 +330,27 @@ def trace_receipt(spans) -> list[dict]:
"""One row per call that :func:`trace_usage_totals` counts, so the receipt sums to
the totals. Every unreported field stays ``None``."""
by_id = {span.span_id: span for span in spans}
+ # Full attributes, so twins of one response merge the token detail the usage slice omits.
rows = _leaf_usage_rows(
(s.trace_id, s.span_id, s.parent_span_id, s.trace_id, s.scope_name)
- + (s.start_time_ns, s.end_time_ns, s.usage)
+ + (s.start_time_ns, s.end_time_ns, {**(s.attributes or {}), **s.usage})
for s in sorted(spans, key=lambda span: span.start_time_ns or 0)
if s.usage is not None
)
receipt = []
- for _trace_id, span_id, usage in rows:
- attrs = by_id[span_id].attributes or {}
+ for _trace_id, span_id, facts in rows:
receipt.append(
{
"span_id": span_id,
"name": by_id[span_id].name,
- "model": _model_from_span_attributes(usage),
- "total_tokens": _total_tokens_from_span_attributes(usage),
- "total_cost": _total_cost_from_span_attributes(usage),
- "input_tokens": _first_int(attrs, PROMPT_TOKEN_KEYS),
- "output_tokens": _first_int(attrs, COMPLETION_TOKEN_KEYS),
- "cache_read_tokens": _cache_read_tokens_from_span_attributes(usage),
- "cache_write_tokens": _first_int(attrs, CACHE_WRITE_TOKEN_KEYS),
- "reasoning_tokens": _first_int(attrs, REASONING_TOKEN_KEYS),
+ "model": _model_from_span_attributes(facts),
+ "total_tokens": _total_tokens_from_span_attributes(facts),
+ "total_cost": _total_cost_from_span_attributes(facts),
+ "input_tokens": _first_int(facts, PROMPT_TOKEN_KEYS),
+ "output_tokens": _first_int(facts, COMPLETION_TOKEN_KEYS),
+ "cache_read_tokens": _cache_read_tokens_from_span_attributes(facts),
+ "cache_write_tokens": _first_int(facts, CACHE_WRITE_TOKEN_KEYS),
+ "reasoning_tokens": _first_int(facts, REASONING_TOKEN_KEYS),
}
)
return receipt
diff --git a/overbae/api/training_preparation.py b/overbae/api/training_preparation.py
index e656c66a..3a2a1ef7 100644
--- a/overbae/api/training_preparation.py
+++ b/overbae/api/training_preparation.py
@@ -10,7 +10,7 @@ from rest_framework.response import Response
from overbae.api.credit_gate import require_credits
from overbae.api.scoping import project_ids_for
from overbae.core.errors import InputValidationError
-from overbae.models import Dataset, DecisionJob, TrainingPreparation
+from overbae.models import Dataset, TrainingPreparation
from overbae.services.datasets.lifecycle import DatasetError
from overbae.services.training_preparation import begin_preparation, retry_preparation
from overbae.tasks.training_preparation import inspect_preparation
@@ -34,18 +34,13 @@ class TrainingPreparationSerializer(serializers.ModelSerializer):
@extend_schema_field(serializers.UUIDField(allow_null=True))
def get_training_job(self, obj):
- job_id = obj.training_jobs.order_by("created_at").values_list("id", flat=True).first()
- return str(job_id) if job_id else None
+ job = obj.current_training_job()
+ return str(job.pk) if job else None
@extend_schema_field(serializers.UUIDField(allow_null=True))
def get_decision_job(self, obj):
- job_id = (
- DecisionJob.objects.filter(finetuning_job__preparation=obj)
- .order_by("finetuning_job__created_at")
- .values_list("id", flat=True)
- .first()
- )
- return str(job_id) if job_id else None
+ identity = getattr(obj.current_training_job(), "decision_job", None)
+ return str(identity.pk) if identity else None
class Meta:
model = TrainingPreparation
diff --git a/overbae/api/uploads.py b/overbae/api/uploads.py
index 181f5798..b9059d9f 100644
--- a/overbae/api/uploads.py
+++ b/overbae/api/uploads.py
@@ -30,14 +30,36 @@ class UploadReservedSerializer(serializers.Serializer):
max_bytes = serializers.IntegerField()
+class UploadReadOptionsSerializer(serializers.Serializer):
+ delimiter = serializers.ChoiceField(choices=list(files.DELIMITERS), required=False)
+ encoding = serializers.ChoiceField(choices=files.ENCODINGS, required=False)
+ header = serializers.BooleanField(
+ required=False, help_text="Whether the first row holds the column names."
+ )
+ sheet = serializers.CharField(
+ max_length=255, required=False, help_text="One workbook sheet; absent reads every sheet."
+ )
+
+
class InspectUploadSerializer(serializers.Serializer):
size = serializers.IntegerField(min_value=0, max_value=files.MAX_UPLOAD_BYTES)
+ preview = serializers.BooleanField(
+ default=False, help_text="Also return the first rows, their columns and the sheets."
+ )
+ options = UploadReadOptionsSerializer(required=False)
class UploadInspectionSerializer(serializers.Serializer):
filename = serializers.CharField()
bytes = serializers.IntegerField()
rows = serializers.IntegerField(allow_null=True)
+ options = UploadReadOptionsSerializer(required=False)
+ sheets = serializers.ListField(child=serializers.CharField(), required=False)
+ columns = serializers.ListField(child=serializers.CharField(), required=False)
+ preview = serializers.ListField(
+ child=serializers.DictField(child=serializers.CharField(allow_blank=True)),
+ required=False,
+ )
class OctetStreamParser(BaseParser):
@@ -66,7 +88,7 @@ class UploadViewSet(viewsets.ViewSet):
raise PermissionDenied("Use the project-scoped dataset transfer receipt.")
@extend_schema(
- summary="Validate an uploaded file and count its rows",
+ summary="Validate an uploaded file, count its rows and preview them",
request=InspectUploadSerializer,
responses={200: UploadInspectionSerializer},
)
@@ -76,7 +98,7 @@ class UploadViewSet(viewsets.ViewSet):
payload = InspectUploadSerializer(data=request.data)
payload.is_valid(raise_exception=True)
try:
- result = files.inspect_upload(upload_id, size=payload.validated_data["size"])
+ result = files.inspect_upload(upload_id, **payload.validated_data)
except files.FileError as exc:
raise ValidationError({"detail": exc.detail}) from exc
return Response(UploadInspectionSerializer(result).data)
diff --git a/overbae/migrations/0081_experiment_step_report.py b/overbae/migrations/0081_experiment_step_report.py
new file mode 100644
index 00000000..423ac6d2
--- /dev/null
+++ b/overbae/migrations/0081_experiment_step_report.py
@@ -0,0 +1,17 @@
+# Generated by Django 6.0.8 on 2026-12-04 15:35
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("overbae", "0080_trigger_cap_credits"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="experimentstep",
+ name="report",
+ field=models.JSONField(default=dict),
+ ),
+ ]
diff --git a/overbae/modal/modal_sft_worker.py b/overbae/modal/modal_sft_worker.py
index 8f557847..c0f2f7b2 100644
--- a/overbae/modal/modal_sft_worker.py
+++ b/overbae/modal/modal_sft_worker.py
@@ -423,6 +423,12 @@ def mark_cancelled(run_id: str) -> dict:
@app.function(
image=light_image,
timeout=3600,
+ startup_timeout=300,
+ # One Python thread hashes, indexes and copies rows while the volume mount does its I/O;
+ # the monitoring plan holds one identity per row.
+ cpu=(2, 2),
+ memory=(8192, 8192),
+ retries=0,
volumes={DATA_MOUNT: sft_vol},
)
def upload_dataset(
diff --git a/overbae/modal/register_model.py b/overbae/modal/register_model.py
index 948eec46..139c1650 100644
--- a/overbae/modal/register_model.py
+++ b/overbae/modal/register_model.py
@@ -818,15 +818,20 @@ def _download_base_snapshot(repo_id: str, dest: Path, *, ignore_patterns: list[s
@app.function(
image=download_image,
timeout=4 * 60 * 60,
+ startup_timeout=300,
+ retries=0,
scaledown_window=2,
ephemeral_disk=524288,
volumes={WEIGHTS_MOUNT: weights_vol},
secrets=[inference_secret],
cpu=16.0,
+ memory=32768,
max_containers=1, # global mutex: never let two callers write one base dir
)
@modal.concurrent(max_inputs=1)
-@container_meter.metered(lambda base_model, **_: f"base_model:{base_model}", cpu=16.0)
+@container_meter.metered(
+ lambda base_model, **_: f"base_model:{base_model}", cpu=16.0, memory_gib=32.0
+)
def fetch_base_model(*, base_model: str) -> dict:
"""The single choke point for base downloads: ``max_containers=1`` plus ``max_inputs=1`` make
it a global mutex, so concurrent callers cannot corrupt a shared
diff --git a/overbae/models/experiments.py b/overbae/models/experiments.py
index f72af7d9..00692ad7 100644
--- a/overbae/models/experiments.py
+++ b/overbae/models/experiments.py
@@ -141,6 +141,8 @@ class ExperimentStep(models.Model):
# Every tool call it made, with its arguments and result summary.
calls = models.JSONField(default=list)
error = models.TextField(blank=True, default="")
+ # Written when it ends: services/experiments/failures.py.
+ report = models.JSONField(default=dict)
reused_from = models.ForeignKey("self", on_delete=models.SET_NULL, null=True, blank=True)
started_at = models.DateTimeField(null=True, blank=True)
ended_at = models.DateTimeField(null=True, blank=True)
diff --git a/overbae/models/finetuning.py b/overbae/models/finetuning.py
index 1397aa8c..a91c425e 100644
--- a/overbae/models/finetuning.py
+++ b/overbae/models/finetuning.py
@@ -30,6 +30,11 @@ class TrainingPreparation(models.Model):
touched_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
+ def current_training_job(self):
+ # A new request after a cancel adds a job; the cancelled one stays as history.
+ jobs = self.training_jobs.order_by("created_at")
+ return jobs.exclude(status="cancelled").first() or jobs.last()
+
class TrainingExperiment(Leased):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
diff --git a/overbae/services/datasets/files.py b/overbae/services/datasets/files.py
index bd27d92a..da5fdab2 100644
--- a/overbae/services/datasets/files.py
+++ b/overbae/services/datasets/files.py
@@ -11,6 +11,7 @@ from __future__ import annotations
import csv
import gzip
import io
+import itertools
import json
import logging
import math
@@ -27,6 +28,7 @@ import pyarrow.parquet as pq
from overbae.core.errors import InputValidationError
from overbae.services.datasets import documents, spreadsheets
+from overbae.services.datasets.store import EVIDENCE
logger = logging.getLogger(__name__)
@@ -48,6 +50,15 @@ UNSUPPORTED = (
"Use a CSV, TSV, JSON, JSONL, Parquet, XLSX, PDF, DOCX, Markdown, text, PNG, JPEG or WebP file."
)
+# How a delimited file or a workbook is read, as the import review sets it. An option that is
+# absent keeps the default: a sniffed separator, UTF-8, a header row, every sheet.
+DELIMITERS = {"comma": ",", "tab": "\t", "semicolon": ";", "pipe": "|"}
+ENCODING_NAMES = {"utf-8-sig": "UTF-8", "utf-16": "UTF-16", "windows-1252": "Windows-1252"}
+ENCODINGS = tuple(ENCODING_NAMES)
+PREVIEW_ROWS = 5
+PREVIEW_COLUMNS = 100
+PREVIEW_CELL_CHARS = 500
+
# A transcript cell is far longer than the csv module's 128 KB default.
csv.field_size_limit(MAX_UPLOAD_BYTES)
@@ -105,16 +116,40 @@ def _sniff_delimiter(sample: str, fallback: str) -> str:
return fallback
-def _iter_delimited(fh: io.TextIOBase, delimiter: str) -> Iterator[dict[str, Any]]:
+def read_options(raw: dict | None) -> dict[str, Any]:
+ """The reading options a person chose, checked; unknown keys and values are refused."""
+ options = dict(raw or {})
+ if set(options) - {"delimiter", "encoding", "header", "sheet"}:
+ raise FileError("Unsupported file reading option.")
+ if options.get("delimiter", "comma") not in DELIMITERS:
+ raise FileError("Choose a comma, tab, semicolon or pipe separator.")
+ if options.get("encoding", "utf-8-sig") not in ENCODINGS:
+ raise FileError("Choose UTF-8, UTF-16 or Windows-1252.")
+ if not isinstance(options.get("header", True), bool):
+ raise FileError("Say whether the first row holds the column names.")
+ if not isinstance(options.get("sheet", ""), str):
+ raise FileError("Choose a sheet by its name.")
+ return options
+
+
+def _iter_delimited(
+ fh: io.TextIOBase, delimiter: str, options: dict | None = None
+) -> Iterator[dict[str, Any]]:
+ options = options or {}
head = fh.read(64 * 1024)
fh.seek(0)
- reader = csv.reader(fh, delimiter=_sniff_delimiter(head, delimiter))
+ chosen = DELIMITERS.get(options.get("delimiter", ""))
+ reader = csv.reader(fh, delimiter=chosen or _sniff_delimiter(head, delimiter))
try:
- header = next(reader, None)
- if not header:
+ first = next(reader, None)
+ if not first:
raise FileError("The file has no header row.")
- header = clean_names(header)
- for cells in reader:
+ if options.get("header", True):
+ header, body = clean_names(first), reader
+ else:
+ header = [f"column_{index}" for index in range(1, len(first) + 1)]
+ body = itertools.chain([first], reader)
+ for cells in body:
if not cells:
continue
if len(cells) > len(header):
@@ -177,14 +212,18 @@ def _coerce_numeric_columns(rows: list[dict[str, Any]]) -> None:
row[name] = next(it) if row[name] not in (None, "") else None
-def _open_text(path: Path, name: str) -> io.TextIOBase:
+def _open_text(path: Path, name: str, encoding: str = "utf-8-sig") -> io.TextIOBase:
if name.endswith(".gz"):
- return io.TextIOWrapper(gzip.open(path, "rb"), encoding="utf-8-sig", newline="")
- return open(path, encoding="utf-8-sig", newline="")
+ return io.TextIOWrapper(gzip.open(path, "rb"), encoding=encoding, newline="")
+ return open(path, encoding=encoding, newline="")
def iter_stream_rows(
- fh: io.TextIOBase, *, filename: str, json_rows_field: str | None = None
+ fh: io.TextIOBase,
+ *,
+ filename: str,
+ json_rows_field: str | None = None,
+ options: dict | None = None,
) -> Iterator[dict[str, Any]]:
"""Rows from an open text stream, keyed off the file extension."""
name = (filename or "").lower().removesuffix(".gz")
@@ -193,9 +232,9 @@ def iter_stream_rows(
elif name.endswith(".json"):
yield from _iter_json(fh, json_rows_field)
elif name.endswith(".tsv"):
- yield from _iter_delimited(fh, "\t")
+ yield from _iter_delimited(fh, "\t", options)
elif name.endswith(".csv"):
- yield from _iter_delimited(fh, ",")
+ yield from _iter_delimited(fh, ",", options)
else:
raise FileError(UNSUPPORTED)
@@ -208,13 +247,20 @@ def _text_rows(fh: io.TextIOBase, name: str) -> list[dict[str, Any]]:
def iter_file_rows(
- path: Path, *, filename: str, json_rows_field: str | None = None, sheet: str | None = None
+ path: Path,
+ *,
+ filename: str,
+ json_rows_field: str | None = None,
+ sheet: str | None = None,
+ options: dict | None = None,
) -> Iterator[dict[str, Any]]:
- """``sheet`` names the one sheet of a workbook to read."""
+ """``sheet`` names the one sheet of a workbook to read; ``options`` are the reading
+ options from :func:`read_options`."""
+ options = options or {}
name = (filename or "").lower()
if name.endswith(".xlsx"):
try:
- yield from spreadsheets.rows(path, sheet or "")
+ yield from spreadsheets.rows(path, sheet or "", header=options.get("header", True))
return
except spreadsheets.SpreadsheetError as exc:
raise FileError(exc.detail) from exc
@@ -237,14 +283,21 @@ def iter_file_rows(
"— use JSONL for larger files."
)
try:
- with _open_text(path, name) as fh:
- yield from iter_stream_rows(fh, filename=bare, json_rows_field=json_rows_field)
+ with _open_text(path, name, options.get("encoding", "utf-8-sig")) as fh:
+ yield from iter_stream_rows(
+ fh, filename=bare, json_rows_field=json_rows_field, options=options
+ )
except UnicodeDecodeError as exc:
- raise FileError("The file is not UTF-8. Save it as UTF-8 and upload it again.") from exc
+ raise FileError(not_decoded(options)) from exc
except (gzip.BadGzipFile, EOFError) as exc:
raise FileError("The file is not readable gzip.") from exc
+def not_decoded(options: dict) -> str:
+ name = ENCODING_NAMES[options.get("encoding", "utf-8-sig")]
+ return f"The file is not {name}. Choose its encoding in the file settings."
+
+
class FileRows:
def __init__(
self,
@@ -253,15 +306,16 @@ class FileRows:
filename: str,
json_rows_field: str | None = None,
sheet: str | None = None,
+ options: dict | None = None,
):
self.path, self.filename, self.sheet = path, filename, sheet
- self.json_rows_field = json_rows_field
+ self.json_rows_field, self.options = json_rows_field, options
self.count = 0
names = {}
numeric = {}
delimited = filename.lower().removesuffix(".gz").endswith((".csv", ".tsv"))
for row in iter_file_rows(
- path, filename=filename, json_rows_field=json_rows_field, sheet=sheet
+ path, filename=filename, json_rows_field=json_rows_field, sheet=sheet, options=options
):
self.count += 1
for key, value in row.items():
@@ -280,6 +334,7 @@ class FileRows:
filename=self.filename,
json_rows_field=self.json_rows_field,
sheet=self.sheet,
+ options=self.options,
):
yield {
self.names[key]: (_number(value) if value not in (None, "") else None)
@@ -290,8 +345,15 @@ class FileRows:
def inspect_upload(
- upload_id: str, *, size: int, json_rows_field: str | None = None
+ upload_id: str,
+ *,
+ size: int,
+ json_rows_field: str | None = None,
+ preview: bool = False,
+ options: dict | None = None,
) -> dict[str, Any]:
+ """Count the upload's rows as ``options`` read them, and keep both for its landing.
+ With ``preview``, also return the first rows, their columns and a workbook's sheets."""
filename = upload_filename(upload_id)
if not filename or upload_received(upload_id) != size:
raise FileError("The upload is incomplete or has expired.")
@@ -305,12 +367,32 @@ def inspect_upload(
record = {"bytes": size, "mtime_ns": stored_stat(path).st_mtime_ns, "rows": None}
_inspection_path(upload_id).write_text(json.dumps(record), encoding="utf-8")
return {"filename": filename, "bytes": size, "rows": None}
+ options = read_options(options)
+ sample: list[dict[str, Any]] = []
+ sheets: list[str] = []
try:
+ if bare.endswith((".csv", ".tsv")):
+ encoding = options.setdefault("encoding", "utf-8-sig")
+ with _open_text(path, filename.lower(), encoding) as fh:
+ fallback = "\t" if bare.endswith(".tsv") else ","
+ sniffed = _sniff_delimiter(fh.read(64 * 1024), fallback)
+ options.setdefault("delimiter", {v: k for k, v in DELIMITERS.items()}[sniffed])
+ options.setdefault("header", True)
if bare.endswith(".xlsx"):
- rows = sum(
- 1 for sheet in spreadsheets.sheets(path) for _ in spreadsheets.rows(path, sheet)
- )
- elif bare.endswith(".parquet"):
+ sheets = spreadsheets.sheets(path)
+ if options.get("sheet") is not None and options["sheet"] not in sheets:
+ raise FileError("The workbook has no rows on that sheet.")
+ rows = 0
+ for sheet in [options["sheet"]] if "sheet" in options else sheets:
+ for row in iter_file_rows(path, filename=filename, sheet=sheet, options=options):
+ rows += 1
+ if (
+ preview
+ and len(sample) < PREVIEW_ROWS
+ and sheet == (options.get("sheet") or sheets[0])
+ ):
+ sample.append(row)
+ elif bare.endswith(".parquet") and not preview:
rows = pq.ParquetFile(path).metadata.num_rows
else:
if bare.endswith(".json") and size > JSON_ARRAY_MAX_BYTES:
@@ -318,16 +400,19 @@ def inspect_upload(
f"JSON files are capped at {JSON_ARRAY_MAX_BYTES // 1024**2} MB. "
"Use JSONL for larger files."
)
- with _open_text(path, filename.lower()) as fh:
- rows = sum(
- 1 for _ in iter_stream_rows(fh, filename=bare, json_rows_field=json_rows_field)
- )
+ rows = 0
+ for row in iter_file_rows(
+ path, filename=filename, json_rows_field=json_rows_field, options=options
+ ):
+ rows += 1
+ if preview and len(sample) < PREVIEW_ROWS:
+ sample.append(row)
except FileError:
raise
except spreadsheets.SpreadsheetError as exc:
raise FileError(exc.detail) from exc
except UnicodeDecodeError as exc:
- raise FileError("The file is not UTF-8. Save it as UTF-8 and upload it again.") from exc
+ raise FileError(not_decoded(options)) from exc
except (gzip.BadGzipFile, EOFError) as exc:
raise FileError("The file is not readable gzip.") from exc
except (OSError, ValueError, csv.Error, pa.ArrowException) as exc:
@@ -345,9 +430,27 @@ def inspect_upload(
"mtime_ns": stored_stat(path).st_mtime_ns,
"rows": rows,
"json_rows_field": json_rows_field,
+ "options": options,
}
_inspection_path(upload_id).write_text(json.dumps(record), encoding="utf-8")
- return {"filename": filename, "bytes": size, "rows": rows}
+ result = {"filename": filename, "bytes": size, "rows": rows}
+ if preview:
+ result |= {"options": options, "sheets": sheets, **_preview(sample)}
+ return result
+
+
+def _preview(sample: list[dict[str, Any]]) -> dict[str, Any]:
+ columns = list(dict.fromkeys(key for row in sample for key in row if key != EVIDENCE))[
+ :PREVIEW_COLUMNS
+ ]
+ rows = [
+ {
+ column: "" if row.get(column) is None else str(row[column])[:PREVIEW_CELL_CHARS]
+ for column in columns
+ }
+ for row in sample
+ ]
+ return {"columns": columns, "preview": rows}
def _inspection_path(upload_id: Any) -> Path:
diff --git a/overbae/services/datasets/imports.py b/overbae/services/datasets/imports.py
index 5e2f0ae6..c0c3d0d9 100644
--- a/overbae/services/datasets/imports.py
+++ b/overbae/services/datasets/imports.py
@@ -17,7 +17,7 @@ from django.db.models import DateTimeField, Exists, ExpressionWrapper, F, Q, Val
from django.db.models.functions import Least
from django.utils import timezone
-from overbae.models import Dataset, DatasetImport, User
+from overbae.models import Dataset, DatasetImport, DatasetLandingWork, User
from overbae.services.activity import asset, record, source_ready, update_task
from overbae.services.datasets import events, files, heartbeat, llm_calls, operations, paths
from overbae.services.datasets import land as landing
@@ -34,6 +34,7 @@ MAX_ATTEMPTS = 3
MAX_PUBLICATIONS = 8
RECONCILE_BATCH = 40
PUBLISH_LEASE_SECONDS = 30
+WORKER_STOPPED = "The import worker stopped before publication. Its source is retained."
@dataclass(frozen=True)
@@ -353,8 +354,6 @@ def resume(run_id):
def stopped_draft(dataset):
- from overbae.models import DatasetLandingWork
-
if (
dataset.state != Dataset.State.ERROR
or dataset.cells.exists()
@@ -369,9 +368,15 @@ def stopped_draft(dataset):
@transaction.atomic
def resume_dataset(dataset):
- run = DatasetImport.objects.filter(
- Q(dataset=dataset) | Q(evaluation=dataset), state=DatasetImport.State.BLOCKED
- ).first()
+ run = (
+ DatasetImport.objects.select_for_update()
+ .filter(Q(dataset=dataset) | Q(evaluation=dataset))
+ .first()
+ )
+ if run is not None and worker_stopped(run):
+ _block(run, "worker_timeout", WORKER_STOPPED)
+ if run is not None and run.state != DatasetImport.State.BLOCKED:
+ run = None
if run is None and (work := stopped_draft(dataset)) is not None:
run = queue_landing_receipt(dataset, work.pk, work.inputs, preserve_error=True)
if run is None:
@@ -381,6 +386,16 @@ def resume_dataset(dataset):
return dataset
+def worker_stopped(run):
+ """The reconciler blocks this run on its next pass; a resume need not wait for it."""
+ return (
+ run.state == DatasetImport.State.RUNNING
+ and run.lease_until is not None
+ and run.lease_until < timezone.now()
+ and DatasetLandingWork.objects.filter(pk=run.pk, state="failed").exists()
+ )
+
+
def status(dataset):
run = DatasetImport.objects.filter(Q(dataset=dataset) | Q(evaluation=dataset)).first()
if run is None:
@@ -393,7 +408,8 @@ def status(dataset):
"started_at": run.started_at.isoformat() if run.started_at else None,
"failure_code": run.failure_code,
"error": run.error,
- "can_resume": run.state == DatasetImport.State.BLOCKED and run.attempts < MAX_ATTEMPTS,
+ "can_resume": (run.state == DatasetImport.State.BLOCKED or worker_stopped(run))
+ and run.attempts < MAX_ATTEMPTS,
}
@@ -499,8 +515,6 @@ def reconcile():
and run.lease_until
and run.lease_until < now
):
- from overbae.models import DatasetLandingWork
-
if DatasetLandingWork.objects.filter(
pk=run.pk, state__in=("waiting", "admitted", "running")
).exists():
@@ -510,11 +524,7 @@ def reconcile():
run.attempts >= MAX_ATTEMPTS
or DatasetLandingWork.objects.filter(pk=run.pk).exists()
):
- _block(
- run,
- "worker_timeout",
- "The import worker stopped before publication. Its source is retained.",
- )
+ _block(run, "worker_timeout", WORKER_STOPPED)
else:
try:
_requeue(run)
@@ -809,6 +819,9 @@ def execute(task_id, inputs):
return {"status": "retry", "error": str(exc)}
fail(claimed, str(exc), code=getattr(exc, "code", "import_failed"))
return {"status": "failed", "error": str(exc)}
+ except BaseException:
+ fail(claimed, WORKER_STOPPED, code="worker_timeout")
+ raise
finally:
beat.set()
try:
diff --git a/overbae/services/datasets/land.py b/overbae/services/datasets/land.py
index 36d81ebb..df1c1431 100644
--- a/overbae/services/datasets/land.py
+++ b/overbae/services/datasets/land.py
@@ -271,6 +271,7 @@ def _read_one(
filename: str,
on_progress: Callable[[dict], None] | None = None,
json_rows_field: str | None = None,
+ options: dict | None = None,
project_id=None,
ocr_languages=None,
) -> list[Landing]:
@@ -300,17 +301,25 @@ def _read_one(
output.write(json.dumps(row) + "\n")
parts = [(files.FileRows(cached, filename="extracted.jsonl"), extraction)]
elif filename.lower().endswith(".xlsx"):
+ chosen = (options or {}).get("sheet")
parts = [
- (files.FileRows(path, filename=filename, sheet=sheet), {"sheet": sheet})
- for sheet in spreadsheets.sheets(path)
+ (
+ files.FileRows(path, filename=filename, sheet=sheet, options=options),
+ {"sheet": sheet, **({"read_options": options} if options else {})},
+ )
+ for sheet in ([chosen] if chosen else spreadsheets.sheets(path))
]
else:
- rows = files.FileRows(path, filename=filename, json_rows_field=json_rows_field)
+ rows = files.FileRows(
+ path, filename=filename, json_rows_field=json_rows_field, options=options
+ )
extraction = (
{"json_rows_field": json_rows_field, "selection": "explicit"}
if json_rows_field
else {}
)
+ if options:
+ extraction["read_options"] = options
parts = [(rows, extraction)]
except (files.FileError, documents.DocumentError, spreadsheets.SpreadsheetError) as exc:
progress({"stage": "failed"})
@@ -444,6 +453,7 @@ def read_uploads(
if on_progress:
on_progress({"completed": index, "total": len(upload_ids), **detail})
+ inspected = files.inspection(upload_id) or {}
parts.extend(
_read_one(
path,
@@ -451,7 +461,8 @@ def read_uploads(
on_progress=progress,
project_id=project_id,
ocr_languages=ocr_languages,
- json_rows_field=(files.inspection(upload_id) or {}).get("json_rows_field"),
+ json_rows_field=inspected.get("json_rows_field"),
+ options=inspected.get("options"),
)
)
if on_progress:
diff --git a/overbae/services/datasets/spreadsheets.py b/overbae/services/datasets/spreadsheets.py
index 5798f23c..9d78e9be 100644
--- a/overbae/services/datasets/spreadsheets.py
+++ b/overbae/services/datasets/spreadsheets.py
@@ -9,6 +9,7 @@ a duration.
from __future__ import annotations
import datetime as dt
+import itertools
from collections.abc import Iterator
from contextlib import contextmanager
from pathlib import Path
@@ -87,7 +88,8 @@ def sheets(path: Path) -> list[str]:
return found
-def rows(path: Path, sheet: str) -> Iterator[dict[str, Any]]:
+def rows(path: Path, sheet: str, *, header: bool = True) -> Iterator[dict[str, Any]]:
+ """Without ``header`` the first row is data and the columns are ``column_N``."""
with _workbook(path) as workbook:
if sheet not in workbook.sheetnames:
raise SpreadsheetError(f"The workbook has no sheet {sheet!r}.")
@@ -95,15 +97,22 @@ def rows(path: Path, sheet: str) -> Iterator[dict[str, Any]]:
first = next(numbered, None)
if first is None:
return
- header = _header(sheet, first[1])
+ if header:
+ names = _header(sheet, first[1])
+ else:
+ values = [cell.value for cell in first[1]]
+ while values and values[-1] is None:
+ values.pop()
+ names = [f"column_{index}" for index in range(1, len(values) + 1)]
+ numbered = itertools.chain([first], numbered)
for number, cells in numbered:
- if any(cell.value is not None for cell in cells[len(header) :]):
+ if any(cell.value is not None for cell in cells[len(names) :]):
raise SpreadsheetError(
f"Sheet {sheet!r} row {number} has a value right of its last header cell."
)
- record: dict[str, Any] = dict.fromkeys(header)
+ record: dict[str, Any] = dict.fromkeys(names)
kinds = {}
- for name, cell in zip(header, cells, strict=False):
+ for name, cell in zip(names, cells, strict=False):
value = cell.value
if isinstance(value, dt.timedelta):
kinds[name] = "duration_seconds"
diff --git a/overbae/services/decision_benchmark_scoring.py b/overbae/services/decision_benchmark_scoring.py
index 0ca69d2e..86269cbe 100644
--- a/overbae/services/decision_benchmark_scoring.py
+++ b/overbae/services/decision_benchmark_scoring.py
@@ -116,14 +116,25 @@ class Accumulator:
if self.out_of_scope_label is not None:
result["out_of_scope_detection"] = binary_detection(self.out_of_scope)
if self.fixed_labels and self.confusion:
- f1 = []
- for label in range(len(self.labels)):
+ per_label = []
+ for label, name in enumerate(self.labels):
tp = self.confusion[label, label]
target_count = sum(n for (a, _), n in self.confusion.items() if a == label)
predicted_count = sum(n for (_, b), n in self.confusion.items() if b == label)
denominator = target_count + predicted_count
- f1.append(2 * tp / denominator if denominator else 0)
- result["macro_f1"] = math.fsum(f1) / len(f1)
+ per_label.append(
+ {
+ "label": name,
+ "support": target_count,
+ "predicted": predicted_count,
+ "correct": tp,
+ "precision": tp / predicted_count if predicted_count else None,
+ "recall": tp / target_count if target_count else None,
+ "f1": 2 * tp / denominator if denominator else None,
+ }
+ )
+ result["labels"] = per_label
+ result["macro_f1"] = math.fsum(row["f1"] or 0 for row in per_label) / len(per_label)
if self.confidence:
bins = [[] for _ in range(15)]
for confidence, mass in self.confidence:
diff --git a/overbae/services/experiments/describe.py b/overbae/services/experiments/describe.py
index 96dd8772..5cc99aeb 100644
--- a/overbae/services/experiments/describe.py
+++ b/overbae/services/experiments/describe.py
@@ -97,6 +97,7 @@ def step(found: ExperimentStep) -> dict:
"receipts": found.receipts,
"calls": found.calls,
"error": found.error,
+ "report": found.report,
"reused_from": str(found.reused_from_id) if found.reused_from_id else None,
"started_at": found.started_at,
"ended_at": found.ended_at,
@@ -137,6 +138,7 @@ def _stage_states(found: ExperimentRun) -> list[dict]:
"node": item.node,
"state": item.state,
**({"error": item.error} if item.error else {}),
+ **({"failure": item.report["failure"]} if "failure" in item.report else {}),
**({"outputs": item.outputs} if item.outputs else {}),
}
for item in latest.values()
diff --git a/overbae/services/experiments/failures.py b/overbae/services/experiments/failures.py
new file mode 100644
index 00000000..2bc31ea3
--- /dev/null
+++ b/overbae/services/experiments/failures.py
@@ -0,0 +1,72 @@
+"""What a finished stage records beside its state: the tool it called, the platform record it
+ended on, how long it ran and, when it did not complete, the class of its failure. The
+message stays in the step's ``error``."""
+
+# Whether running the stage again unchanged can succeed. A class that is absent is unknown.
+RETRYABLE = {
+ "stopped": True,
+ "code_error": False,
+ "check_failed": False,
+ "output_contract": False,
+ "invalid_configuration": False,
+ "admission_denied": False,
+ # An uncertain provider outcome is reconciled from its saved identity, never resubmitted.
+ "outcome_unknown": False,
+}
+DENIED = frozenset(
+ {
+ "authentication_failed",
+ "authentication_required",
+ "holdout_sealed",
+ "insufficient_credits",
+ "permission_denied",
+ "protected_setting",
+ }
+)
+TRACEBACK = "Traceback (most recent call last):"
+
+
+def tool_error(code) -> str:
+ """The class of a catalog tool's refusal, from its error code."""
+ if code == "request_in_progress":
+ return "outcome_unknown"
+ if code == "internal_error":
+ return "operation_failed"
+ return "admission_denied" if code in DENIED else "invalid_configuration"
+
+
+def last_exception(text) -> str | None:
+ """The exception line that ends the last Python traceback in a program's output."""
+ lines = str(text or "").splitlines()
+ starts = [index for index, line in enumerate(lines) if line.startswith(TRACEBACK)]
+ if not starts:
+ return None
+ return next(
+ (line.strip()[:500] for line in lines[starts[-1] + 1 :] if line and not line[0].isspace()),
+ None,
+ )
+
+
+def failed_job(job: dict) -> dict:
+ """The failure of a stage whose platform record ended without success, as get_job reads it."""
+ status = job.get("status")
+ if status == "submission_unknown":
+ return {"code": "outcome_unknown"}
+ if status != "failed":
+ return {"code": "stopped"}
+ exception = last_exception(job.get("job_error"))
+ if exception:
+ return {"code": "code_error", "exception": exception}
+ return {"code": "operation_failed"}
+
+
+def report(step, failure: dict | None, action: dict | None) -> dict:
+ receipt = action or (step.receipts[0] if step.receipts else None)
+ out = {
+ "tool": next((call["tool"] for call in step.calls if call.get("tool")), None),
+ "action": {"kind": receipt["kind"], "id": receipt["id"]} if receipt else None,
+ "duration_seconds": round((step.ended_at - step.started_at).total_seconds(), 3),
+ }
+ if failure is not None:
+ out["failure"] = {**failure, "retryable": RETRYABLE.get(failure["code"])}
+ return out
diff --git a/overbae/services/experiments/operator.py b/overbae/services/experiments/operator.py
index 93aa5210..148429d1 100644
--- a/overbae/services/experiments/operator.py
+++ b/overbae/services/experiments/operator.py
@@ -11,6 +11,7 @@ ENDED = {
ExperimentRun.State.UNMET: "ended incomplete",
ExperimentRun.State.STOPPED: "stopped",
}
+RETRY = {True: ", retryable", False: ", not retryable"}
def notify(experiment, user, *, origin: str, text: str, request_key: str):
@@ -36,7 +37,12 @@ def run_ended(run: ExperimentRun):
# A retried stage's earlier attempts stay in the history, not in the notice.
for step in run.steps.order_by("node", "-attempt").distinct("node"):
if step.state in (ExperimentStep.State.FAILED, ExperimentStep.State.CANCELLED):
- lines.append(f"- {step.node}: {step.error or step.state}")
+ failure = step.report.get("failure") or {}
+ retry = RETRY.get(failure.get("retryable"), "")
+ kind = f" ({failure['code']}{retry})" if failure else ""
+ lines.append(f"- {step.node}{kind}: {step.error or step.state}")
+ if failure.get("exception") and failure["exception"] not in step.error:
+ lines.append(f" Last exception: {failure['exception']}")
return notify(
run.experiment,
run.created_by,
diff --git a/overbae/services/experiments/runs.py b/overbae/services/experiments/runs.py
index 54a5a562..f769c4cd 100644
--- a/overbae/services/experiments/runs.py
+++ b/overbae/services/experiments/runs.py
@@ -28,7 +28,7 @@ from overbae.models import (
ExperimentStep,
)
from overbae.services import activity
-from overbae.services.experiments import describe, records, stages
+from overbae.services.experiments import describe, failures, records, stages
from overbae.services.experiments import document as flow
from overbae.services.experiments.catalog import FLOWS, KINDS
@@ -418,7 +418,9 @@ def _invoker(context, step: ExperimentStep, calls: list):
}
)
if result.isError:
- raise stages.StageFailedError(_error(content))
+ error = content.get("error")
+ code = error.get("code") if isinstance(error, dict) else None
+ raise stages.StageFailedError(_error(content), failures.tool_error(code))
return content
return invoke
@@ -441,14 +443,14 @@ def _advance(run_id) -> None:
return
if run.state == State.RUNNING and timezone.now() > run.deadline:
hours = round((run.deadline - run.created_at).total_seconds() / 3600)
- _halt(run, f"Reached its time limit of {hours} hours.")
+ _halt(run, f"Reached its time limit of {hours} hours.", "timeout")
return
if run.state == State.STOPPING:
- _halt(run, "Stopped.")
+ _halt(run, "Stopped.", "stopped")
return
context = _context(run)
if context is None:
- _halt(run, "The person who started it left the project.")
+ _halt(run, "The person who started it left the project.", "admission_denied")
return
document = run.revision.document
nodes = flow.order(document["nodes"])
@@ -525,7 +527,9 @@ def _gather(node, latest, status):
return inputs
-def _save(step: ExperimentStep, **values) -> None:
+def _save(step: ExperimentStep, *, failure=None, action=None, **values) -> None:
+ """``failure`` is the class of a stage that did not complete; ``action`` the receipt
+ it ended on, when that is not its first."""
now = timezone.now()
for key, value in values.items():
setattr(step, key, value)
@@ -533,6 +537,9 @@ def _save(step: ExperimentStep, **values) -> None:
step.started_at = now
if step.state in ENDED:
step.ended_at = now
+ step.report = failures.report(
+ step, {"code": failure} if isinstance(failure, str) else failure, action
+ )
step.save()
records.changed(step.run.experiment_id, "experiment")
@@ -584,19 +591,32 @@ def _dispatch(run, step, node, settings, context) -> None:
try:
outcome = stages.START[node["kind"]](stage)
except stages.StageFailedError as exc:
- _save(step, state=Step.FAILED, error=exc.message, calls=calls)
+ failure = exc.failure or "invalid_configuration"
+ _save(step, state=Step.FAILED, error=exc.message, calls=calls, failure=failure)
_logged(run, step, node)
return
except Exception:
logger.exception("experiment stage %s of run %s failed to start", node["id"], run.pk)
telemetry.report_failure("Experiment stage failed to start", run_id=run.pk)
- _save(step, state=Step.FAILED, error="The stage failed to start.", calls=calls)
+ _save(
+ step,
+ state=Step.FAILED,
+ error="The stage failed to start.",
+ calls=calls,
+ failure="operation_failed",
+ )
_logged(run, step, node)
return
if isinstance(outcome, stages.Done):
_save(step, state=Step.COMPLETED, outputs=outcome.outputs, calls=calls)
elif not outcome.receipts:
- _save(step, state=Step.FAILED, error="The stage started no platform work.", calls=calls)
+ _save(
+ step,
+ state=Step.FAILED,
+ error="The stage started no platform work.",
+ calls=calls,
+ failure="output_contract",
+ )
else:
_save(step, receipts=outcome.receipts, calls=calls)
_logged(run, step, node)
@@ -622,7 +642,8 @@ def _observe(run, step, node, settings, context) -> bool:
return _observe_flow(run, step, node, settings)
except (stages.StageFailedError, InputValidationError) as exc:
message = getattr(exc, "message", None) or getattr(exc, "detail", str(exc))
- _save(step, state=Step.FAILED, error=message)
+ failure = getattr(exc, "failure", None) or "invalid_configuration"
+ _save(step, state=Step.FAILED, error=message, failure=failure)
_logged(run, step, node)
return True
if not step.receipts:
@@ -639,19 +660,32 @@ def _observe(run, step, node, settings, context) -> bool:
job = invoke("get_job", {"kind": receipt["kind"], "id": receipt["id"], "view": "full"})
jobs.append(job)
except stages.StageFailedError as exc:
- _save(step, state=Step.FAILED, error=exc.message)
+ # The record it waits on could not be read, so its outcome is not known.
+ _save(step, state=Step.FAILED, error=exc.message, failure="outcome_unknown")
_logged(run, step, node)
return True
receipts = [
{**r, "status": job.get("status")} for r, job in zip(step.receipts, jobs, strict=True)
]
- failed = next((job for job in jobs if job.get("status") in FAILED_JOBS), None)
+ failed = next(
+ (
+ (receipt, job)
+ for receipt, job in zip(receipts, jobs, strict=True)
+ if job.get("status") in FAILED_JOBS
+ ),
+ None,
+ )
if failed is not None:
- reason = (
- failed.get("job_error")
- or f"{failed.get('label') or failed['kind']} {failed['status']}."
+ receipt, job = failed
+ reason = job.get("job_error") or f"{job.get('label') or job['kind']} {job['status']}."
+ _save(
+ step,
+ state=Step.FAILED,
+ error=str(reason)[:1000],
+ receipts=receipts,
+ failure=failures.failed_job(job),
+ action=receipt,
)
- _save(step, state=Step.FAILED, error=str(reason)[:1000], receipts=receipts)
_logged(run, step, node)
return True
if not all(job.get("status") in stages.SUCCEEDED for job in jobs):
@@ -671,7 +705,14 @@ def _observe(run, step, node, settings, context) -> bool:
outcome = stages.FINISH[node["kind"]](stage, jobs)
_save(step, state=Step.COMPLETED, outputs=outcome.outputs, receipts=receipts, calls=calls)
except stages.StageFailedError as exc:
- _save(step, state=Step.FAILED, error=exc.message, receipts=receipts, calls=calls)
+ _save(
+ step,
+ state=Step.FAILED,
+ error=exc.message,
+ receipts=receipts,
+ calls=calls,
+ failure=exc.failure or "output_contract",
+ )
_logged(run, step, node)
return True
@@ -743,7 +784,8 @@ def _start_flow(run, step, node, settings) -> None:
_child(run, step, target, revision, parameters, node["title"])
except (stages.StageFailedError, InputValidationError) as exc:
message = getattr(exc, "message", None) or getattr(exc, "detail", str(exc))
- _save(step, state=Step.FAILED, error=message)
+ failure = getattr(exc, "failure", None) or "invalid_configuration"
+ _save(step, state=Step.FAILED, error=message, failure=failure)
_logged(run, step, node)
@@ -796,7 +838,12 @@ def _observe_flow(run, step, node, settings) -> bool:
return True
last = children[-1]
if last.state != State.COMPLETED:
- _save(step, state=Step.FAILED, error=f"Its run ended {last.get_state_display().lower()}.")
+ _save(
+ step,
+ state=Step.FAILED,
+ error=f"Its run ended {last.get_state_display().lower()}.",
+ failure="stopped" if last.state == State.STOPPED else "child_run_failed",
+ )
_logged(run, step, node)
return True
outputs = _child_outputs(last)
@@ -840,7 +887,7 @@ def _settle(run, nodes) -> None:
_end(run, State.UNMET, reason, (State.RUNNING,))
-def _halt(run, reason: str) -> None:
+def _halt(run, reason: str, failure: str) -> None:
"""Stop the work each running stage started, then end the run."""
context = _context(run)
for step in _latest(run).values():
@@ -862,7 +909,7 @@ def _halt(run, reason: str) -> None:
_invoker(context, step, list(step.calls))(tool, {argument: receipt["id"]})
except stages.StageFailedError as exc:
notes.append(f"Stopping {receipt['kind']} {receipt['id']} failed: {exc.message}")
- _save(step, state=Step.CANCELLED, error=" ".join([reason, *notes]))
+ _save(step, state=Step.CANCELLED, error=" ".join([reason, *notes]), failure=failure)
_end(run, State.STOPPED, reason, ACTIVE)
diff --git a/overbae/services/experiments/stages.py b/overbae/services/experiments/stages.py
index dcf0683c..ebb7b7d4 100644
--- a/overbae/services/experiments/stages.py
+++ b/overbae/services/experiments/stages.py
@@ -60,9 +60,13 @@ SYSTEM_OUTPUTS = "system_outputs"
class StageFailedError(Exception):
- def __init__(self, message: str):
+ """``failure`` classes the refusal (services/experiments/failures.py); None leaves it to
+ the caller."""
+
+ def __init__(self, message: str, failure: str | None = None):
super().__init__(message)
self.message = message
+ self.failure = failure
@dataclass
@@ -232,7 +236,9 @@ def _check_data(stage: Stage):
report = {"rows": cell.rows, "invalid_rows": invalid, "errors": errors}
allowed = stage.settings.get("max_invalid") or 0
if invalid > allowed:
- raise StageFailedError(f"{invalid:,} of {cell.rows:,} rows break the schema.")
+ raise StageFailedError(
+ f"{invalid:,} of {cell.rows:,} rows break the schema.", failure="check_failed"
+ )
return Done({"data": data_value(cell), "report": report})
diff --git a/overbae/services/mcp/__init__.py b/overbae/services/mcp/__init__.py
index e43e725c..65264aaa 100644
--- a/overbae/services/mcp/__init__.py
+++ b/overbae/services/mcp/__init__.py
@@ -1,3 +1,3 @@
"""MCP protocol and catalog services."""
-CONTRACT_VERSION = "13.0.0"
+CONTRACT_VERSION = "13.1.0"
diff --git a/overbae/services/mcp/resources.py b/overbae/services/mcp/resources.py
index f5048603..c9778ba4 100644
--- a/overbae/services/mcp/resources.py
+++ b/overbae/services/mcp/resources.py
@@ -1220,12 +1220,8 @@ def _job_resource(project, kind: str, value: str, uri: str) -> dict:
"kind": kind,
"id": str(prep.id),
"status": prep.state,
- "training_job": str(job_id)
- if (
- job_id := prep.training_jobs.order_by("created_at")
- .values_list("id", flat=True)
- .first()
- )
+ "training_job": str(training_job.pk)
+ if (training_job := prep.current_training_job())
else None,
"report": prep.report,
"config": prep.config,
diff --git a/overbae/services/mcp/tools_finetuning.py b/overbae/services/mcp/tools_finetuning.py
index 0f77533c..569c9df6 100644
--- a/overbae/services/mcp/tools_finetuning.py
+++ b/overbae/services/mcp/tools_finetuning.py
@@ -1033,7 +1033,7 @@ def _prepare_training_sync(payload, context):
raise MCPError("preparation_invalid", exc.detail) from exc
if prep.state == "queued":
inspect_preparation.delay(str(prep.id))
- training_job = prep.training_jobs.earliest("created_at")
+ training_job = prep.current_training_job()
identity = getattr(training_job, "decision_job", None)
return PrepareTrainingOutput(
training_job=FineTuneJobReference(
diff --git a/overbae/services/mcp/tools_observability.py b/overbae/services/mcp/tools_observability.py
index cb295fbd..6270ce7b 100644
--- a/overbae/services/mcp/tools_observability.py
+++ b/overbae/services/mcp/tools_observability.py
@@ -399,10 +399,8 @@ def get_job_sync(payload: GetJobInput, context: MCPContext) -> GetJobOutput:
label, status, job_error = "Training preparation", job.state, job.error or None
progress = safe_json(job.report)
details = safe_json(job.config)
- training_job_id = (
- job.training_jobs.order_by("created_at").values_list("id", flat=True).first()
- )
- details["training_job"] = str(training_job_id) if training_job_id else None
+ training_job = job.current_training_job()
+ details["training_job"] = str(training_job.pk) if training_job else None
primary = _link("jobs", f"training_preparation/{job.id}", label)
elif kind == "eval_run":
job, error = resolve_eval_run(context.project, ref)
diff --git a/overbae/tasks/finetuning.py b/overbae/tasks/finetuning.py
index ca31c216..d50db4d8 100644
--- a/overbae/tasks/finetuning.py
+++ b/overbae/tasks/finetuning.py
@@ -436,6 +436,14 @@ def _finalize_success(job, runner, snap, remote: str) -> dict[str, Any]:
max_retries=0,
)
def run_finetuning(*, job_id: str) -> dict[str, Any]:
+ # The reconciler re-drives a submission only while nobody holds this lock.
+ with acquire_task_lock(f"training_submission:{job_id}", timeout=30, renew=True) as acquired:
+ if not acquired:
+ return {"status": "skipped", "reason": "submission_driver_active"}
+ return _drive_submission(job_id)
+
+
+def _drive_submission(job_id: str) -> dict[str, Any]:
from django.conf import settings
from overbae.models import FinetuningJob
diff --git a/overbae/tasks/finetuning_reconciler.py b/overbae/tasks/finetuning_reconciler.py
index 60c2e58f..be72cb1f 100644
--- a/overbae/tasks/finetuning_reconciler.py
+++ b/overbae/tasks/finetuning_reconciler.py
@@ -7,7 +7,7 @@ from celery import shared_task
from django.utils import timezone
from overbae.services import operational_progress, training_submission, training_transfer
-from overbae.tasks.utils.task_lock import with_task_lock
+from overbae.tasks.utils.task_lock import acquire_task_lock, with_task_lock
logger = logging.getLogger(__name__)
@@ -17,6 +17,30 @@ _ACTIVE_STATUSES = {"queued", "preparing", "running", "submission_unknown"}
_RUN_TASK = "overbae.tasks.finetuning.run_finetuning"
+def _resolve_lost_submission(job, inventory_known) -> bool:
+ stale = (timezone.now() - job.updated_at).total_seconds() >= 120
+ if job.status in {"preparing", "submission_unknown"} and inventory_known and stale:
+ training_submission.restage(job)
+ if job.status == "submission_unknown":
+ try:
+ training_submission.recover(job)
+ except Exception:
+ logger.exception("Provider submission reconciliation unavailable for %s", job.id)
+ return False
+ if job.status == "preparing" and not job.remote_job_id:
+ if not inventory_known or not stale:
+ return False
+ if job.provider_submission:
+ training_submission.unknown(job, RuntimeError("Submission task disappeared"))
+ job.refresh_from_db()
+ try:
+ training_submission.recover(job)
+ except Exception:
+ logger.exception("Lost submission could not yet be reconciled for %s", job.id)
+ return False
+ return True
+
+
def _reconcile() -> dict:
from overbae.celery import get_celery_app
from overbae.models.finetuning import FinetuningJob
@@ -54,20 +78,6 @@ def _reconcile() -> dict:
training_transfer.observe(job)
if job.celery_task_id and job.celery_task_id in running_task_ids:
continue
- if (
- job.status in {"preparing", "submission_unknown"}
- and inventory_known
- and (timezone.now() - job.updated_at).total_seconds() >= 120
- ):
- training_submission.restage(job)
- if job.status == "submission_unknown":
- from overbae.services.training_submission import recover
-
- try:
- recover(job)
- except Exception:
- logger.exception("Provider submission reconciliation unavailable for %s", job.id)
- continue
if job.remote_job_id and job.status in {"running", "preparing", "queued"}:
try:
observe_finetuning_job(job)
@@ -76,25 +86,19 @@ def _reconcile() -> dict:
else:
observed += 1
continue
- if job.status == "preparing" and not job.remote_job_id:
- if not inventory_known or (timezone.now() - job.updated_at).total_seconds() < 120:
- continue
- if job.provider_submission:
- training_submission.unknown(job, RuntimeError("Submission task disappeared"))
- job.refresh_from_db()
- try:
- training_submission.recover(job)
- except Exception:
- logger.exception("Lost submission could not yet be reconciled for %s", job.id)
- continue
- task_name = _RUN_TASK
+ # Inventory can miss a task it just dispatched; run_finetuning holds this lock while it
+ # stages. Release it before enqueueing, or the new task finds it taken and exits.
+ with acquire_task_lock(f"training_submission:{job.pk}", timeout=30) as idle:
+ enqueue = idle and _resolve_lost_submission(job, inventory_known)
+ if not enqueue:
+ continue
logger.info(
"Reconciler: re-enqueuing %s for orphaned job %s (status=%s)",
- task_name,
+ _RUN_TASK,
job.id,
job.status,
)
- result = celery_app.send_task(task_name, kwargs={"job_id": str(job.id)})
+ result = celery_app.send_task(_RUN_TASK, kwargs={"job_id": str(job.id)})
job.celery_task_id = result.id
job.save(update_fields=["celery_task_id"])
kicked += 1
diff --git a/tests/journeys/test_data.py b/tests/journeys/test_data.py
index 0a67348b..9c2265ba 100644
--- a/tests/journeys/test_data.py
+++ b/tests/journeys/test_data.py
@@ -67,6 +67,7 @@ def hand_uploaded_data_to_the_coding_agent(console, tmp_path):
)
console.upload('input[type="file"]', tickets(tmp_path))
console.sees("3 rows")
+ console.press("Continue")
console._browser.call(lambda: console._page.get_by_role("tab", name="From repository").click())
console.sees("Copy prompt")
console.press("Choose coding agent")
@@ -125,6 +126,9 @@ def use_freezes_an_uploaded_eval_source(console, workshop, project, worker, tmp_
labels.write_text("text,label\nhello,greeting\n")
console.goto(f"/?projectId={project}")
console.upload('input[aria-label="Attach dataset files"]', tickets(tmp_path), labels)
+ console.press("Continue")
+ console.sees("labels.csv")
+ console.press("Continue")
console.press("Send")
def landed():
diff --git a/tests/journeys/test_evaluate.py b/tests/journeys/test_evaluate.py
index 0c7d0883..48ee00cc 100644
--- a/tests/journeys/test_evaluate.py
+++ b/tests/journeys/test_evaluate.py
@@ -2,8 +2,10 @@ import json
import pytest
+from overbae.models import EvalRun
+
from .datasets import JUDGE, tickets, upload
-from .stack import drain, drain_run
+from .stack import drain, drain_run, settle
pytestmark = pytest.mark.covers("evaluate")
@@ -32,9 +34,14 @@ def test_evaluate(workshop, cli, sample_agent, worker, tmp_path, fake_llm, conso
],
},
)
- drain(worker)
- runs = {run["label"]: workshop.read(run["resource"]["uri"]) for run in group["runs"]}
+ # A target's judging is queued once its generation commits, after the drain
+ # may already have found the queue empty.
+ def ended():
+ read = {run["label"]: workshop.read(run["resource"]["uri"]) for run in group["runs"]}
+ return read if all(run["status"] in EvalRun.TERMINAL for run in read.values()) else None
+
+ runs = settle(worker, ended)
assert {label: run["status"] for label, run in runs.items()} == dict.fromkeys(
("recorded", "candidate", "weak"), "completed"
)
diff --git a/tests/test_dataset_import_receipts.py b/tests/test_dataset_import_receipts.py
index 9b297d96..f9c581ca 100644
--- a/tests/test_dataset_import_receipts.py
+++ b/tests/test_dataset_import_receipts.py
@@ -14,11 +14,19 @@ import uuid
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta
+import pandas as pd
import pytest
from django.db import close_old_connections, connection
from django.utils import timezone
-from overbae.models import Cell, Dataset, DatasetImport, DatasetPipelineRun, Project
+from overbae.models import (
+ Cell,
+ Dataset,
+ DatasetImport,
+ DatasetLandingWork,
+ DatasetPipelineRun,
+ Project,
+)
from overbae.services.datasets import dispatch, files, imports, workbench
from overbae.services.datasets.lifecycle import DatasetError
from overbae.tasks import datasets as dataset_tasks
@@ -352,6 +360,47 @@ def test_existing_run_action_resumes_blocked_source_import(imported_source, monk
assert imports.execute(str(run.pk), run.inputs) == {"status": "ok", "rows": 2}
[email protected]("expired", [False, True])
+def test_resume_recovers_a_dead_worker_only_after_its_lease_lapses(imported_source, expired):
+ dataset, run = create_import(imported_source)
+ old_claim = imports.claim(run.pk)
+ DatasetLandingWork.objects.create(
+ id=run.pk, project=dataset.project, dataset=dataset, inputs=run.inputs, state="failed"
+ )
+ if not expired:
+ assert imports.status(dataset)["can_resume"] is False
+ with pytest.raises(DatasetError, match="No stopped source import"):
+ imports.resume_dataset(dataset)
+ run.refresh_from_db()
+ assert run.state == "running" and run.owner == old_claim.owner
+ return
+ DatasetImport.objects.filter(pk=run.pk).update(
+ lease_until=timezone.now() - timedelta(seconds=1)
+ )
+ assert imports.status(dataset)["can_resume"] is True
+ imports.resume_dataset(dataset)
+ new_claim = imports.claim(run.pk)
+ imports.fail(old_claim, "Late interruption", code="worker_timeout")
+ run.refresh_from_db()
+ assert run.state == "running" and run.owner == new_claim.owner
+ assert files.upload_data_path(imported_source[1]).exists()
+ assert not dataset.cells.exists()
+
+
+def test_a_worker_stopped_mid_import_records_worker_timeout(imported_source, monkeypatch):
+ dataset, run = create_import(imported_source)
+
+ def stop(*args, **kwargs):
+ raise SystemExit
+
+ monkeypatch.setattr(pd.DataFrame, "from_records", stop)
+ with pytest.raises(SystemExit):
+ imports.execute(str(run.pk), run.inputs)
+ run.refresh_from_db()
+ assert (run.state, run.failure_code) == ("blocked", "worker_timeout")
+ assert imports.status(dataset)["can_resume"] is True
+
+
def test_adopting_an_existing_message_does_not_publish_again(imported_source):
from overbae.services.datasets import imports
diff --git a/tests/test_dataset_uploads.py b/tests/test_dataset_uploads.py
index 92b1899e..ff3a4dbd 100644
--- a/tests/test_dataset_uploads.py
+++ b/tests/test_dataset_uploads.py
@@ -7,6 +7,7 @@ import pyarrow as pa
import pyarrow.parquet as pq
import pytest
from conftest import read_table
+from openpyxl import Workbook
from rest_framework.test import APIClient
from overbae.models import Dataset, Project, ProjectMembership, User
@@ -208,3 +209,62 @@ def test_invalid_multi_file_sources_are_rejected_before_creation(client_project)
)
assert response.status_code == 400, response.data
assert not Dataset.objects.filter(project=project).exists()
+
+
[email protected]_db(transaction=True)
+def test_reading_options_set_how_a_delimited_file_previews_and_lands(client_project):
+ client, project = client_project
+ content = "Café;3\nThé;4\n".encode("windows-1252")
+ upload_id = _upload("menu.csv", content)
+ url = f"/api/uploads/{upload_id}/inspect/"
+ plain = client.post(url, {"size": len(content), "preview": True}, format="json")
+ assert plain.status_code == 400
+ options = {"delimiter": "semicolon", "encoding": "windows-1252", "header": False}
+ read = client.post(
+ url, {"size": len(content), "preview": True, "options": options}, format="json"
+ )
+ assert read.status_code == 200, read.data
+ assert read.data["rows"] == 2
+ assert read.data["columns"] == ["column_1", "column_2"]
+ assert read.data["preview"] == [
+ {"column_1": "Café", "column_2": "3"},
+ {"column_1": "Thé", "column_2": "4"},
+ ]
+ refused = client.post(url, {"size": len(content), "options": {"delimiter": "x"}}, format="json")
+ assert refused.status_code == 400
+ body = {"project": str(project.id), "name": "Menu", "source": {"uploads": [upload_id]}}
+ created = client.post("/api/datasets/", body, format="json")
+ assert created.status_code == 201, created.data
+ dataset = Dataset.objects.get(pk=created.data["id"])
+ assert dataset.state == Dataset.State.IDLE, dataset.error
+ landed = read_table(paths.cell_path(dataset.id, dataset.source.id))
+ assert landed["column_1"].tolist() == ["Café", "Thé"]
+ assert landed["column_2"].tolist() == [3, 4]
+
+
[email protected]_db(transaction=True)
+def test_a_chosen_sheet_is_the_only_one_that_lands(client_project, tmp_path):
+ client, project = client_project
+ workbook = Workbook()
+ workbook.active.title = "orders"
+ for row in (["id"], ["a"], ["b"]):
+ workbook.active.append(row)
+ notes = workbook.create_sheet("notes")
+ for row in (["note"], ["first"]):
+ notes.append(row)
+ path = tmp_path / "book.xlsx"
+ workbook.save(path)
+ content = path.read_bytes()
+ upload_id = _upload("book.xlsx", content)
+ every = files.inspect_upload(upload_id, size=len(content), preview=True)
+ assert (every["rows"], every["sheets"], every["columns"]) == (3, ["orders", "notes"], ["id"])
+ chosen = files.inspect_upload(
+ upload_id, size=len(content), preview=True, options={"sheet": "notes"}
+ )
+ assert (chosen["rows"], chosen["preview"]) == (1, [{"note": "first"}])
+ body = {"project": str(project.id), "name": "Notes", "source": {"uploads": [upload_id]}}
+ created = client.post("/api/datasets/", body, format="json")
+ assert created.status_code == 201, created.data
+ dataset = Dataset.objects.get(pk=created.data["id"])
+ assert dataset.state == Dataset.State.IDLE, dataset.error
+ assert read_table(paths.cell_path(dataset.id, dataset.source.id))["note"].tolist() == ["first"]
diff --git a/tests/test_decision_benchmark_scoring.py b/tests/test_decision_benchmark_scoring.py
index ce67f08f..757f4e96 100644
--- a/tests/test_decision_benchmark_scoring.py
+++ b/tests/test_decision_benchmark_scoring.py
@@ -74,6 +74,26 @@ def test_scoring_preserves_soft_labels_and_reports_hard_label_denominator(tmp_pa
(-math.log(0.8) - math.log(0.3) - 0.2 * math.log(0.4) - 0.8 * math.log(0.6)) / 3
)
assert card["macro_f1"] == pytest.approx(1 / 3)
+ assert card["labels"] == [
+ {
+ "label": "a",
+ "support": 1,
+ "predicted": 2,
+ "correct": 1,
+ "precision": 0.5,
+ "recall": 1.0,
+ "f1": pytest.approx(2 / 3),
+ },
+ {
+ "label": "b",
+ "support": 1,
+ "predicted": 0,
+ "correct": 0,
+ "precision": None,
+ "recall": 0.0,
+ "f1": 0.0,
+ },
+ ]
assert card["metrics"]["cross_entropy"]["groups"] == 3
diff --git a/tests/test_experiments.py b/tests/test_experiments.py
index 168dc8ae..e8f0c0b7 100644
--- a/tests/test_experiments.py
+++ b/tests/test_experiments.py
@@ -22,7 +22,16 @@ from overbae.models import (
ExperimentStep,
ExperimentTrigger,
)
-from overbae.services.experiments import document, operator, records, runs, stages, triggers
+from overbae.services.experiments import (
+ describe,
+ document,
+ failures,
+ operator,
+ records,
+ runs,
+ stages,
+ triggers,
+)
pytestmark = [pytest.mark.django_db, pytest.mark.covers("experiments")]
@@ -157,13 +166,47 @@ def test_a_failed_stage_ends_the_run_incomplete_and_a_retry_runs_it_again(setup)
run = runs.start(experiment, context.user, origin="mcp")
run.refresh_from_db()
assert run.state == ExperimentRun.State.UNMET
- assert run.steps.get(node="check").error == "2 of 2 rows break the schema."
+ step = run.steps.get(node="check")
+ assert step.error == "2 of 2 rows break the schema."
+ assert step.report["failure"] == {"code": "check_failed", "retryable": False}
+ assert step.report["tool"] is None and step.report["duration_seconds"] >= 0
+ described = {item["node"]: item for item in describe.run(run)["steps"]}
+ assert described["check"]["report"] == step.report
+ notice = AssistantInput.objects.get(thread=experiment.assistant_thread, origin="run")
+ assert "- check (check_failed, not retryable): 2 of 2 rows" in notice.text
retried = runs.retry(run, context.user)
assert retried.state == ExperimentRun.State.UNMET
assert sorted(run.steps.filter(node="check").values_list("attempt", flat=True)) == [1, 2]
+def test_a_failed_job_is_classed_by_the_exception_its_program_raised_last():
+ output = "\n".join(
+ [
+ "Traceback (most recent call last):",
+ ' File "step.py", line 3, in <module>',
+ "KeyError: 'label'",
+ "",
+ "During handling of the above exception, another exception occurred:",
+ "",
+ "Traceback (most recent call last):",
+ ' File "step.py", line 5, in <module>',
+ " raise ValueError(f'no label in {row}')",
+ "ValueError: no label in {'id': 1}",
+ ]
+ )
+ failed = {"status": "failed", "job_error": output}
+ assert failures.failed_job(failed) == {
+ "code": "code_error",
+ "exception": "ValueError: no label in {'id': 1}",
+ }
+ assert failures.failed_job({"status": "failed", "job_error": "Quota."}) == {
+ "code": "operation_failed"
+ }
+ assert failures.failed_job({"status": "cancelled"}) == {"code": "stopped"}
+ assert failures.failed_job({"status": "submission_unknown"}) == {"code": "outcome_unknown"}
+
+
def test_a_stop_ends_the_run_and_names_work_it_could_not_stop(setup):
context, _ = setup
connector = ConnectorCredential.objects.create(
diff --git a/tests/test_finetuning_reconciler.py b/tests/test_finetuning_reconciler.py
index c1f058b1..6c018b0d 100644
--- a/tests/test_finetuning_reconciler.py
+++ b/tests/test_finetuning_reconciler.py
@@ -3,16 +3,20 @@ would queue a duplicate register_finetuned_model on every beat."""
from __future__ import annotations
+import os
import uuid
from datetime import timedelta
from unittest.mock import MagicMock, patch
import pytest
+import redis
from conftest import TRAIN_ROWS, frozen_dataset
from django.utils import timezone
from overbae.models.finetuning import FinetuningJob
+from overbae.tasks.finetuning import run_finetuning
from overbae.tasks.finetuning_reconciler import _reconcile
+from overbae.tasks.utils.task_lock import acquire_task_lock
pytestmark = [pytest.mark.django_db, pytest.mark.covers("recovery")]
@@ -122,3 +126,26 @@ def test_active_modal_staging_is_not_requeued():
job.save()
_, sent = _run_reconcile(active_tasks=[{"id": "live-task"}])
assert sent == []
+
+
+def test_submission_still_being_driven_is_not_requeued(settings):
+ settings.CELERY_BROKER_URL = os.environ.get("TEST_REDIS_URL", "redis://127.0.0.1:6379/15")
+ try:
+ redis.from_url(settings.CELERY_BROKER_URL).ping()
+ except redis.ConnectionError:
+ pytest.skip("Requires the test Redis service")
+ job = _job("preparing")
+ job.provider = "modal"
+ job.remote_job_id, job.celery_task_id = "", "unlisted-task"
+ job.provider_submission = {"state": "submitting", "intent_at": timezone.now().isoformat()}
+ job.save()
+ FinetuningJob.objects.filter(pk=job.pk).update(updated_at=timezone.now() - timedelta(hours=1))
+ with acquire_task_lock(f"training_submission:{job.pk}", timeout=30) as driving:
+ assert driving
+ assert run_finetuning(job_id=str(job.pk))["status"] == "skipped"
+ _, sent = _run_reconcile(active_tasks=[])
+ job.refresh_from_db()
+ assert sent == [] and job.status == "preparing"
+ assert job.provider_submission["state"] == "submitting"
+ _, sent = _run_reconcile(active_tasks=[])
+ assert sent == [("overbae.tasks.finetuning.run_finetuning", {"job_id": str(job.id)})]
diff --git a/tests/test_mcp_finetuning.py b/tests/test_mcp_finetuning.py
index 94dea6bd..089f449d 100644
--- a/tests/test_mcp_finetuning.py
+++ b/tests/test_mcp_finetuning.py
@@ -26,6 +26,7 @@ from overbae.services.mcp import tools_finetuning
from overbae.services.mcp.catalog import CATALOG
from overbae.services.mcp.context import MCPContext, bind_context
from overbae.services.mcp.resources import read_resource
+from overbae.services.training_cancellation import cancel as cancel_training
pytestmark = [pytest.mark.django_db, pytest.mark.covers("mcp-surface")]
@@ -155,6 +156,29 @@ def test_exact_preparation_has_pollable_project_scoped_receipt(settings, monkeyp
assert denied.isError
+def test_preparation_after_a_cancel_returns_the_new_training_job(settings, monkeypatch):
+ settings.FINETUNING_BACKEND = "modal"
+ context = _context(permission=["read", "write", "train"])
+ dataset = frozen_dataset(context.project, TRAIN_ROWS, contract="train")
+ monkeypatch.setattr(tools_finetuning.inspect_preparation, "delay", lambda *a: None)
+ arguments = {
+ "dataset": str(dataset.id),
+ "base_model": "Qwen/Qwen3.5-9B",
+ "context_length": 4096,
+ }
+ first = _call("prepare_training_data", arguments, context).structuredContent
+ cancel_training(FinetuningJob.objects.get(pk=first["training_job"]["id"]))
+
+ again = _call("prepare_training_data", arguments, context)
+ assert not again.isError, again.structuredContent
+ training = again.structuredContent["training_job"]
+ assert training["id"] != first["training_job"]["id"]
+ assert training["status"] == "preprocessing"
+ receipt = again.structuredContent["job"]
+ poll = _call("get_job", {"kind": receipt["kind"], "id": receipt["id"]}, context)
+ assert poll.structuredContent["details"]["training_job"] == training["id"]
+
+
def test_readiness_rejects_wrong_intent():
context = _context()
wrong_intent = Dataset.objects.create(
diff --git a/tests/test_trace_usage_aggregation.py b/tests/test_trace_usage_aggregation.py
index b5fe56f1..6d73fe43 100644
--- a/tests/test_trace_usage_aggregation.py
+++ b/tests/test_trace_usage_aggregation.py
@@ -145,16 +145,23 @@ def test_response_ids_decide_twins_when_both_reports_carry_one():
def test_one_response_keeps_every_fact_and_an_id_less_twin_stands_for_one_call():
- """Reports of one response keep its tokens and its cost whichever span carries
- each; an ID-less framework span overlapping two responses absorbs only one."""
- _, project = _client_and_project()
+ """Reports of one response keep its tokens, its token detail and its cost whichever
+ span carries each; an ID-less framework span overlapping two responses absorbs only one."""
+ client, project = _client_and_project()
trace_id = uuid.uuid4().hex[:32]
root = _span(project, trace_id=trace_id)
reports = [
("openinference.langchain", {"gen_ai.response.id": "resp-1", "genai.cost": 0.03}, 0, 5_000),
(
"opentelemetry.instrumentation.openai.v1",
- {"gen_ai.response.id": "resp-1", "gen_ai.usage.total_tokens": 700},
+ {
+ "gen_ai.response.id": "resp-1",
+ "gen_ai.usage.total_tokens": 700,
+ "gen_ai.usage.input_tokens": 500,
+ "gen_ai.usage.output_tokens": 200,
+ "genai.cache_write_tokens": 12,
+ "genai.reasoning_tokens": 8,
+ },
100,
4_900,
),
@@ -186,6 +193,11 @@ def test_one_response_keeps_every_fact_and_an_id_less_twin_stands_for_one_call()
assert totals["total_tokens"] == 700 + 500 + 500
assert totals["total_cost"] == pytest.approx(0.03 + 0.01)
+ detail = client.get(f"{TRACES_URL}{trace_id}/", {"project_id": project.id}).json()
+ call = next(row for row in detail["receipt"] if row["total_cost"] == 0.03)
+ assert (call["total_tokens"], call["input_tokens"], call["output_tokens"]) == (700, 500, 200)
+ assert (call["cache_write_tokens"], call["reasoning_tokens"]) == (12, 8)
+
def test_helper_counts_sequential_identical_calls_separately():
"""Two identical calls that do NOT overlap in time are two real calls."""
diff --git a/tests/test_training_monitoring.py b/tests/test_training_monitoring.py
index c250ceda..4c93b66d 100644
--- a/tests/test_training_monitoring.py
+++ b/tests/test_training_monitoring.py
@@ -106,11 +106,11 @@ def test_adaptive_schedule_records_conflicts_without_changing_the_probe():
schedule.observe_step(30)
decision = schedule.completed(step=14, duration=120)
assert decision["overhead_interval_steps"] == 36
- assert schedule.next_step == 50
+ assert schedule.next_step == 36
assert decision["basis"] == "measured_optimizer_time"
restored = MonitoringSchedule(policy, total_steps=133, state=schedule.state())
assert restored.state() == schedule.state()
- assert not restored.due(49) and restored.due(50)
+ assert not restored.due(35) and restored.due(36)
for bad in (0, -1, math.inf, math.nan):
with pytest.raises(ValueError):
restored.observe_step(bad)
@@ -138,8 +138,10 @@ def test_schedule_finishes_normally_without_a_spurious_budget_conflict(mode):
schedule.observe_step(1)
decision = schedule.completed(step=2, duration=0)
assert decision["conflicts"] == []
- assert decision["next_step"] is None
- assert decision["stop_reason"] == ("epoch_boundary" if mode == "epoch" else "run_boundary")
+ assert decision["next_step"] == (3 if mode == "adaptive" else None)
+ assert decision["stop_reason"] == (
+ None if mode == "adaptive" else "epoch_boundary" if mode == "epoch" else "run_boundary"
+ )
assert schedule.final_required(4)
@@ -174,10 +176,10 @@ def test_adaptive_budget_conflict_distinguishes_overhead_from_normal_end():
schedule = MonitoringSchedule(policy, total_steps=10)
schedule.observe_step(1)
decision = schedule.completed(step=2, duration=2)
- assert decision["next_step"] is None
- assert decision["stop_reason"] == "run_boundary"
+ assert decision["next_step"] == 3
+ assert decision["stop_reason"] is None
assert decision["conflicts"] == [
- "monitoring_budget_conflict: overhead target prevents another periodic check"
+ "monitoring_budget_conflict: bounded cadence cannot yet meet overhead target"
]
explicit = MonitoringSchedule({**policy, "mode": "steps", "interval_steps": 20}, 10)
explicit.observe_step(1)
@@ -413,3 +415,14 @@ def test_generation_selection_probes_every_check_and_keeps_the_best_passing_chec
checks = monitor.summary()["checks"]
assert all(check["metrics"]["generation"]["expected"] == 4 for check in checks)
assert monitor.summary()["selected_checkpoint"] == "1:20"
+
+
+def test_short_adaptive_run_keeps_intermediate_evidence_despite_slow_checks():
+ policy = resolve_policy(None, has_development=True, provider="modal")
+ schedule = MonitoringSchedule(policy, total_steps=60)
+ schedule.observe_step(0.2)
+ decision = schedule.completed(step=0, duration=5)
+ assert decision["next_step"] == 10
+ assert decision["adaptation"] == "run_length_cadence"
+ assert decision["conflicts"]
+ assert schedule.final_required(60)