Skip to content

The platform for continuously improving AI agents.

23.2 KB
Raw Blame
import {
  type ComponentProps,
  type CSSProperties,
  type ReactNode,
  type Ref,
  useEffect,
  useId,
  useImperativeHandle,
  useRef,
  useState,
  useSyncExternalStore,
} from "react";

import {
  type AssistantRuntime,
  AssistantRuntimeProvider,
  ComposerPrimitive,
  ThreadPrimitive,
} from "@assistant-ui/react";

import {
  ChatCitationDraft,
  readCitationDraft,
} from "@/components/ai-components/chat-inline-citation";
import { useGhostCompletion } from "@/components/ai-components/ghost-completion";
import { PromptInput } from "@/components/ai-components/prompt-input";
import {
  WORKSHOP_PANEL_WIDTH,
  WorkshopPanelResize,
} from "@/components/datasets/workshop-panel-resize";
import { ToolMark } from "@/components/tool-mark";
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 { useGuestGate } from "@/hooks/use-guest-gate";
import { editMentionRanges, serializeMentions } from "@/lib/entity-mentions";
import { errorMessage, notify } from "@/lib/notify";
import { cn } from "@/lib/utils";
import { appendChatDraft, WorkspaceChatDraft } from "./workspace-chat-draft";

interface ChatReference {
  icon?: ReactNode;
  id: string;
  title: string;
  kind: "cell" | "node";
}

