Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

8.1 KB
Raw Blame
import { useEffect, useId, useRef, useState, type ReactNode, type TextareaHTMLAttributes } from "react";
import { useStoreActions } from "@/state/store-select";

import { BOT_PROFILE_LIMITS } from "../../shared/bot-profile";
import { cn } from "@/lib/cn";
import { firstSentence, soulPatchFor, utf8Bytes } from "@/lib/soul";
import { type Bot } from "@/state/store";
import { useModalDialog } from "@/hooks/use-modal-dialog";
import { useAdvancedMode } from "@/lib/interface-mode";
import { Layer } from "./Layer";
import { useBotEditor } from "./bot-settings/BotEditorContext";
import { inputCls } from "./bot-settings/field";
import { intlLocale, t } from "@/lib/i18n";

type SoulRead = { soul: string; revision: string; bytes: number; limit: number; file: string; drift: boolean; fileText?: string };

export function SoulField({
  bot,
  onPatch,
  simple,
}: {
  bot: Bot;
  onPatch: (patch: { soul?: string; description?: string }) => void;
  simple?: { label: string; placeholder: string };
}) {
  const { dispatch, flushBotPatches } = useStoreActions();
  const { request: api } = useBotEditor();
  const limit = BOT_PROFILE_LIMITS.soul;
  const [draft, setDraft] = useState(bot.soul ?? "");
  const [info, setInfo] = useState<SoulRead | null>(null);
  const [resolving, setResolving] = useState(false);
  const [large, setLarge] = useState(false);
  const advanced = useAdvancedMode();
  const largeTitleId = useId();
  const largeCountId = useId();

  useEffect(() => {
    setDraft(bot.soul ?? "");
  }, [bot.id, bot.soul]);

  // Must not key off bot.soul: onPatch updates it on every keystroke, which would refetch per keystroke.
  const refresh = () => {
    return flushBotPatches(bot.id)
      .then(() => api(`/api/bots/${bot.id}/soul`))
      .then((read: SoulRead) => setInfo(read))
      .catch(() => setInfo(null));
  };
  useEffect(() => { void refresh(); }, [bot.id, bot.soulDrift, flushBotPatches]);

  const bytes = utf8Bytes(draft);
  const over = bytes > limit;
  const change = (value: string) => {
    setDraft(value);
    const patch = soulPatchFor(value, limit);
    if (patch) onPatch(patch);
  };
  const resolve = async (action: "apply-file" | "discard-file") => {
    if (resolving || !info?.revision || typeof info.fileText !== "string") return;
    setResolving(true);
    try {
      await flushBotPatches(bot.id);
      await api(`/api/bots/${bot.id}/soul/${action}`, {
        method: "POST",
        body: JSON.stringify({ fileText: info.fileText, expectedRevision: info.revision }),
      });
    } catch (error: unknown) {
      dispatch({ type: "error", message: error instanceof Error ? error.message : String(error) });
    } finally {
      await refresh();
      setResolving(false);
    }
  };
  const canMigrate = bot.description.length > 400 && !(bot.soul ?? "").trim();
  const label = simple ? simple.label : t("botIdentity.soul.label");
  const editor = (className: string, attrs: TextareaHTMLAttributes<HTMLTextAreaElement>) => (
    <textarea
      {...attrs}
      dir="auto"
      className={cn(inputCls, className, over && "ring-2 ring-danger/60")}
      placeholder={simple ? simple.placeholder : t("bot.soul.placeholder")}
      aria-invalid={over || undefined}
      disabled={resolving}
      value={draft}
      onChange={(e) => change(e.target.value)}
    />
  );
  const byteCount = (id?: string) => (
    <span id={id} className={cn("shrink-0 tabular-nums", over && "font-medium text-danger")}>
      {t(over ? "botIdentity.soul.bytesOver" : "botIdentity.soul.bytes", { bytes: bytes.toLocaleString(intlLocale()), limit: limit.toLocaleString(intlLocale()) })}
    </span>
  );

  return (
    <div className="block">
      <div className="mb-1.5 flex items-center justify-between gap-3">
        <label htmlFor={`bot-soul-${bot.id}`} className={simple ? "text-[12px] text-ink-secondary" : "text-[13px] text-ink-secondary"}>
          {label}
        </label>
        <div className="flex items-center gap-1">
          {!simple && canMigrate && (
            <button
              type="button"
              disabled={resolving}
              onClick={() => onPatch({ soul: bot.description, description: firstSentence(bot.description) })}
              className={HEADER_BUTTON}
            >
              {t("botIdentity.soul.moveToFile")}
            </button>
          )}
          {advanced && (
            <button type="button" disabled={resolving} onClick={() => setLarge(true)} className={HEADER_BUTTON}>
              {t("botIdentity.soul.openLarge")}
            </button>
          )}
        </div>
      </div>
      {info?.drift && (
        <div className="mb-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-[12px] text-ink">
          <div className="font-medium">{t("botIdentity.soul.externalEdit")}</div>
          <div className="mt-1 text-ink-secondary">
            {t("botIdentity.soul.externalEditHelp")} {t("botIdentity.soul.fileLabel")} <span className="break-all">{info.file}</span>
          </div>
          <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap rounded bg-control p-2 text-[12px]">{info.fileText}</pre>
          <div className="mt-2 flex gap-2">
            <button type="button" disabled={resolving} onClick={() => void resolve("apply-file")} className="rounded-lg bg-accent px-3 py-1.5 text-[12px] font-medium text-white hover:brightness-110 disabled:opacity-50">
              {t("botIdentity.soul.useFile")}
            </button>
            <button type="button" disabled={resolving} onClick={() => void resolve("discard-file")} className="rounded-lg bg-control px-3 py-1.5 text-[12px] text-ink hover:bg-raised-hover disabled:opacity-50">
              {t("botIdentity.soul.keepSaved")}
            </button>
          </div>
        </div>
      )}
      {editor(simple ? "min-h-[140px] resize-y rounded-xl text-[14px] leading-relaxed" : "min-h-[220px] resize-y font-mono leading-relaxed", { id: `bot-soul-${bot.id}` })}
      {(!simple || over) && <div className="mt-1.5 flex items-start justify-between gap-3 text-[11px] text-ink-secondary">
        <span>
          {!simple && <>{t("botIdentity.soul.contextHelp")}{info?.file ? <> {t("botIdentity.soul.mirroredTo")} <span className="break-all">{info.file}</span>.</> : null}</>}
        </span>
        {byteCount()}
      </div>}
      {advanced && large && (
        <Layer modal>
          <SoulLargeDialog titleId={largeTitleId} title={label} byteCount={byteCount(largeCountId)} onClose={() => setLarge(false)}>
            {editor(
              cn("min-h-0 flex-1 resize-none leading-relaxed", simple ? "rounded-xl text-[14px]" : "font-mono"),
              { "aria-labelledby": largeTitleId, "aria-describedby": largeCountId },
            )}
          </SoulLargeDialog>
        </Layer>
      )}
    </div>
  );
}

