Skip to content

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

28.6 KB
Raw Blame
import { BookOpen, FolderOpen, Trash2, Users } from "lucide-react";
import { t } from "@/lib/i18n";
import { relayLink } from "@/lib/relay-server";
import { skillImportLines } from "@/lib/skill-import";
import type { SkillFolderProblem, SkillImportSummary } from "../../../shared/skill-import";
import type { LocaleKey } from "@/locales";
import { useEffect, useRef, useState } from "react";

import { type Bot } from "@/state/store";
import { useBotEditor } from "./BotEditorContext";
import { skillAuthoringEnabled, skillsLibraryEnabled } from "@/lib/feature-flags";
import { Switch } from "../SettingsPrimitives";
import { inputCls } from "./field";
import { OrgSkillsCard } from "./OrgSkillsCard";
import { WriteCommandCard } from "./WriteCommandCard";
import { Select } from "../Select";
import { sameFields, useStoreSelector } from "@/state/store-select";

export interface ManagedSkill {
  name: string;
  description: string;
  enabled: boolean;
  source: string;
  warnings: string[];
  /** "imported": one copy brought in from this computer for every bot, switched per bot and removable from one bot.
   * "native": loaded by the bot's engine from a skills folder of its own; changed only there.
   * "project": shipped in the folder the bot works in; used while the owner trusts project skills, changed only there. */
  origin?: "private" | "library" | "all-bots" | "imported" | "native" | "project";
  /** On all of the person's bots, a bot made later too; the switch is this bot's own. */
  allBots?: boolean;
  canUseOnAllBots?: boolean;
  /** An imported skill that is on but not in this bot's list: the bot finds it when a task needs it. */
  listed?: boolean;
  /** An imported copy whose source folder is gone: removing it clears OpenMausBot's copy for every bot. */
  sourceGone?: boolean;
}

/** On all of the person's bots, with this bot's own switch. */
export const onAllBots = (skill: ManagedSkill): boolean => skill.allBots === true;

/** One of this bot's own skills, on, that this person may put on all of their bots (the server says so per skill). */
export const canUseOnAllBots = (skill: ManagedSkill): boolean => skill.canUseOnAllBots === true;

/** A skill that lives in a folder of the person's, read only here. */
const inFolder = (skill: ManagedSkill): boolean => skill.origin === "native" || skill.origin === "project";

/** A skill's switch: on whenever the skill is on, including an imported one the bot finds only when a task needs it,
 * so one click always turns it fully off. */
export const skillSwitchOn = (skill: ManagedSkill): boolean => skill.enabled;

interface LibraryPoolSkill {
  name: string;
  description: string;
}

interface StagedSkillSummary {
  id: string;
  name: string;
  gist: string;
}

