Skip to content

The platform for continuously improving AI agents.

11.0 KB
Raw Blame
import { useEffect, useRef } from "react";

import type { AppendMessage } from "@assistant-ui/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";

import api from "@/client";
import {
  useWorkshopRuntime,
  WorkshopConversation,
} from "@/components/datasets/workshop-conversation";
import { useWorkshopQueue, WorkshopQueue } from "@/components/datasets/workshop-queue";
import { WorkspaceChat, type WorkspaceChatHandle } from "@/components/datasets/workspace-chat";
import { Button } from "@/components/ui/button";
import { Icon } from "@/components/ui/icons";
import { invalidateDataset } from "@/hooks/use-datasets";
import { useWorkshopConversation } from "@/hooks/use-workshop-conversation";
import type { Cell, WorkshopControlRequest, WorkshopInteraction } from "@/openapi";
import { workshopSuggestion } from "./workshop-suggestion";

const terminal = new Set(["completed", "cancelled", "failed"]);
const emptyCells: Cell[] = [];
const noop = () => {};

export function WorkshopAgent({
  datasetId,
  projectId,
  cells = emptyCells,
  selectedCell,
  onSelectCell = noop,
  fullScreen = false,
}: {
  datasetId: string;
  projectId: string;
  cells?: Cell[];
  selectedCell?: string | null;
  onSelectCell?: (id: string) => void;
  fullScreen?: boolean;
}) {
  const qc = useQueryClient();
  const chat = useRef<WorkspaceChatHandle>(null);
  const conversation = useWorkshopConversation(projectId, datasetId);
  const submission = useRef<{
    text: string;
    cell?: string;
    interaction?: WorkshopInteraction;
    requestKey: string;
  } | null>(null);
  const queryKey = ["workshop-agent", projectId, datasetId];
  const query = useQuery({
    queryFn: () => api.workshopTasks.workshopTasksList({ dataset: datasetId, project: projectId }),
    queryKey,
    refetchInterval: 3000,
  });
  const task = query.data?.tasks[0];
  const active = !!task && !terminal.has(task.state);
  const updated = task?.updatedAt?.getTime();
  useEffect(() => {
    if (updated) invalidateDataset(qc, datasetId);
  }, [qc, datasetId, updated]);

  const start = useMutation({
    mutationFn: ({ text, interaction }: { text: string; interaction?: WorkshopInteraction }) => {
      const cell = selectedCell ?? undefined;
      if (
        submission.current?.text !== text ||
        submission.current?.cell !== cell ||
        JSON.stringify(submission.current?.interaction) !== JSON.stringify(interaction)
      ) {
        submission.current = { cell, interaction, requestKey: crypto.randomUUID(), text };
      }
      return api.workshopTasks.workshopTasksMessagesCreate({
        workshopMessageRequestRequest: {
          dataset: datasetId,
          project: projectId,
          ...submission.current,
        },
      });
    },
    onError: () => chat.current?.open(),
    onSuccess: (created) => {
      submission.current = null;
      qc.setQueryData(queryKey, {
        tasks: [created, ...(query.data?.tasks ?? []).filter((item) => item.id !== created.id)],
      });
      void qc.invalidateQueries({ queryKey });
    },
  });
  const control = useMutation({
    mutationFn: (command: WorkshopControlRequest["command"]) =>
      api.workshopTasks.workshopTasksControlCreate({
        id: task!.id,
        workshopControlRequest: { command },
      }),
    onSuccess: (updatedTask) => {
      qc.setQueryData(queryKey, {
        tasks: (query.data?.tasks ?? []).map((item) =>
          item.id === updatedTask.id ? updatedTask : item
        ),
      });
      void qc.invalidateQueries({ queryKey });
    },
  });
  const stopping =
    active &&
    (task.desiredState === "cancelled" || (control.isPending && control.variables === "cancel"));
  const queueing = active && task.state !== "blocked";
  const queued = conversation.messages.filter(
    (message) =>
      message.id.startsWith(`${task?.id}:`) &&
      message.role === "user" &&
      (message.status === "pending" || message.status === "delivering")
  );
  const send = async (text: string, interaction?: WorkshopInteraction) => {
    if (!query.data || !text || start.isPending || stopping)
      throw new Error("Workshop is not accepting messages.");
    chat.current?.open();
    await start.mutateAsync({ interaction, text });
  };
  const latestActivity = [...conversation.messages]
    .reverse()
    .find(
      (message) =>
        message.id.startsWith(`${task?.id}:`) &&
        message.role === "activity" &&
        (message.status === "running" || message.status === "preparing")
    );
  const current = typeof task?.result?.activity === "string" ? task.result.activity : null;
  const paused = active && task.desiredState === "paused";
  const status = stopping
    ? "Stopping"
    : task?.state === "completed"
      ? "Request complete"
      : task?.state === "blocked"
        ? "Needs your attention"
        : task?.state === "failed"
          ? "Task failed"
          : task?.state === "cancelled"
            ? "Cancelled"
            : paused
              ? "Paused"
              : active
                ? (!latestActivity && current) ||
                  (task.state === "queued"
                    ? "Waiting for the workspace"
                    : "Working on your request")
                : "Ask about this data";
  const failure = query.error || control.error || start.error;
  const requestState = !task
    ? undefined
    : stopping
      ? "working"
      : task.state === "blocked" || task.state === "failed"
        ? "attention"
        : paused || task.state === "cancelled"
          ? "stopped"
          : active
            ? "working"
            : "complete";
  const selected = cells.find((cell) => cell.id === selectedCell);
  const sendHint = !query.data
    ? query.isError
      ? "Could not load this conversation. Retrying…"
      : "Loading this conversation…"
    : stopping
      ? "Wait for the run to stop."
      : queueing
        ? "Queue a follow-up"
        : "Send message";
  const queueChange = useWorkshopQueue(task?.id);
  const orderedQueue = [...queued].sort(
    (a, b) => (a.queuePosition ?? Infinity) - (b.queuePosition ?? Infinity)
  );
  const messageText = (message: AppendMessage) =>
    message.content
      .filter((part) => part.type === "text")
      .map((part) => part.text)
      .join("\n");
  const suggestion = workshopSuggestion(conversation.messages);
  const submit = async (message: AppendMessage) => {
    const text = messageText(message).trim();
    try {
      await send(
        text,
        suggestion
          ? {
              component: suggestion.id,
              message: suggestion.message,
              values: { [suggestion.field.name]: text },
            }
          : undefined
      );
    } catch {
      // Queue callbacks are fire-and-forget; restore only an untouched composer after rejection.
      if (!runtime.thread.composer.getState().text) runtime.thread.composer.setText(text);
    }
  };
  const changeQueued = (
    id: string,
    command: "move" | "edit" | "remove",
    extra: { position?: number; text?: string } = {}
  ) => {
    const message = queued.find((item) => item.id === id);
    if (!task || !message || message.status !== "pending" || stopping || queueChange.isPending)
      return;
    queueChange.mutate({
      command,
      message: id.slice(task.id.length + 1),
      revision: message.revision ?? 0,
      ...extra,
    });
  };
  const runtime = useWorkshopRuntime(conversation.messages, {
    isRunning: active,
    isSendDisabled: !query.data || start.isPending || stopping,
    onCancel: async () => {
      await control.mutateAsync("cancel");
    },
    onNew: submit,
    queue: {
      edit: (id, message) => changeQueued(id, "edit", { text: messageText(message) }),
      enqueue: submit,
      items: orderedQueue.map((message) => ({
        id: message.id,
        parts: [{ text: message.text, type: "text" as const }],
        prompt: message.text,
      })),
      move: (id, placement) => {
        const remaining = orderedQueue.filter(
          (item) => item.id !== id && item.status === "pending"
        );
        const before = remaining.findIndex((item) => item.id === placement.insertBefore);
        const after = remaining.findIndex((item) => item.id === placement.insertAfter);
        const position = before >= 0 ? before : after >= 0 ? after + 1 : 0;
        changeQueued(id, "move", { position });
      },
      remove: (id) => changeQueued(id, "remove"),
      steer: submit,
      steerItems: [],
    },
  });
  const selectCell = (id: string) => {
    if (!fullScreen && window.matchMedia("(max-width: 767px)").matches) chat.current?.close();
    onSelectCell(id);
  };
  return (
    <WorkspaceChat
      active={active}
      activityTool={active && !paused && !stopping ? latestActivity?.tool : undefined}
      collapsedActivity={
        active && !paused && !stopping ? (latestActivity?.text ?? current ?? status) : status
      }
      completions={[
        suggestion?.suggestion ||
          (active
            ? "Summarize progress and flag anything that needs my input."
            : selected
              ? "Check the selected dataset version for missing values and duplicates."
              : "Summarize this dataset and suggest the next preparation step."),
      ]}
      controlling={control.isPending}
      conversation={
        <WorkshopConversation
          activeTaskId={active ? task?.id : undefined}
          cells={cells}
          messages={conversation.messages}
          onCell={(cell) => {
            if (cell.dataset === datasetId || cells.some((item) => item.id === cell.id))
              selectCell(cell.id);
            else
              window.location.assign(
                `/datasets/${encodeURIComponent(cell.dataset)}?projectId=${encodeURIComponent(projectId)}&cell=${encodeURIComponent(cell.id)}`
              );
          }}
          onSelect={selectCell}
          onSend={send}
          sending={start.isPending}
        />
      }
      failure={failure}
      fullScreen={fullScreen}
      initiallyOpen={fullScreen}
      queue={
        task && (
          <WorkshopQueue
            change={queueChange}
            disabled={stopping}
            messages={queued}
            taskId={task.id}
          />
        )
      }
      queueing={queueing}
      ref={chat}
      requestState={requestState}
      runtime={runtime}
      selection={
        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>
        )
      }
      sendDisabled={!query.data || start.isPending || stopping}
      sendHint={sendHint}
      sending={start.isPending}
      showStatus={
        active &&
        !conversation.messages.some(
          (message) => message.id.startsWith(`${task?.id}:`) && message.role !== "user"
        )
      }
      status={status}
      stopping={stopping}
      suggestion={suggestion?.suggestion}
    />
  );
}