const HEADER_BUTTON = "rounded-md px-1.5 py-1 text-[12px] font-medium text-accent-text enabled:hover:bg-ink/[0.06] disabled:opacity-50";

function SoulLargeDialog({ titleId, title, byteCount, onClose, children }: {
  titleId: string;
  title: string;
  byteCount: ReactNode;
  onClose: () => void;
  children: ReactNode;
}) {
  const dialogRef = useRef<HTMLDivElement>(null);
  useModalDialog(dialogRef, onClose);
  useEffect(() => { dialogRef.current?.querySelector("textarea")?.focus(); }, []);
  return (
    <div className="ui-scrim fixed inset-0 z-[90] flex items-center justify-center p-4" onMouseDown={(event) => { if (event.target === event.currentTarget) onClose(); }}>
      <div
        ref={dialogRef}
        tabIndex={-1}
        role="dialog"
        aria-modal="true"
        aria-labelledby={titleId}
        className="ui-modal animate-pop-in flex h-[min(760px,100%)] w-full max-w-3xl flex-col text-ink outline-none motion-reduce:animate-none"
      >
        <h2 id={titleId} className="min-w-0 truncate px-5 pb-3 pt-4 text-[20px] font-semibold tracking-[-0.01em]">{title}</h2>
        <div className="flex min-h-0 flex-1 flex-col px-5">{children}</div>
        <footer className="flex items-center justify-between gap-3 px-5 pb-4 pt-3 text-[12px] text-ink-secondary">
          {byteCount}
          <button type="button" onClick={onClose} className="ui-button ui-button-md">{t("common.done")}</button>
        </footer>
      </div>
    </div>
  );
}