export function useManagedSkills(bot: Bot) {
  const { request: api } = useBotEditor();
  const [skills, setSkills] = useState<ManagedSkill[]>([]);
  const [assignedSkills, setAssignedSkills] = useState<string[]>([]);
  const [libraryPool, setLibraryPool] = useState<LibraryPoolSkill[]>([]);
  const [addFromLibrary, setAddFromLibrary] = useState("");
  const [staged, setStaged] = useState<StagedSkillSummary[]>([]);
  const [loading, setLoading] = useState(true);
  const [working, setWorking] = useState("");
  const [error, setError] = useState("");
  const [reviewing, setReviewing] = useState<{ skill: ManagedSkill; text: string } | null>(null);
  const assignmentBusy = useRef(false);
  /** What the last "use on all bots" left to say: bots that keep a different copy of their own. */
  const [note, setNote] = useState("");

  const refresh = async (cancelled?: () => boolean) => {
    try {
      const result = (await api(`/api/bots/${bot.id}/skills`)) as {
        skills?: ManagedSkill[];
        staged?: StagedSkillSummary[];
        library?: LibraryPoolSkill[];
        assignedSkills?: string[];
      };
      if (cancelled?.()) return;
      setSkills(result.skills ?? []);
      setStaged(result.staged ?? []);
      setLibraryPool(result.library ?? []);
      setAssignedSkills(result.assignedSkills ?? []);
      setAddFromLibrary("");
      setError("");
    } catch (cause) {
      if (!cancelled?.()) setError(cause instanceof Error ? cause.message : t("skills.error.loadLearned"));
    } finally {
      if (!cancelled?.()) setLoading(false);
    }
  };

  useEffect(() => {
    let cancelled = false;
    setLoading(true);
    setReviewing(null);
    void refresh(() => cancelled);
    return () => {
      cancelled = true;
    };
  }, [bot.id]);

  const putAssignments = async (name: string, remove = false) => {
    const listing = (await api(`/api/bots/${bot.id}/skills`)) as { assignedSkills?: string[] };
    const current = listing.assignedSkills ?? assignedSkills;
    const next = remove ? current.filter((skill) => skill !== name) : [...new Set([...current, name])];
    await api(`/api/bots/${bot.id}/skills-library`, {
      method: "PUT",
      body: JSON.stringify({ skills: next }),
    });
    await refresh();
  };

  const addToBot = async () => {
    const name = addFromLibrary.trim();
    if (!name || assignmentBusy.current) return;
    assignmentBusy.current = true;
    setWorking(name);
    setError("");
    try {
      await putAssignments(name);
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("skills.error.assign"));
    } finally {
      assignmentBusy.current = false;
      setWorking("");
    }
  };

  const toggle = async (skill: ManagedSkill) => {
    setWorking(skill.name);
    setError("");
    try {
      // Native skills live in the engine's own folders, and one on all the person's bots is switched here for this bot
      // only: the switch only affects this bot.
      if (skill.origin === "native" || skill.allBots) {
        await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}`, {
          method: "PATCH",
          body: JSON.stringify({ enabled: !skill.enabled }),
        });
        await refresh();
        return;
      }
      if (skill.origin === "library" && skill.enabled) {
        await api(`/api/skills-library/${encodeURIComponent(skill.name)}`, {
          method: "PATCH",
          body: JSON.stringify({ enabled: !skill.enabled }),
        });
        await refresh();
        return;
      }
      if (!skill.enabled) {
        // Security: a disabled import has not necessarily been reviewed; its integrity-checked bytes need one explicit
        // review before they reach the prompt.
        const result = (await api(skill.origin === "library" ? `/api/skills-library/${encodeURIComponent(skill.name)}` : `/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}`)) as { text?: string };
        if (!result.text) throw new Error(t("skills.error.contentsRelearn"));
        setReviewing({ skill, text: result.text });
        return;
      }
      await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}`, {
        method: "PATCH",
        body: JSON.stringify({ enabled: false }),
      });
      await refresh();
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("skills.error.update"));
    } finally {
      setWorking("");
    }
  };

  const enableReviewed = async () => {
    if (!reviewing) return;
    const { skill } = reviewing;
    setWorking(skill.name);
    setError("");
    try {
      await api(skill.origin === "library" ? `/api/skills-library/${encodeURIComponent(skill.name)}` : `/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}`, {
        method: "PATCH",
        body: JSON.stringify({ enabled: true }),
      });
      setReviewing(null);
      await refresh();
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("skills.error.enable"));
    } finally {
      setWorking("");
    }
  };

  /** Puts one of this bot's own skills on all of the person's bots; a bot with a different copy of its own keeps it. */
  const putOnAllBots = async (skill: ManagedSkill) => {
    setWorking(skill.name);
    setError("");
    setNote("");
    try {
      const result = (await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}/all-bots`, { method: "POST" })) as { kept?: string[] };
      if (result.kept?.length) setNote(t("skills.allBots.kept", { names: result.kept.join(", ") }));
      await refresh();
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("skills.allBots.failed"));
    } finally {
      setWorking("");
    }
  };

  return {
    skills, staged, loading, working, setWorking, error, setError, note, reviewing, setReviewing, refresh, toggle, enableReviewed, putOnAllBots,
    libraryPool, addFromLibrary, setAddFromLibrary, assignmentBusy, putAssignments, addToBot,
  };
}

export function SkillReviewDialog({
  skill,
  text,
  error,
  working,
  onCancel,
  onEnable,
}: {
  skill: ManagedSkill;
  text: string;
  error: string;
  working: boolean;
  onCancel: () => void;
  onEnable: () => void;
}) {
  const dialogRef = useRef<HTMLDivElement>(null);
  const cancel = useRef(onCancel);
  cancel.current = onCancel;

  useEffect(() => {
    const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    const dialog = dialogRef.current;
    const parentDialog = dialog?.parentElement?.closest<HTMLElement>('[role="dialog"]');
    dialog?.focus();
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        if (!working) cancel.current();
      }
      if (event.key !== "Tab" || !dialog) return;
      const controls = dialog.querySelectorAll<HTMLElement>('button:not([disabled]), [tabindex="0"]');
      const first = controls[0];
      const last = controls[controls.length - 1];
      if (!first || !last) return;
      if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog)) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      if (previousFocus && previousFocus !== document.body && previousFocus.isConnected) previousFocus.focus();
      else parentDialog?.focus();
    };
  }, [working]);

  return (
    <div
      ref={dialogRef}
      tabIndex={-1}
      role="dialog"
      aria-modal="true"
      aria-labelledby="skill-review-title"
      className="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-6"
    >
      <div className="flex max-h-[min(760px,90vh)] w-full max-w-2xl flex-col rounded-2xl bg-card p-5 shadow-2xl">
        <div id="skill-review-title" className="text-[16px] font-semibold text-ink">
          {t("skills.reviewTitle", { name: skill.name })}
        </div>
        <div className="mt-1 break-all text-[12px] text-ink-secondary">
          {t("skills.source", { source: skill.source })}
        </div>
        {skill.warnings.length > 0 && (
          <div className="mt-2 rounded-lg bg-warning/10 px-3 py-2 text-[12px] text-warning">
            {skill.warnings.join(" · ")}
          </div>
        )}
        <pre
          tabIndex={0}
          aria-label={t("skills.fullSkill", { name: skill.name })}
          className="mt-3 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-inset p-3 font-mono text-[12px] leading-relaxed text-ink"
        >
          {text}
        </pre>
        {error && <div role="alert" className="mt-2 text-[12px] text-danger">{error}</div>}
        <div className="mt-4 flex justify-end gap-2">
          <button
            type="button"
            disabled={working}
            onClick={onCancel}
            className="rounded-lg px-4 py-2 text-[13px] font-medium text-ink-secondary hover:bg-raised disabled:opacity-40"
          >
            {t("common.cancel")}
          </button>
          <button
            type="button"
            disabled={working}
            onClick={onEnable}
            className="rounded-lg bg-accent px-4 py-2 text-[13px] font-semibold text-white disabled:opacity-40"
          >
            {t("skills.enableReviewed")}
          </button>
        </div>
      </div>
    </div>
  );
}

const SKILL_FOLDER_PROBLEM: Record<SkillFolderProblem, LocaleKey> = {
  missing: "skills.import.folder.missing",
  "too-large": "skills.import.folder.tooLarge",
  "too-many": "skills.import.folder.tooMany",
  unreadable: "skills.import.folder.unreadable",
};

export function useSkillImport(botId: string, { refresh, setError }: Pick<ReturnType<typeof useManagedSkills>, "refresh" | "setError">, failure: string) {
  const { request: api, draft } = useBotEditor();
  const bridge = globalThis.window?.ogb;
  const pick = draft || bridge?.remoteClient?.active || relayLink() ? undefined : bridge?.pickSkillFolder;
  const [source, setSource] = useState("");
  const [importing, setImporting] = useState<"url" | "folder" | null>(null);
  const [imported, setImported] = useState<string[] | null>(null);

  const selection = useRef(botId);
  useEffect(() => {
    selection.current = botId;
    setImporting(null);
    setImported(null);
    setSource("");
    return () => { selection.current = ""; };
  }, [botId]);
  const submit = async (from: "url" | "folder") => {
    const trimmed = source.trim();
    if (importing || (from === "folder" ? !pick : !trimmed)) return;
    setImporting(from);
    try {
      const picked = from === "folder" ? await pick?.() : null;
      if (selection.current !== botId || (from === "folder" && !picked)) return;
      setError("");
      setImported(null);
      if (picked && "error" in picked) throw new Error(t(SKILL_FOLDER_PROBLEM[picked.error] ?? "skills.import.folder.unreadable"));
      if (picked && relayLink()) throw new Error(failure);
      const result = await api<{ imported?: SkillImportSummary[] }>(`/api/bots/${botId}/skills${picked ? "?from=folder" : ""}`, {
        method: "POST",
        ...(picked ? { redirect: "error" } : {}),
        body: JSON.stringify(picked ? { files: picked.files } : { source: trimmed }),
      });
      if (selection.current !== botId) return;
      const summaries = result.imported ?? [];
      setImported(skillImportLines(picked ? summaries.map((summary) => ({
        ...summary,
        skipped: [...picked.skipped, ...summary.skipped],
        skippedCount: picked.skippedCount + summary.skippedCount,
      })) : summaries));
      if (!picked) setSource("");
      await refresh(() => selection.current !== botId);
    } catch (cause) {
      if (selection.current === botId) setError(cause instanceof Error && cause.message ? cause.message : failure);
    } finally {
      if (selection.current === botId) setImporting(null);
    }
  };

  return { source, setSource, importing, imported, submit, canPick: Boolean(pick) };
}

export function SkillsSection({ bot }: { bot: Bot }) {
  const { request: api } = useBotEditor();
  const state = useStoreSelector((s) => ({ config: s.config }), sameFields);
  const featureEnabled = skillAuthoringEnabled(state.config);
  const libraryOn = skillsLibraryEnabled(state.config);
  const {
    skills, staged, loading, working, setWorking, error, setError, note, reviewing, setReviewing, refresh, toggle, enableReviewed, putOnAllBots,
    libraryPool, addFromLibrary, setAddFromLibrary, assignmentBusy, addToBot,
  } = useManagedSkills(bot);
  const [viewing, setViewing] = useState<{ name: string; text: string } | null>(null);
  const { source, setSource, importing, imported, submit, canPick } = useSkillImport(bot.id, { refresh, setError }, t("skills.error.import"));
  const skillDialogRef = useRef<HTMLDivElement>(null);
  const skillDialogOpen = Boolean(viewing);

  useEffect(() => {
    if (!skillDialogOpen) return;
    const previousFocus = document.activeElement instanceof HTMLElement ? document.activeElement : null;
    const dialog = skillDialogRef.current;
    const parentDialog = dialog?.parentElement?.closest<HTMLElement>('[role="dialog"]');
    dialog?.focus();
    const onKey = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        event.preventDefault();
        if (!working) setViewing(null);
      }
      if (event.key !== "Tab" || !dialog) return;
      const controls = dialog.querySelectorAll<HTMLElement>('button:not([disabled]), [tabindex="0"]');
      const first = controls[0];
      const last = controls[controls.length - 1];
      if (!first || !last) return;
      if (event.shiftKey && (document.activeElement === first || document.activeElement === dialog)) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      if (previousFocus && previousFocus !== document.body && previousFocus.isConnected) previousFocus.focus();
      else parentDialog?.focus();
    };
  }, [skillDialogOpen, working]);

  useEffect(() => {
    setViewing(null);
  }, [bot.id]);

  const remove = async (skill: ManagedSkill) => {
    if (skill.origin === "imported") {
      const stale = skill.sourceGone === true;
      if (!window.confirm(t(stale ? "skills.imported.removeStaleConfirm" : "skills.imported.removeConfirm", { name: skill.name }))) return;
      setWorking(skill.name);
      setError("");
      try {
        await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}${stale ? "?scope=all-bots" : ""}`, { method: "DELETE" });
        await refresh();
      } catch (cause) {
        setError(cause instanceof Error ? cause.message : t("skills.error.remove"));
      } finally {
        setWorking("");
      }
      return;
    }
    if (skill.origin === "library") {
      if (assignmentBusy.current) return;
      if (!window.confirm(t("skills.unassignConfirm", { name: skill.name }))) return;
      assignmentBusy.current = true;
      setWorking(skill.name);
      setError("");
      try {
        await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}`, { method: "DELETE" });
        await refresh();
      } catch (cause) {
        setError(cause instanceof Error ? cause.message : t("skills.error.unassign"));
      } finally {
        assignmentBusy.current = false;
        setWorking("");
      }
      return;
    }
    if (!window.confirm(t(skill.allBots ? "skills.allBots.removeConfirm" : "skills.removeLearnedConfirm", { name: skill.name }))) return;
    setWorking(skill.name);
    setError("");
    try {
      await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}${skill.allBots ? "/all-bots" : ""}`, { method: "DELETE" });
      await refresh();
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("skills.error.remove"));
    } finally {
      setWorking("");
    }
  };

  const view = async (skill: ManagedSkill) => {
    setError("");
    try {
      const result = skill.origin === "library"
        ? ((await api(`/api/skills-library/${encodeURIComponent(skill.name)}`)) as { text?: string })
        : ((await api(`/api/bots/${bot.id}/skills/${encodeURIComponent(skill.name)}`)) as { text?: string });
      setViewing({ name: skill.name, text: result.text ?? "" });
    } catch (cause) {
      setError(cause instanceof Error ? cause.message : t("skills.error.load"));
    }
  };

  return (
    <div className="flex flex-col gap-4">
      <div className="rounded-xl bg-card p-4">
        <div className="flex items-center gap-2">
          <BookOpen size={16} className="text-ink-secondary" />
          <div className="text-[15px] font-medium text-ink">{t("skills.learned.title")}</div>
        </div>
        <div className="mt-1 text-[12px] leading-relaxed text-ink-secondary">
          {featureEnabled ? t("skills.learned.hintOn") : t("skills.learned.hintOff")}
        </div>

        {libraryOn ? (
          <div className="mt-3 flex flex-col gap-1.5">
            {libraryPool.length > 0 ? (
              <div className="flex items-center gap-2">
                <Select size="lg" className="flex-1"
                  aria-label={t("skills.library.addLabel")}
                  value={addFromLibrary}
                  disabled={Boolean(working)}
                  onChange={(e) => setAddFromLibrary(e.target.value)}
                >
                  <option value="">{t("skills.library.addPlaceholder")}</option>
                  {libraryPool.map((skill) => (
                    <option key={skill.name} value={skill.name}>{skill.name}</option>
                  ))}
                </Select>
                <button
                  type="button"
                  disabled={!addFromLibrary || Boolean(working)}
                  onClick={() => void addToBot()}
                  className="shrink-0 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50"
                >
                  {t("common.add")}
                </button>
              </div>
            ) : (
              <div className="text-[12px] text-ink-secondary">{t("skills.library.allAssigned")}</div>
            )}
            <div className="text-[12px] text-ink-secondary">{t("skills.library.manageHint")}</div>
          </div>
        ) : (
          <form
            className="mt-3 flex items-center gap-2"
            onSubmit={(e) => {
              e.preventDefault();
              void submit("url");
            }}
          >
            <input
              className={inputCls}
              placeholder={t("skills.import.placeholder")}
              aria-label={t("skills.import.label")}
              value={source}
              onChange={(e) => setSource(e.target.value)}
            />
            <button
              type="submit"
              disabled={Boolean(importing) || !source.trim()}
              className="shrink-0 rounded-lg bg-control px-3 py-2 text-[13px] text-ink hover:bg-raised-hover disabled:opacity-50"
            >
              {t(importing === "url" ? "skills.import.importing" : "skills.import.button")}
            </button>
          </form>
        )}
        {canPick && (
          <button type="button" className="ui-button ui-button-md mt-2" disabled={Boolean(importing)} onClick={() => void submit("folder")}>
            <FolderOpen size={14} aria-hidden="true" />{t(importing === "folder" ? "skills.import.importing" : "templateImport.chooseFolder")}
          </button>
        )}
        {imported && <div role="status" className="mt-1 text-[12px] text-ink-secondary">{[...imported, t("skills.import.reviewBelow")].join(" ")}</div>}

        {loading ? (
          <div className="mt-3 text-[12px] text-ink-secondary">{t("skills.loading")}</div>
        ) : skills.length === 0 ? (
          <div className="mt-3 rounded-lg bg-inset px-3 py-2 text-[12px] text-ink-secondary">{t("skills.empty")}</div>
        ) : (
          <div className="mt-3 divide-y divide-hairline/40 overflow-hidden rounded-lg border border-hairline/40">
            {skills.map((skill) => (
              <div key={skill.name} className="px-3 py-2.5">
                <div className="flex items-center gap-2">
                  <button
                    type="button"
                    onClick={() => void view(skill)}
                    className="min-w-0 flex-1 text-left"
                  >
                    <div className="truncate font-mono text-[13px] text-ink">{skill.name}</div>
                    {(libraryOn || onAllBots(skill) || skill.origin === "imported" || inFolder(skill)) && (
                      <span
                        className="ml-1.5 rounded bg-control px-1 py-px font-mono text-[10px] uppercase tracking-wide text-ink-secondary"
                        title={onAllBots(skill) ? t("skills.allBots.tagHint") : skill.origin === "imported" ? t("skills.origin.importedHint") : skill.origin === "native" ? t("skills.origin.nativeHint") : skill.origin === "project" ? t("skills.origin.projectHint") : undefined}
                      >
                        {onAllBots(skill) ? t("skills.allBots.tag") : skill.origin === "imported" ? t("skills.origin.imported") : skill.origin === "native" ? t("skills.origin.native") : skill.origin === "project" ? t("skills.origin.project") : skill.origin === "library" ? t("skills.origin.library") : t("skills.origin.private")}
                      </span>
                    )}
                    <div className="mt-0.5 line-clamp-2 text-[12px] text-ink-secondary">{skill.description}</div>
                    <div className="mt-0.5 text-[11px] text-ink-secondary">{t(skill.enabled && skill.listed === false ? "skills.foundWhenNeeded" : "skills.usedWhenRelevant")}</div>
                  </button>
                  {skill.origin !== "project" && (
                    <Switch
                      checked={skillSwitchOn(skill)}
                      aria-label={t(skillSwitchOn(skill) ? "skills.disableName" : "skills.enableName", { name: skill.name })}
                      disabled={Boolean(working)}
                      onClick={() => void toggle(skill)}
                    />
                  )}
                  {canUseOnAllBots(skill) && (
                    <button
                      type="button"
                      aria-label={t("skills.allBots.useName", { name: skill.name })}
                      title={t("skills.allBots.use")}
                      disabled={Boolean(working)}
                      onClick={() => void putOnAllBots(skill)}
                      className="flex size-8 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-control hover:text-ink disabled:opacity-40"
                    >
                      <Users size={15} />
                    </button>
                  )}
                  {!inFolder(skill) && (
                    <button
                      aria-label={t("skills.removeName", { name: skill.name })}
                      title={t("skills.remove")}
                      disabled={Boolean(working)}
                      onClick={() => void remove(skill)}
                      className="flex size-8 shrink-0 items-center justify-center rounded-md text-ink-secondary hover:bg-danger/10 hover:text-danger disabled:opacity-40"
                    >
                      <Trash2 size={15} />
                    </button>
                  )}
                </div>
                <div className="mt-1 truncate text-[11px] text-ink-secondary" title={skill.source}>{t("skills.source", { source: skill.source })}</div>
                {skill.sourceGone && <div className="mt-1 text-[11px] text-ink-secondary">{t("skills.imported.sourceGone")}</div>}
                {skill.warnings.length > 0 && (
                  <div className="mt-1 text-[11px] text-warning">{skill.warnings.join(" · ")}</div>
                )}
              </div>
            ))}
          </div>
        )}
        {staged.length > 0 && (
          <div className="mt-2 text-[12px] text-warning">
            {staged.length === 1 ? t("skills.stagedOne") : t("skills.stagedMany", { count: staged.length })}
          </div>
        )}
        {note && <div className="mt-2 text-[12px] text-ink-secondary">{note}</div>}
        {error && <div role="alert" className="mt-2 text-[12px] text-danger">{error}</div>}
      </div>

      <WriteCommandCard bot={bot} taken={skills.map((skill) => skill.name)} onSaved={() => void refresh()} />

      <OrgSkillsCard bot={bot} onAdded={() => void refresh()} />

      {reviewing && (
        <SkillReviewDialog
          skill={reviewing.skill}
          text={reviewing.text}
          error={error}
          working={working === reviewing.skill.name}
          onCancel={() => setReviewing(null)}
          onEnable={() => void enableReviewed()}
        />
      )}

      {viewing && (
        <div
          ref={skillDialogRef}
          tabIndex={-1}
          role="dialog"
          aria-modal="true"
          aria-labelledby="skill-view-title"
          className="fixed inset-0 z-[90] flex items-center justify-center bg-black/45 p-6"
        >
          <div className="flex max-h-[min(760px,90vh)] w-full max-w-2xl flex-col rounded-2xl bg-card p-5 shadow-2xl">
            <div className="flex items-center justify-between gap-3">
              <div id="skill-view-title" className="text-[16px] font-semibold text-ink">{viewing.name}</div>
              <button
                type="button"
                onClick={() => setViewing(null)}
                className="rounded-md px-2 py-1 text-[13px] text-ink-secondary hover:bg-control hover:text-ink"
              >
                {t("common.close")}
              </button>
            </div>
            <pre
              tabIndex={0}
              aria-label={t("skills.fullSkill", { name: viewing.name })}
              className="mt-3 min-h-0 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-xl bg-inset p-3 font-mono text-[12px] leading-relaxed text-ink"
            >
              {viewing.text}
            </pre>
          </div>
        </div>
      )}
    </div>
  );
}