export interface WorkspaceChatHandle {
  open: () => void;
  close: () => void;
}
export function WorkspaceChat({
  runtime,
  fullScreen = false,
  conversation,
  collapsedActivity,
  showStatus = false,
  completions = [],
  queue,
  selection,
  attachment,
  attachments,
  references = [],
  status,
  activityTool,
  requestState,
  active,
  queueing,
  stopping,
  sending,
  controlling,
  sendDisabled,
  sendHint,
  failure,
  suggestion,
  initiallyOpen = false,
  label = "Workshop chat",
  inputLabel = "Transformation request",
  placeholder = "Ask about the data or describe a change…",
  maxLength = 16000,
  ref,
}: {
  fullScreen?: boolean;
  runtime: AssistantRuntime;
  conversation: ReactNode;
  collapsedActivity?: string;
  showStatus?: boolean;
  completions?: string[];
  queue?: ReactNode;
  selection?: ReactNode;
  attachment?: ReactNode;
  attachments?: ReactNode;
  references?: ChatReference[];
  status: string;
  activityTool?: string;
  requestState?: "working" | "complete" | "attention" | "stopped";
  active: boolean;
  queueing: boolean;
  stopping: boolean;
  sending: boolean;
  controlling: boolean;
  sendDisabled: boolean;
  sendHint: string;
  failure?: unknown;
  suggestion?: string;
  initiallyOpen?: boolean;
  label?: string;
  inputLabel?: string;
  placeholder?: string;
  maxLength?: number;
  ref?: Ref<WorkspaceChatHandle>;
}) {
  const guard = useGuestGate();
  const text = useSyncExternalStore(
    runtime.thread.composer.subscribe,
    () => runtime.thread.composer.getState().text
  );
  const ghost = useGhostCompletion(
    text,
    (value) => runtime.thread.composer.setText(value),
    completions,
    true
  );
  const [expanded, setExpanded] = useState(initiallyOpen);
  const [panel, setPanel] = useState(initiallyOpen);
  const [panelWidth, setPanelWidth] = useState(WORKSHOP_PANEL_WIDTH);
  const [resizing, setResizing] = useState(false);
  const [mentionIndex, setMentionIndex] = useState(0);
  const textarea = useRef<HTMLTextAreaElement>(null);
  const mirror = useRef<HTMLDivElement>(null);
  const draft = readCitationDraft(text);
  const mention = references.length ? draft.text.match(/(?:^|\s)@([^\s@]*)$/) : null;
  const mentionStart = mention ? draft.text.length - mention[1].length - 1 : -1;
  const mentionItems =
    mention && !draft.ranges.some(({ start, end }) => start <= mentionStart && mentionStart < end)
      ? references
          .filter((item) => item.title.toLowerCase().includes(mention[1].toLowerCase()))
          .slice(0, 8)
      : [];
  const mentionOpen = mentionItems.length > 0;
  const pickMention = (item: ChatReference) => {
    const label = `@${item.title}`;
    const next = serializeMentions(`${draft.text.slice(0, mentionStart)}${label} `, [
      ...draft.ranges,
      {
        end: mentionStart + label.length,
        entity: { href: `#${item.kind}=${encodeURIComponent(item.id)}` },
        start: mentionStart,
      },
    ]);
    if (next.length > maxLength) {
      notify.info("Draft is too long to add this selection");
      return;
    }
    runtime.thread.composer.setText(next);
    setMentionIndex(0);
    requestAnimationFrame(() => {
      textarea.current?.focus();
      const end = textarea.current?.value.length ?? 0;
      textarea.current?.setSelectionRange(end, end);
    });
  };
  const hasCitations = draft.ranges.length > 0;
  const updateDraftText = (value: string) =>
    runtime.thread.composer.setText(
      serializeMentions(value, editMentionRanges(draft.text, value, draft.ranges))
    );
  const draftInput: ComponentProps<typeof ComposerPrimitive.Input> = {
    ...ghost.inputProps,
    maxLength: maxLength - (text.length - draft.text.length),
    onChange: (event) => {
      if (!hasCitations) return;
      event.preventDefault();
      updateDraftText(event.currentTarget.value);
    },
    onCompositionEnd: (event) => {
      ghost.inputProps.onCompositionEnd(event);
      if (hasCitations) event.preventDefault();
    },
    onScroll: (event) => {
      ghost.inputProps.onScroll(event);
      if (mirror.current) mirror.current.scrollTop = event.currentTarget.scrollTop;
    },
    value: draft.text,
  };
  const draftLayer = (className: string) =>
    hasCitations && (
      <ChatCitationDraft
        className={className}
        ranges={draft.ranges}
        ref={mirror}
        text={draft.text}
      />
    );
  const inputClass = cn(
    "col-start-1 row-start-1 block min-h-7 max-h-52 w-full resize-none border-0 bg-transparent px-1 py-1.5 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-0",
    hasCitations ? "leading-6" : "leading-4"
  );
  const inputColor = hasCitations ? "text-transparent caret-foreground" : "text-foreground";
  const removeMention = (event: React.KeyboardEvent<HTMLTextAreaElement>) => {
    const { selectionStart, selectionEnd } = event.currentTarget;
    if (selectionStart !== selectionEnd || !["Backspace", "Delete"].includes(event.key)) return;
    const range = draft.ranges.find(({ start, end }) =>
      event.key === "Backspace" ? end === selectionStart : start === selectionStart
    );
    if (!range) return;
    event.preventDefault();
    updateDraftText(draft.text.slice(0, range.start) + draft.text.slice(range.end));
    requestAnimationFrame(() => textarea.current?.setSelectionRange(range.start, range.start));
  };
  const bodyId = useId();
  const panelId = useId();
  const focusOnExpansion = useRef(false);
  const compact = !panel && collapsedActivity !== undefined;
  const requestLabel = sending ? "Sending message" : compact ? collapsedActivity : status;
  const state = sending ? "working" : requestState;
  const requestIcon =
    state === "working" && activityTool && !sending ? (
      <ToolMark name={activityTool} />
    ) : state === "working" ? (
      <Spinner size="sm" />
    ) : state === "complete" ? (
      <Icon.success className="size-3.5 text-success" />
    ) : state === "attention" ? (
      <Icon.warning className="size-3.5 text-warning" />
    ) : state === "stopped" ? (
      <Icon.stop className="size-3.5 text-muted-foreground" />
    ) : null;
  useEffect(() => {
    if (expanded && focusOnExpansion.current) {
      focusOnExpansion.current = false;
      textarea.current?.focus();
    }
  }, [expanded]);
  const collapse = () => {
    if (fullScreen) return;
    setPanel(false);
    setResizing(false);
    setExpanded(false);
    textarea.current?.blur();
  };

  useImperativeHandle(ref, () => ({
    close: collapse,
    open: () => {
      setPanel(true);
      setExpanded(true);
    },
  }));

  return (
    <AssistantRuntimeProvider runtime={runtime}>
      <WorkspaceChatDraft.Provider
        value={(text) => {
          const next = appendChatDraft(runtime.thread.composer.getState().text, text, maxLength);
          if (next === null) {
            notify.info("Draft is too long to add this selection");
            return;
          }
          runtime.thread.composer.setText(next);
          setExpanded(true);
          setPanel(true);
          requestAnimationFrame(() => textarea.current?.focus());
        }}
      >
        <ThreadPrimitive.Root asChild>
          <Card
            aria-label={label}
            className="workshop-chat-surface workshop-dock absolute bottom-3 z-20 flex min-h-0 flex-col gap-2 overflow-hidden bg-muted p-1.5 data-[compact=true]:p-0"
            data-compact={compact}
            data-expanded={expanded}
            data-fullscreen={fullScreen}
            data-panel={panel}
            data-resizing={resizing}
            id={panelId}
            onBlurCapture={(event) => {
              if (
                !panel &&
                !mentionOpen &&
                !focusOnExpansion.current &&
                !event.currentTarget.contains(event.relatedTarget) &&
                !(
                  event.relatedTarget instanceof Element &&
                  event.relatedTarget.closest("[data-chat-composer-popover]")
                ) &&
                !event.currentTarget.matches(":hover")
              )
                setExpanded(false);
            }}
            onFocusCapture={(event) => {
              if (compact || event.target.closest("[data-workshop-view-toggle]")) return;
              if (!expanded && event.target.closest(".workshop-dock-footer"))
                focusOnExpansion.current = true;
              setExpanded(true);
            }}
            onKeyDown={(event) => {
              if (event.key === "Escape" && !event.defaultPrevented) {
                event.preventDefault();
                collapse();
              }
            }}
            onMouseEnter={() => {
              if (!compact) setExpanded(true);
            }}
            onMouseLeave={(event) => {
              if (
                !panel &&
                !mentionOpen &&
                !event.currentTarget.contains(document.activeElement) &&
                !document.activeElement?.closest("[data-chat-composer-popover]")
              )
                setExpanded(false);
            }}
            role="region"
            style={{ "--workshop-panel-width": `${panelWidth}px` } as CSSProperties}
          >
            {panel && conversation}
            {panel && !!failure && (
              <Alert className="w-auto text-xs">
                {errorMessage(failure, "Could not load the conversation.")}
              </Alert>
            )}
            {compact ? (
              <PromptInput
                asChild
                className="workshop-compact-input flex-row items-center gap-2 border-0 bg-transparent"
              >
                <ComposerPrimitive.Root
                  aria-label={`${inputLabel} composer`}
                  className="p-2"
                  onSubmit={guard()}
                >
                  {state && (
                    <div className="flex max-w-[45%] shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
                      <span aria-hidden="true" className="flex shrink-0">
                        {requestIcon}
                      </span>
                      <span className={text || ghost.suffix ? "truncate" : "sr-only"} role="status">
                        {requestLabel}
                      </span>
                    </div>
                  )}
                  <div className="relative grid min-w-0 flex-1 overflow-hidden">
                    {ghost.layer}
                    {ghost.hint}
                    {draftLayer(inputClass)}
                    <ComposerPrimitive.Input
                      {...draftInput}
                      aria-label={inputLabel}
                      cancelOnEscape={false}
                      className={cn(inputClass, inputColor)}
                      disabled={sending}
                      onKeyDown={(event) => {
                        removeMention(event);
                        if (event.key === "Enter") guard()(event);
                      }}
                      placeholder={ghost.suffix ? "" : requestLabel}
                      ref={textarea}
                      rows={1}
                    />
                  </div>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <Button
                        aria-label="Open chat"
                        data-workshop-view-toggle
                        onClick={() => {
                          setPanel(true);
                          setExpanded(true);
                        }}
                        size="icon-xs"
                        type="button"
                        variant="ghost"
                      >
                        <Icon.expand />
                      </Button>
                    </TooltipTrigger>
                    <TooltipContent>Open chat</TooltipContent>
                  </Tooltip>
                </ComposerPrimitive.Root>
              </PromptInput>
            ) : (
              <div className="workshop-composer-stack flex min-w-0 shrink-0 flex-col gap-1">
                {panel && (sending || showStatus) && state && (
                  <div className="flex min-w-0 items-center gap-1.5 px-2 py-1 text-xs text-muted-foreground">
                    <span aria-hidden="true" className="flex shrink-0">
                      {requestIcon}
                    </span>
                    <span className="truncate" role="status">
                      {requestLabel}
                    </span>
                  </div>
                )}
                {expanded && queue}
                {expanded && attachments}
                <PromptInput asChild className="workshop-chat-inner shrink-0">
                  <ComposerPrimitive.Root aria-label={`${inputLabel} composer`} onSubmit={guard()}>
                    <div className="workshop-dock-body" id={bodyId} inert={!expanded}>
                      {mentionOpen && (
                        <div
                          aria-label="Canvas mentions"
                          className="max-h-52 overflow-auto border-b border-border/70 bg-card p-1"
                          role="listbox"
                        >
                          {mentionItems.map((item, index) => (
                            <button
                              aria-selected={index === mentionIndex % mentionItems.length}
                              className="flex w-full items-center gap-2 rounded-sm px-2 py-1.5 text-left text-xs hover:bg-accent aria-selected:bg-accent"
                              key={`${item.kind}:${item.id}`}
                              onClick={() => pickMention(item)}
                              role="option"
                              type="button"
                            >
                              {item.icon}
                              <span className="truncate">{item.title}</span>
                            </button>
                          ))}
                        </div>
                      )}
                      <div className="relative grid min-h-0 overflow-hidden workspace-ghost">
                        {ghost.layer}
                        {ghost.hint}
                        {draftLayer(inputClass)}
                        <ComposerPrimitive.Input
                          {...draftInput}
                          aria-label={inputLabel}
                          cancelOnEscape={false}
                          className={cn("workshop-chat-input", inputClass, inputColor)}
                          disabled={sending}
                          onKeyDown={(event) => {
                            if (event.nativeEvent.isComposing) return;
                            removeMention(event);
                            if (
                              mentionOpen &&
                              ["ArrowDown", "ArrowUp", "Enter", "Tab", "Escape"].includes(event.key)
                            ) {
                              event.preventDefault();
                              event.stopPropagation();
                              if (event.key === "ArrowDown")
                                setMentionIndex((index) => (index + 1) % mentionItems.length);
                              else if (event.key === "ArrowUp")
                                setMentionIndex(
                                  (index) => (index + mentionItems.length - 1) % mentionItems.length
                                );
                              else if (event.key === "Enter" || event.key === "Tab")
                                pickMention(mentionItems[mentionIndex % mentionItems.length]);
                              else updateDraftText(draft.text.slice(0, -1));
                              return;
                            }
                            if (
                              event.key === "Tab" &&
                              !event.shiftKey &&
                              !event.altKey &&
                              !event.ctrlKey &&
                              !event.metaKey &&
                              !event.nativeEvent.isComposing &&
                              suggestion &&
                              !event.currentTarget.value
                            ) {
                              event.preventDefault();
                              runtime.thread.composer.setText(suggestion);
                            }
                            if (event.key === "Enter") guard()(event);
                          }}
                          placeholder={
                            ghost.suffix
                              ? ""
                              : suggestion || (queueing ? "Queue a follow-up…" : placeholder)
                          }
                          ref={textarea}
                          rows={1}
                        />
                      </div>
                    </div>
                    <div className="workshop-dock-footer flex min-w-0 items-center gap-2">
                      {expanded ? (
                        <>
                          {attachment}
                          {!panel && <div className="min-w-0 flex-1">{selection}</div>}
                          {active && (
                            <Tooltip>
                              <TooltipTrigger asChild>
                                <ComposerPrimitive.Cancel asChild>
                                  <Button
                                    aria-label={stopping ? "Stopping…" : "Stop"}
                                    disabled={controlling || stopping}
                                    onClick={guard()}
                                    size="icon-xs"
                                    type="button"
                                    variant="ghost"
                                  >
                                    {stopping ? <Spinner size="sm" /> : <Icon.stop />}
                                  </Button>
                                </ComposerPrimitive.Cancel>
                              </TooltipTrigger>
                              <TooltipContent>Stop run</TooltipContent>
                            </Tooltip>
                          )}
                          <Tooltip>
                            <TooltipTrigger asChild>
                              <span>
                                <ComposerPrimitive.Send asChild>
                                  <Button
                                    aria-label={queueing ? "Queue" : "Send"}
                                    disabled={sendDisabled}
                                    onClick={guard()}
                                    size={!panel && !queueing ? "sm" : "icon-sm"}
                                    type="button"
                                    variant="send"
                                  >
                                    {sending ? <Spinner size="sm" /> : <Icon.send />}
                                    {!panel && !queueing && "Send"}
                                  </Button>
                                </ComposerPrimitive.Send>
                              </span>
                            </TooltipTrigger>
                            <TooltipContent>{sendHint}</TooltipContent>
                          </Tooltip>
                        </>
                      ) : (
                        <Button
                          aria-controls={bodyId}
                          aria-expanded={false}
                          aria-label={`Expand ${label}`}
                          className="min-w-0 flex-1 justify-start border-0 bg-transparent text-muted-foreground"
                          onClick={() => {
                            focusOnExpansion.current = true;
                            setExpanded(true);
                          }}
                          size="xs"
                          type="button"
                          variant="outline"
                        >
                          <span className="min-w-0 flex-1 truncate text-left">{status}</span>
                        </Button>
                      )}
                      {panel && !fullScreen && (
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              aria-label="Minimize chat"
                              data-workshop-view-toggle
                              onClick={collapse}
                              size="icon-xs"
                              type="button"
                              variant="ghost"
                            >
                              <Icon.collapse />
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>Minimize chat</TooltipContent>
                        </Tooltip>
                      )}
                      {!panel && (
                        <Tooltip>
                          <TooltipTrigger asChild>
                            <Button
                              aria-label="Open full conversation"
                              data-workshop-view-toggle
                              onClick={() => {
                                setPanel(true);
                                setExpanded(true);
                              }}
                              size="icon-xs"
                              type="button"
                              variant="ghost"
                            >
                              <Icon.expand />
                            </Button>
                          </TooltipTrigger>
                          <TooltipContent>Open conversation</TooltipContent>
                        </Tooltip>
                      )}
                    </div>
                  </ComposerPrimitive.Root>
                </PromptInput>
              </div>
            )}
            {panel && !fullScreen && (
              <WorkshopPanelResize
                onResizingChange={setResizing}
                onWidthChange={setPanelWidth}
                panelId={panelId}
                width={panelWidth}
              />
            )}
          </Card>
        </ThreadPrimitive.Root>
      </WorkspaceChatDraft.Provider>
    </AssistantRuntimeProvider>
  );
}