Skip to content

The platform for continuously improving AI agents.

26.4 KB
Raw Blame
import { createContext, lazy, Suspense, useContext, useMemo, useState } from "react";

import {
  type ExternalStoreAdapter,
  type ThreadMessageLike,
  useExternalStoreRuntime,
} from "@assistant-ui/react";

import {
  entityCitation,
  type ResolveCitation,
} from "@/components/ai-components/chat-inline-citation";
import { ChatThread, ChatThreadUserMessage } from "@/components/ai-components/chat-thread";
import { CursorQuestionsPanel } from "@/components/ai-components/cursor-questions-panel";
import { FileCode } from "@/components/ai-components/file-code";
import { InterruptedReply } from "@/components/ai-components/interrupted-reply";
import { Markdown } from "@/components/ai-components/markdown";
import { MessageActions } from "@/components/ai-components/message-actions";
import { quoteReply, SelectionActions } from "@/components/ai-components/selection-actions";
import {
  TerminalResult,
  type TerminalResultStatus,
} from "@/components/ai-components/terminal-result";
import { ThinkingState, type ThinkingStep } from "@/components/ai-components/thinking-state";
import { ToolCallApproval } from "@/components/ai-components/tool-call-approval";
import { BenchmarkReview } from "@/components/evaluations/benchmark-review";
import { ToolMark } from "@/components/tool-mark";
import { Button } from "@/components/ui/button";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { Icon } from "@/components/ui/icons";
import { cn } from "@/lib/utils";
import type {
  Cell,
  ChatAccess,
  EvalCriterion,
  WorkshopCellReference,
  WorkshopInteraction,
  WorkshopMessage,
} from "@/openapi";
import { activityIcon } from "./chat-activity";
import { WorkshopHandoff } from "./workshop-handoff";
import { useWorkspaceChatDraft } from "./workspace-chat-draft";

const WorkshopPresentationView = lazy(() => import("./workshop-presentation"));
type ConversationMessage = WorkshopMessage & {
  steps?: WorkshopMessage[];
  entries?: WorkshopMessage[];
};
const activityLabels: Record<string, string> = {
  completed: "Done",
  failed: "Failed",
  interrupted: "Interrupted",
  preparing: "Preparing",
  running: "Running",
};
const References = createContext<{
  cells: Cell[];
  onSelect: (id: string) => void;
  nodes?: { id: string; title: string }[];
  onNode?: (id: string) => void;
}>({ cells: [], onSelect: () => {} });

