The platform for continuously improving AI agents.
import { useRef, useState } from "react";
import type { AppendMessage } from "@assistant-ui/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import api from "@/client";
import { IMPORT_ACCEPT } from "@/components/ai-components/file-import";
import { AttachmentsTray } from "@/components/assistant/attachments-tray";
import { ComposerAttachmentsMenu } from "@/components/assistant/composer-attachments-menu";
import { UploadReview } from "@/components/datasets/upload-review";
import {
useWorkshopRuntime,
WorkshopConversation,
} from "@/components/datasets/workshop-conversation";
import { WorkshopQueue } from "@/components/datasets/workshop-queue";
import { WorkspaceChat, type WorkspaceChatHandle } from "@/components/datasets/workspace-chat";
import { Icon, type IconName } from "@/components/ui/icons";
import { activeCellOf, invalidateDataset } from "@/hooks/use-datasets";
import { useDatasetUploads } from "@/hooks/use-uploads";
import type {
Cell,
Dataset,
EvalCriterion,
ExperimentSource,
WorkshopMessage,
WorkshopMessageControlRequest,
} from "@/openapi";
import { experimentCompletions } from "./chat-completions";
import { activeRun, type ExperimentRecord, runLabel } from "./document";
const referenceIcons: Record<string, { icon: IconName; color: string }> = {
compare: { color: "text-cat-6", icon: "diff" },
data: { color: "text-cat-2", icon: "dataset" },
evaluate: { color: "text-cat-3", icon: "eval" },
model: { color: "text-cat-4", icon: "models" },
predict: { color: "text-cat-5", icon: "inference" },
publish: { color: "text-cat-5", icon: "server" },
split: { color: "text-cat-2", icon: "gitBranch" },
train: { color: "text-cat-1", icon: "finetuning" },
transform: { color: "text-cat-2", icon: "workshop" },
};
const emptyCells: Cell[] = [];
const noop = () => {};
const messageText = (message: AppendMessage) =>
message.content
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
export function ExperimentAgent({
record,
fullScreen = false,
messages: transcript,
beforeSend,
readOnly,
onSelect,
connectionError,
projectId,
onAttach,
}: {
fullScreen?: boolean;
record: ExperimentRecord;
messages: WorkshopMessage[];
beforeSend: () => Promise<number>;
readOnly: boolean;
connectionError?: unknown;
onSelect: (id: string) => void;
projectId?: string;
onAttach?: (sources: ExperimentSource[]) => void;
}) {
const client = useQueryClient();
const chat = useRef<WorkspaceChatHandle>(null);
const upload = useDatasetUploads();
const [selected, setSelected] = useState<Dataset[]>([]);
const sources = useQuery({
enabled: !!projectId,
queryFn: () => api.researchExperiments.researchExperimentsSourcesList({ project: projectId! }),
queryKey: ["experiment-sources", projectId],
});
const fileInput = useRef<HTMLInputElement>(null);
const uploadedDatasets = useRef(new Map<string, string>());
const request = useRef({ key: "", text: "" });
const queueRequest = useRef({ identity: "", key: "" });
const run = record.runs.find((item) => !item.controller && item.execution !== "flow");
const messages = transcript.filter(
(message) =>
message.id === `${record.id}:request` || (run && message.id.startsWith(`${run.id}:`))
);
const active = activeRun(run);
const stopping = run?.state === "stopping";
const refresh = (
saved: Awaited<ReturnType<typeof api.researchExperiments.researchExperimentsRetrieve>>
) => {
client.setQueryData(["research-experiment", record.id], saved);
void client.invalidateQueries({ queryKey: ["research-experiments"] });
};
const start = useMutation({
mutationFn: async (text: string) => {
const datasetIds = selected.map((dataset) => dataset.id);
for (const file of upload.files) {
if (
file.status !== "ready" ||
file.reviewed !== true ||
!file.uploadId ||
!projectId ||
!onAttach
)
throw new Error("Wait for the attachments to finish uploading");
let id = uploadedDatasets.current.get(file.id);
if (!id) {
const dataset = await api.datasets.datasetsCreate({
datasetCreateRequest: {
name: file.file.name.replace(/(\.[a-z0-9]+){1,2}$/i, "") || "Untitled dataset",
project: projectId,
source: { uploads: [file.uploadId] },
},
});
id = dataset.id;
uploadedDatasets.current.set(file.id, id);
invalidateDataset(client);
}
datasetIds.push(id);
}
const cells = await Promise.all(
datasetIds.map(async (id) => {
let dataset = await api.datasets.datasetsRetrieve({ id });
while (dataset.state === "landing") {
await new Promise((resolve) => window.setTimeout(resolve, 1000));
dataset = await api.datasets.datasetsRetrieve({ id });
}
const cell = activeCellOf(dataset);
if (dataset.state === "error" || !cell)
throw new Error("An attachment has no ready dataset version");
return cell.id;
})
);
const available =
cells.length > 0 && projectId
? await api.researchExperiments.researchExperimentsSourcesList({ project: projectId })
: [];
const attached = cells.map((id) => {
const source = available.find((item) => item.id === id);
if (!source?.available) throw new Error("An attachment is unavailable for this experiment");
return source;
});
if (attached.length) onAttach?.(attached);
await beforeSend();
if (request.current.text !== text) request.current = { key: crypto.randomUUID(), text };
return api.researchExperiments.researchExperimentsMessagesCreate({
experimentMessageInputRequest: { requestKey: request.current.key, text },
id: record.id,
});
},
onSuccess: (saved) => {
upload.reset();
setSelected([]);
uploadedDatasets.current.clear();
request.current = { key: "", text: "" };
refresh(saved);
},
});
const answerRequest = useRef({ identity: "", key: "" });
const answer = useMutation({
mutationFn: ({
question,
text,
approved,
criteria,
}: {
question: string;
text: string;
approved?: boolean;
criteria?: EvalCriterion[];
}) => {
const identity = JSON.stringify({ approved, criteria, question, text });
if (answerRequest.current.identity !== identity)
answerRequest.current = { identity, key: crypto.randomUUID() };
return api.researchExperiments.researchExperimentsMessagesCreate({
experimentMessageInputRequest: {
approved,
criteria,
question,
requestKey: answerRequest.current.key,
text,
},
id: record.id,
});
},
onSuccess: refresh,
});
const stop = useMutation({
mutationFn: () =>
api.researchExperiments.researchExperimentsStopCreate({
experimentStopInputRequest: { run: run!.id },
id: record.id,
}),
onSuccess: refresh,
});
const change = useMutation({
mutationFn: (input: Omit<WorkshopMessageControlRequest, "requestKey">) => {
const identity = JSON.stringify(input);
if (identity !== queueRequest.current.identity)
queueRequest.current = { identity, key: crypto.randomUUID() };
return api.researchExperiments.researchExperimentsMessagesControlCreate({
id: record.id,
workshopMessageControlRequest: { ...input, requestKey: queueRequest.current.key },
});
},
onSuccess: (saved) => {
queueRequest.current = { identity: "", key: "" };
refresh(saved);
},
});
const queue = messages
.filter((message) => message.id.startsWith(`${run?.id}:`) && message.status === "pending")
.sort((a, b) => (a.queuePosition ?? 0) - (b.queuePosition ?? 0));
const uploading = upload.files.some((file) => file.status !== "ready" || file.reviewed !== true);
const disabled = readOnly || stopping || start.isPending || uploading;
const send = async (text: string) => {
if (disabled) throw new Error("The experiment is not accepting messages.");
chat.current?.open();
await start.mutateAsync(text);
};
const submit = async (message: AppendMessage) => {
const text = messageText(message).trim();
try {
await send(text);
} catch {
if (!runtime.thread.composer.getState().text) runtime.thread.composer.setText(text);
}
};
const control = (
id: string,
command: "edit" | "move" | "remove",
extra: { text?: string; position?: number } = {}
) => {
const message = queue.find((item) => item.id === id);
if (!message || !run || stopping || change.isPending) return;
change.mutate({
command,
message: id.slice(run.id.length + 1),
revision: message.revision ?? 0,
...extra,
});
};
const runtime = useWorkshopRuntime(messages, {
isRunning: active,
isSendDisabled: disabled,
onCancel: async () => {
await stop.mutateAsync();
},
onNew: submit,
queue: {
edit: (id, message) => control(id, "edit", { text: messageText(message) }),
enqueue: submit,
items: queue.map((message) => ({
id: message.id,
parts: [{ text: message.text, type: "text" as const }],
prompt: message.text,
})),
move: (id, placement) => {
const remaining = queue.filter((item) => item.id !== id);
const before = remaining.findIndex((item) => item.id === placement.insertBefore);
const after = remaining.findIndex((item) => item.id === placement.insertAfter);
control(id, "move", { position: before >= 0 ? before : after >= 0 ? after + 1 : 0 });
},
remove: (id) => control(id, "remove"),
steer: submit,
steerItems: [],
},
});
const activity = [...messages]
.reverse()
.find(
(message) =>
message.id.startsWith(`${run?.id}:`) &&
message.role === "activity" &&
["running", "preparing"].includes(message.status)
);
const waiting =
active &&
messages.some(
(message) => message.id.startsWith(`${run?.id}:`) && message.status === "question_pending"
);
const requestState = !run
? undefined
: stopping || stop.isPending
? "working"
: waiting || run.state === "blocked"
? "attention"
: active
? "working"
: run.state === "completed"
? "complete"
: "stopped";
const status =
stopping || stop.isPending
? "Stopping"
: waiting
? "Waiting for your answer"
: run?.state === "completed"
? "Request complete"
: runLabel(run);
return (
<WorkspaceChat
active={active}
activityTool={activity && !stopping && !stop.isPending ? activity.tool : undefined}
attachment={
projectId && onAttach && !readOnly ? (
<>
<input
accept={IMPORT_ACCEPT}
aria-label="Attach files to experiment"
className="hidden"
multiple
onChange={(event) => {
upload.add(Array.from(event.target.files ?? []));
event.target.value = "";
}}
ref={fileInput}
type="file"
/>
<ComposerAttachmentsMenu
disabled={stopping || start.isPending}
isAvailable={(dataset) =>
sources.data?.some((source) => source.dataset === dataset.id && source.available) ??
false
}
onAdd={(dataset) => setSelected((current) => [...current, dataset])}
onFiles={() => fileInput.current?.click()}
onRemove={(id) => setSelected((current) => current.filter((item) => item.id !== id))}
projectId={projectId}
selected={selected}
/>
</>
) : null
}
attachments={
<>
<UploadReview busy={start.isPending} upload={upload} />
<AttachmentsTray
datasets={selected}
files={upload.files}
locked={start.isPending}
onPreviewFile={upload.setPreviewId}
onRemoveDataset={(id) =>
setSelected((current) => current.filter((item) => item.id !== id))
}
onRemoveFile={upload.remove}
onRetryFile={upload.retry}
/>
</>
}
collapsedActivity={
run
? active && !waiting && !stopping && !stop.isPending
? (activity?.text ?? status)
: status
: "Ask about the experiment or describe a change…"
}
completions={experimentCompletions(record, run)}
controlling={stop.isPending}
conversation={
<WorkshopConversation
activeTaskId={active ? run?.id : undefined}
cells={emptyCells}
messages={messages}
nodes={record.document.nodes}
onAnswer={async (question, text, approved, criteria) => {
if (readOnly) return;
await answer.mutateAsync({ approved, criteria, question, text });
}}
onCell={noop}
onNode={onSelect}
onSelect={noop}
onSend={send}
readOnly={readOnly || stopping}
sending={start.isPending}
/>
}
failure={start.error || stop.error || change.error || answer.error || connectionError}
fullScreen={fullScreen}
initiallyOpen={fullScreen}
inputLabel="Research follow-up"
label="Experiment chat"
maxLength={8000}
placeholder="Ask about the experiment or describe a change…"
queue={
run && (
<WorkshopQueue
change={change}
disabled={stopping || !active}
messages={queue}
taskId={run.id}
/>
)
}
queueing={active && !waiting}
ref={chat}
references={record.document.nodes.map((node) => {
const appearance = referenceIcons[node.kind] ?? {
color: "text-muted-foreground",
icon: "gitBranch" as const,
};
const Glyph = Icon[appearance.icon];
return {
icon: <Glyph className={appearance.color} />,
id: node.id,
kind: "node",
title: node.title,
};
})}
requestState={requestState}
runtime={runtime}
sendDisabled={disabled}
sendHint={
readOnly
? "Return to the latest revision to send a message"
: stopping
? "Wait for the run to stop"
: uploading
? "Wait for attachments"
: active
? "Queue a follow-up"
: "Send message"
}
sending={start.isPending}
status={status}
stopping={stopping}
/>
);
}