function useCitationResolver(): ResolveCitation {
  const { cells, nodes, onSelect, onNode } = useContext(References);
  return (href) => {
    const match = /^(?:#(node|cell)=|cell:)([^#\s]+)$/.exec(href);
    if (!match) return entityCitation(href);
    const [, kind, encodedId] = match;
    let id: string;
    try {
      id = decodeURIComponent(encodedId);
    } catch {
      return;
    }
    if (kind === "node") {
      const node = nodes?.find((item) => item.id === id);
      if (node && onNode) return { kind: "Step", onOpen: () => onNode(id), title: node.title };
      return;
    }
    const cell = cells.find((item) => item.id === id);
    if (cell) return { kind: "Dataset version", onOpen: () => onSelect(id), title: cell.title };
  };
}

function UserCitations({ text }: { text: string }) {
  return <Markdown resolveCitation={useCitationResolver()} text={text} />;
}

function MessageText({ text, streaming = false }: { text: string; streaming?: boolean }) {
  const resolve = useCitationResolver();
  return <Markdown resolveCitation={resolve} streaming={streaming} text={text} />;
}

// A reasoning summary opens each section with a bold heading; the newest one names the thought.
const thoughtHeading = (text: string) =>
  [...text.matchAll(/^\*\*(.+?)\*\*\s*$/gm)].at(-1)?.[1] ??
  text.trim().split("\n").at(-1)?.slice(0, 96);

// A workspace run has its own card; every other step shares the reply's activity list.
function isActivity(entry: WorkshopMessage) {
  return (
    entry.role === "thinking" ||
    (entry.role === "activity" && !entry.terminal && !entry.datasetActivity)
  );
}

const terminalStatus = (status: string): TerminalResultStatus =>
  status === "preparing"
    ? "pending"
    : status === "running"
      ? "running"
      : status === "completed"
        ? "success"
        : status === "failed"
          ? "failed"
          : "stopped";

// A run's card sits where the run happened; the steps and replies between runs stay together.
function replySegments(entries: WorkshopMessage[]) {
  const segments: WorkshopMessage[][] = [[]];
  for (const entry of entries) {
    if (entry.terminal || entry.datasetActivity) segments.push([entry], []);
    else segments.at(-1)!.push(entry);
  }
  return segments.filter((segment) => segment.length);
}

const callStopped = (entry: WorkshopMessage) =>
  ["cancelled", "interrupted", "refused"].includes(entry.status);

const callRunning = (entry: WorkshopMessage) =>
  entry.status === "running" || entry.status === "preparing";

const callState = (entry: WorkshopMessage) =>
  entry.status === "refused"
    ? "Not run"
    : entry.status === "cancelled"
      ? "Stopped"
      : (activityLabels[entry.status] ?? entry.status);

const callsStatus = (calls: WorkshopMessage[]): ThinkingStep["status"] =>
  calls.some(callRunning)
    ? "active"
    : calls.some((entry) => entry.status === "failed")
      ? "error"
      : calls.every(callStopped)
        ? "pending"
        : "done";

const hasBody = (entry: WorkshopMessage) => Boolean(entry.code?.trim() || entry.error);

// A connector's tools are named <connection>__<tool>; its calls share the connection's row.
const integration = (entry: WorkshopMessage) => entry.tool?.split("__")[0] ?? entry.text;

const callsState = (calls: WorkshopMessage[]) => {
  const running = calls.find(callRunning);
  if (running) return callState(running);
  const failed = calls.filter((entry) => entry.status === "failed").length;
  if (failed) return `${failed} failed`;
  // A call refused and then made again is done.
  return callState(calls.find((entry) => !callStopped(entry)) ?? calls.at(-1)!);
};

function CallBody({ entry }: { entry: WorkshopMessage }) {
  const tool = activityIcon(entry.tool);
  return (
    <div className="min-w-0 space-y-1.5">
      {entry.code?.trim() && (
        <FileCode
          language={tool === "python" ? "python" : entry.tool === "sql" ? "sql" : "bash"}
          source={entry.code}
        />
      )}
      {entry.error && (
        <p
          className={cn(
            "text-xs break-words whitespace-pre-wrap",
            callStopped(entry) ? "text-muted-foreground" : "text-destructive"
          )}
        >
          {entry.error}
        </p>
      )}
    </div>
  );
}

// One call inside a row of calls to the same integration.
function GroupedCall({ entry, name }: { entry: WorkshopMessage; name: string }) {
  const title = (
    <>
      <span className="min-w-0 flex-1 break-words">
        <span className={entry.status === "failed" ? "text-destructive" : "text-foreground"}>
          {name}
        </span>
        {entry.detail && <span className="text-muted-foreground"> {entry.detail}</span>}
      </span>
      <span className="shrink-0 text-muted-foreground">{callState(entry)}</span>
    </>
  );
  const row = "flex min-h-6 w-full items-start gap-2 text-left text-xs leading-5";
  if (!hasBody(entry)) return <li className={row}>{title}</li>;
  return (
    <li>
      <Collapsible defaultOpen={callRunning(entry) || entry.status === "failed"}>
        <CollapsibleTrigger
          className={cn(row, "group rounded-sm focus-visible:outline-2 focus-visible:outline-ring")}
        >
          {title}
          <Icon.chevronDown
            aria-hidden
            className="mt-1 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 pb-1">
          <CallBody entry={entry} />
        </CollapsibleContent>
      </Collapsible>
    </li>
  );
}

// Consecutive calls to one integration share a row.
function callRuns(entries: WorkshopMessage[]) {
  const runs: WorkshopMessage[][] = [];
  for (const entry of entries) {
    const last = runs.at(-1);
    if (
      entry.role === "activity" &&
      last?.[0].role === "activity" &&
      integration(last[0]) === integration(entry)
    )
      last.push(entry);
    else runs.push([entry]);
  }
  return runs;
}

function ReplyActivity({ entries, active }: { entries: WorkshopMessage[]; active: boolean }) {
  const [open, setOpen] = useState<boolean | undefined>();
  const tools = entries.filter((entry) => entry.role === "activity");
  const failed = tools.filter((entry) => entry.status === "failed").length;
  const executing = tools.some(callRunning);
  const working = entries.length
    ? entries.some((entry) => ["streaming", "running", "preparing"].includes(entry.status))
    : active;
  const thought = entries.filter((entry) => entry.role === "thinking").at(-1);
  const steps = callRuns(entries).map((calls): ThinkingStep => {
    const [entry] = calls;
    if (entry.role === "thinking") {
      return {
        content: (
          <div className="text-muted-foreground">
            <MessageText streaming={entry.status === "streaming"} text={entry.text} />
          </div>
        ),
        icon: <Icon.ai aria-hidden className="size-3.5" />,
        id: entry.id,
        label:
          entry.status === "streaming" ? "Thinking" : (thoughtHeading(entry.text) ?? "Reasoning"),
        status: entry.status === "streaming" ? "active" : "done",
      };
    }
    if (calls.length > 1) {
      // "huggingface · hf fs" is the connection and its tool; a native tool has one name.
      const connector = entry.tool?.includes("__");
      const shared = calls.every((call) => call.text === entry.text);
      const name = connector
        ? entry.text.split(" · ")[0]
        : shared
          ? entry.text
          : integration(entry).replaceAll("_", " ");
      return {
        collapsible: true,
        content: (
          <ol className="min-w-0 space-y-1">
            {calls.map((call) => (
              <GroupedCall
                entry={call}
                key={call.id}
                name={connector ? call.text.split(" · ").slice(1).join(" · ") : call.text}
              />
            ))}
          </ol>
        ),
        id: entry.id,
        label: `${name} · ${calls.length} calls`,
        stateLabel: callsState(calls),
        status: callsStatus(calls),
        tool: entry.tool,
      };
    }
    return {
      collapsible: true,
      content: hasBody(entry) ? <CallBody entry={entry} /> : undefined,
      detail: entry.detail || undefined,
      id: entry.id,
      label: entry.text,
      stateLabel: callsState(calls),
      status: callsStatus(calls),
      tool: entry.tool,
    };
  });
  const summary = tools.length
    ? `${thought ? "Thought · " : ""}Ran ${tools.length} ${tools.length === 1 ? "tool" : "tools"}${failed ? ` · ${failed} failed` : ""}`
    : ["Thought", thought && thoughtHeading(thought.text)].filter(Boolean).join(" · ");
  return (
    <ThinkingState
      classNames={{ header: "w-fit max-w-full", root: "bg-transparent p-0", steps: "pt-2" }}
      label={working ? (executing ? "Running tools" : "Thinking") : summary}
      onOpenChange={setOpen}
      open={open ?? (working || (active && entries.at(-1)?.status === "failed"))}
      status={working ? "working" : failed ? "error" : "settled"}
      steps={steps}
    />
  );
}

function convertMessage(message: ConversationMessage): ThreadMessageLike {
  return {
    content: (message.entries ?? [message]).map((entry) => {
      if (entry.role === "activity")
        return {
          args: {},
          argsText: entry.code || "",
          toolCallId: entry.id,
          toolName: entry.tool || "action",
          type: "tool-call" as const,
          ...(entry.status === "running" || entry.status === "preparing"
            ? {}
            : {
                isError: entry.status === "failed",
                result: entry.error || activityLabels[entry.status] || entry.status,
              }),
        };
      if (entry.presentation)
        return { data: entry, name: "workshop-result", type: "data" as const };
      if (entry.role === "thinking") return { text: entry.text, type: "reasoning" as const };
      return { text: entry.text, type: "text" as const };
    }),
    id: message.id,
    metadata: { custom: { workshop: message } },
    role: message.role === "user" ? "user" : "assistant",
    ...(message.role === "user"
      ? {}
      : {
          status:
            message.status === "streaming" ||
            message.status === "running" ||
            message.status === "preparing" ||
            message.steps?.some((step) => step.status === "running" || step.status === "preparing")
              ? { type: "running" as const }
              : { reason: "stop" as const, type: "complete" as const },
        }),
  };
}

export function useWorkshopRuntime(
  messages: WorkshopMessage[],
  adapter: Omit<ExternalStoreAdapter<ConversationMessage>, "messages" | "convertMessage">
) {
  const grouped = useMemo(() => groupMessages(messages), [messages]);
  return useExternalStoreRuntime({ ...adapter, convertMessage, messages: grouped });
}

export function groupMessages(messages: WorkshopMessage[]): ConversationMessage[] {
  const result: ConversationMessage[] = [];
  for (const message of messages) {
    if (
      !(message.text || message.cells?.length || message.presentation) ||
      ["pending", "delivering", "removed"].includes(message.status)
    )
      continue;
    const previous = result.at(-1);
    if (
      !message.questions &&
      !previous?.questions &&
      message.role !== "user" &&
      previous?.role !== "user" &&
      previous?.entries &&
      previous.id.split(":")[0] === message.id.split(":")[0]
    ) {
      previous.entries!.push(message);
      if (message.role === "activity") previous.steps!.push(message);
      previous.status = message.status;
      previous.cells = [
        ...new Map(
          [...(previous.cells ?? []), ...(message.cells ?? [])].map((cell) => [cell.id, cell])
        ).values(),
      ];
    } else {
      result.push({
        ...message,
        entries: [message],
        steps: message.role === "activity" ? [message] : [],
      });
    }
  }
  return result;
}

const CREDENTIALS: Record<string, string> = { huggingface: "Hugging Face token" };

const accessFields = (access: ChatAccess) => [
  { label: "Declared hosts", value: access.hosts.join(", ") },
  { label: "Network", value: "All hosts, until this request ends" },
  ...(access.credentials.length
    ? [
        {
          label: "Credentials",
          value: access.credentials.map((name) => CREDENTIALS[name] ?? name).join(", "),
        },
      ]
    : []),
];

export function WorkshopConversation({
  activeTaskId,
  messages,
  cells,
  onSelect,
  onSend,
  onCell,
  nodes,
  onNode,
  onAnswer,
  readOnly = false,
  sending = false,
}: {
  sending?: boolean;
  onAnswer?: (
    question: string,
    text: string,
    approved?: boolean,
    criteria?: EvalCriterion[]
  ) => Promise<void>;
  readOnly?: boolean;
  nodes?: { id: string; title: string }[];
  onNode?: (id: string) => void;
  activeTaskId?: string;
  messages: WorkshopMessage[];
  cells: Cell[];
  onSelect: (id: string) => void;
  onSend: (text: string, interaction?: WorkshopInteraction) => Promise<void>;
  onCell: (cell: WorkshopCellReference) => void;
}) {
  const draft = useWorkspaceChatDraft();
  const grouped = useMemo(() => groupMessages(messages), [messages]);
  const currentReply = grouped.at(-1);
  // A message being sent, or sent and not yet replied to, has nothing else to show for it.
  const starting =
    sending || (activeTaskId && currentReply?.role === "user") ? "reply:starting" : undefined;
  const thread: ConversationMessage[] = starting
    ? [...grouped, { id: starting, role: "assistant", status: "running", text: "" }]
    : grouped;
  return (
    <References.Provider value={{ cells, nodes, onNode, onSelect }}>
      <div className="workshop-history relative flex min-h-0 flex-1 flex-col">
        <SelectionActions
          actions={[
            { id: "quote", label: "Quote" },
            {
              id: "explain",
              label: "Explain",
              prompt: "Explain this finding and the evidence behind it.",
            },
          ]}
          className="flex min-h-0 flex-1 flex-col"
          disabled={!draft}
          onAction={({ message }) => draft?.(message)}
          onAsk={({ message }) => draft?.(message)}
        >
          <ChatThread
            classNames={{ content: "gap-8 px-3 pt-4 pb-10", turn: "gap-4" }}
            empty={null}
            id={messages[0]?.id.split(":")[0]}
            jumpLabel="Scroll to latest message"
            label="Conversation"
            messages={thread}
            renderMessage={(message) => {
              if (message.id === starting)
                return (
                  <article aria-label="Overmind response" className="min-w-0">
                    <ReplyActivity active entries={[]} />
                  </article>
                );
              if (message.access && message.question)
                return (
                  <ToolCallApproval
                    detail={message.access.purpose}
                    disabled={readOnly || !onAnswer}
                    fields={accessFields(message.access)}
                    icon={
                      message.access.credentials.includes("huggingface") ? (
                        <ToolMark name="huggingface" />
                      ) : undefined
                    }
                    key={message.id}
                    onDecide={(approved, reason) =>
                      onAnswer
                        ? onAnswer(
                            message.question!,
                            approved ? "Approved" : reason || "Denied",
                            approved
                          )
                        : Promise.reject()
                    }
                    status={
                      message.status === "question_pending"
                        ? "pending"
                        : message.status === "question_cancelled"
                          ? "cancelled"
                          : message.approved
                            ? "approved"
                            : "denied"
                    }
                    title="Internet access"
                  />
                );
              if (message.evalSetDraft && message.question)
                return (
                  <BenchmarkReview
                    disabled={readOnly || !onAnswer}
                    draft={message.evalSetDraft}
                    key={message.id}
                    onDecide={(approved, text, criteria) =>
                      onAnswer
                        ? onAnswer(message.question!, text, approved, criteria)
                        : Promise.reject()
                    }
                    status={
                      message.status === "question_pending"
                        ? "pending"
                        : message.status === "question_cancelled"
                          ? "cancelled"
                          : message.approved
                            ? "approved"
                            : "rejected"
                    }
                  />
                );
              if (message.questions && message.question)
                return (
                  <CursorQuestionsPanel
                    disabled={readOnly || !onAnswer}
                    key={message.id}
                    onSubmit={(text) =>
                      onAnswer ? onAnswer(message.question!, text) : Promise.reject()
                    }
                    questions={message.questions}
                    state={
                      message.status === "question_pending"
                        ? "pending"
                        : message.status === "question_answered"
                          ? "answered"
                          : "cancelled"
                    }
                  />
                );
              const user = message.role === "user";
              const segments = replySegments(message.entries ?? [message]);
              const working =
                !!activeTaskId &&
                message === currentReply &&
                segments.at(-1)![0].id.split(":")[0] === activeTaskId;
              const lastRun = segments.at(-1)![0].terminal ? segments.at(-1)![0] : undefined;
              return (
                <article
                  aria-label={user ? "Your message" : "Overmind response"}
                  className="min-w-0"
                  data-role={message.role}
                >
                  {user ? (
                    <ChatThreadUserMessage
                      renderText={(text) => <UserCitations text={text} />}
                      text={message.text}
                    />
                  ) : (
                    <div className="flex min-w-0 flex-col gap-3" data-slot="chat-thread-assistant">
                      {segments.flatMap((segment) => {
                        const activity = segment.filter(isActivity);
                        return segment.map((entry) => {
                          if (entry.datasetActivity)
                            return (
                              <WorkshopHandoff activity={entry.datasetActivity} key={entry.id} />
                            );
                          if (isActivity(entry))
                            return entry === activity[0] ? (
                              <ReplyActivity
                                active={
                                  working &&
                                  segment === segments.at(-1) &&
                                  isActivity(segment.at(-1)!)
                                }
                                entries={activity}
                                key={entry.id}
                              />
                            ) : null;
                          if (entry.terminal)
                            return (
                              <TerminalResult
                                command={entry.text}
                                durationMs={entry.terminal.durationMs ?? undefined}
                                exitCode={entry.terminal.exitCode}
                                key={entry.id}
                                output={entry.terminal.output}
                                prompt
                                startedAt={entry.terminal.startedAt ?? undefined}
                                status={terminalStatus(entry.status)}
                                truncated={entry.terminal.truncated}
                              />
                            );
                          return entry.presentation ? (
                            <Suspense
                              fallback={
                                <p className="text-xs text-muted-foreground">Loading result…</p>
                              }
                              key={entry.id}
                            >
                              <WorkshopPresentationView
                                message={entry}
                                messages={messages}
                                onCell={onCell}
                                onSend={onSend}
                              />
                            </Suspense>
                          ) : (
                            <MessageText
                              key={entry.id}
                              streaming={entry.status === "streaming"}
                              text={entry.text}
                            />
                          );
                        });
                      })}
                      {/* A finished run is followed by thought that has not arrived yet. */}
                      {working && lastRun && !["running", "preparing"].includes(lastRun.status) && (
                        <ReplyActivity active entries={[]} />
                      )}
                    </div>
                  )}
                  {!message.presentation && !!message.cells?.length && (
                    <div className={`mt-2 flex flex-wrap gap-1 ${user ? "justify-end" : ""}`}>
                      {message.cells.map((reference) => (
                        <Button
                          aria-label={`Show ${reference.name || "dataset"} cell`}
                          className="max-w-full"
                          key={reference.id}
                          onClick={() => onCell(reference)}
                          size="xs"
                          variant="secondary"
                        >
                          <Icon.dataset className="text-cat-2" />
                          <span className="truncate">{reference.name || "Dataset cell"}</span>
                        </Button>
                      ))}
                    </div>
                  )}
                  {!user &&
                    message.entries?.some((entry) => entry.role === "assistant" && entry.text) && (
                      <div className="mt-2 text-muted-foreground">
                        <MessageActions
                          onQuote={
                            draft
                              ? () =>
                                  draft(
                                    quoteReply(
                                      message
                                        .entries!.filter((entry) => entry.role === "assistant")
                                        .map((entry) => entry.text)
                                        .join("\n\n")
                                    )
                                  )
                              : undefined
                          }
                          text={message.entries
                            .filter((entry) => entry.role === "assistant")
                            .map((entry) => entry.text)
                            .join("\n\n")}
                        />
                      </div>
                    )}
                  {user && message.status === "cancelled" && (
                    <p className="mt-1 text-right text-xs text-muted-foreground">
                      Not delivered · task cancelled
                    </p>
                  )}
                  {!user && ["interrupted", "cancelled"].includes(message.status) && (
                    <InterruptedReply
                      className="mt-2"
                      reason={message.status === "cancelled" ? "stopped" : "error"}
                    />
                  )}
                </article>
              );
            }}
          />
        </SelectionActions>
      </div>
    </References.Provider>
  );
}