Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

47.0 KB
Raw Blame
/**
 * Agent settings page "Memory" tab: the switch, then every memory the Agent keeps, grouped by
 * scope — user memory first (read by every Session), then one group per Workspace (labeled by
 * its `.workspace` path, newest activity first).
 *
 * A memory's content is the model's document, so per-file editing stays out of the tab: both
 * "edit" and each scope header's "add" open a bridge modal first — a text field and a live
 * preview of the generated prompt, the same shape as the skill import modal — and then jump to
 * a new chat with this Agent and the prompt as the prefilled draft (the same draft-cache
 * route). For a Workspace scope the draft also pins that Workspace, so the Session is injected
 * with the very index it is about to change. Deleting confirms first and also drops the file's
 * MEMORY.md index lines (server-side).
 *
 * A whole group moves in one piece, though: each header carries export and import, following
 * the Agent State snapshot's split — any member may download a group, only the owner may write
 * one back. Import defaults to the mode that loses nothing, and the two that do not are held
 * behind a confirmation naming the memories at stake.
 *
 * The switch writes immediately rather than joining a tab-level Save, so turning Memory off
 * never drags an unrelated half-finished edit along with it. Off keeps every file and this tab
 * fully usable; it only stops Memory from entering the context and from preparing directories
 * for new Sessions.
 */
import { useCallback, useEffect, useRef, useState } from "react";
import type { ChangeEvent, RefObject } from "react";
import type {
  MemoryFileInfo,
  MemoryImportMode,
  MemoryScopeExport,
  MemoryScopeInfo,
} from "@adelie/server/api";
import {
  Button,
  Card,
  CollapsibleSection,
  ConfirmModal,
  CopiedStatus,
  CopyCheckGlyph,
  DownloadIcon,
  Drawer,
  GlyphIcon,
  HelpFold,
  HiddenFileInput,
  ICONS,
  IconButton,
  InfoPopover,
  ListRow,
  Md,
  Modal,
  Notice,
  RadioGroup,
  Sheet,
  SkeletonList,
  Textarea,
  ToggleRow,
  UploadIcon,
  bodyWithoutFrontmatter,
  buttonClass,
  toastSuccess,
  useCopied,
} from "@adelie/ui";
import type { SheetSnap } from "@adelie/ui";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText, refusalText } from "../../lib/api-error";
import { toneInk } from "../../lib/tone";
import { formatRelativeDate } from "../../lib/format";
import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { useProject } from "../../state/project";
import { featureSwitchRefused } from "./feature-switch-refusal";
import { placeholderInsertRefused } from "./placeholder-insert-refusal";
import { useSaveConfirm } from "./save-confirm";
import { useAiBridge } from "../ai-create";
import { buildMemoryAddPrompt, buildMemoryEditPrompt } from "./memory-chat-prompts";
import { memoryFileRefusalFor, memoryViewRefused } from "./memory-file-refusal";
import type { MemoryFileRefusal } from "./memory-file-refusal";
import {
  memoryExportRefused,
  memoryGroupRefusalFor,
  memoryImportRefused,
} from "./memory-group-refusal";
import type { MemoryGroupRefusal } from "./memory-group-refusal";
import {
  memoryDocumentFileName,
  parseMemoryScopeDocument,
  planMemoryImport,
} from "./memory-transfer";
import type { MemoryImportPlan } from "./memory-transfer";

/** Same breakpoint as the chat page's panels: \u22651024px the view opens as a side Drawer, below it as a bottom Sheet. */
const DESKTOP_QUERY = "(min-width: 1024px)";

/**
 * The small ghost button's look on a `<label>`: the Button component only renders a `<button>`,
 * and the import control has to wrap a file input (the Agent State section's transfer label does
 * the same for its own size). Mirrors Button's `ghost` variant at `sm`, icon + text.
 */
const GHOST_LABEL_CLASS = buttonClass("ghost", "sm");

/**
 * Collapsed scope keys, persisted per user \u00d7 Project \u00d7 Agent (localStorage, same conventions as
 * the chat draft cache: userId in the key against cross-account leaks, tolerant reads, silent
 * best-effort writes). Only collapsed keys are stored, so new scopes start expanded.
 */
const collapsedStoreKey = (userId: string, projectId: string, agentId: string): string =>
  `penguin.memoryCollapsed.${userId}.${projectId}.${agentId}`;

function readCollapsedScopes(key: string | null): Set<string> {
  if (!key) return new Set();
  try {
    const parsed: unknown = JSON.parse(localStorage.getItem(key) ?? "[]");
    if (!Array.isArray(parsed)) return new Set();
    return new Set(parsed.filter((s): s is string => typeof s === "string"));
  } catch {
    return new Set();
  }
}

function writeCollapsedScopes(key: string | null, collapsed: ReadonlySet<string>): void {
  if (!key) return;
  try {
    localStorage.setItem(key, JSON.stringify([...collapsed]));
  } catch {
    // Quota / private browsing: the collapse state just won't survive the visit.
  }
}

/** One scope group as the tab renders it: the overview entry plus its listed files. */
interface ScopeGroup {
  scope: MemoryScopeInfo;
  files: MemoryFileInfo[];
}

/** A memory selected for an action (view drawer / delete confirm). */
interface Selected {
  scope: MemoryScopeInfo;
  file: MemoryFileInfo;
}

/**
 * A group's name in the interface: user memory, or a Workspace's last path segment (its key as a
 * last resort). Module level because the export refusal names the group it was made for, and that
 * sentence is built where the attempt fails — during a render that may have returned early.
 */
const scopeTitle = (scope: MemoryScopeInfo): string =>
  scope.kind === "user"
    ? S.memory.userScope
    : (scope.workspacePath?.split(/[\\/]/).filter(Boolean).at(-1) ?? scope.scopeKey);

export function MemoryTab({
  agentId,
  onConfigChanged,
}: {
  agentId: string;
  /** Config writes happen here directly, so the settings page must refetch its own copy — otherwise a later Prompt-tab save from stale data would silently revert them (e.g. the inserted placeholder). */
  onConfigChanged?: () => void;
}) {
  const { openAiChat } = useAiBridge();
  const { locale } = useLocale();
  const userId = useAuth().user?.userId ?? null;
  const { currentProject, reloadAgents } = useProject();
  const projectId = currentProject?.projectId ?? null;
  // Import writes a whole group at once, so it follows the Agent State snapshot's owner gate;
  // the server enforces it either way, this only keeps the control out of a member's reach.
  const isOwner = currentProject?.role === "owner";

  const [enabled, setEnabled] = useState(true);
  const [templateHasMemory, setTemplateHasMemory] = useState(true);
  const [memoryDir, setMemoryDir] = useState("");
  const [groups, setGroups] = useState<ScopeGroup[] | null>(null);
  // Tab-level error is the initial load failure only: every action below keeps its refusal where it
  // asked (the slots under this one), so nothing that fails once the page is up becomes a
  // notification that dismisses itself.
  const [error, setError] = useState<string | null>(null);
  const [switchBusy, setSwitchBusy] = useState(false);
  // The server's words for a flip of the memory switch it refused, drawn under that card: the
  // switch keeps the position the server has, so this line is the only account of why.
  const [switchRefusal, setSwitchRefusal] = useState<string | null>(null);
  // The server's words for a refused placeholder write, drawn under the strip that asked: the
  // template still has no {{MEMORY}}, so the strip and its button stay and that button is the retry.
  const [insertRefusal, setInsertRefusal] = useState<string | null>(null);
  // The reason one whole-group attempt did not land, kept in the group that asked
  // (memory-group-refusal.ts): the group's head strip, the control that asked and every memory are
  // still there, so a notification that dismisses itself after six seconds is the one thing that
  // would carry that reason away. One slot for both directions — a later attempt supersedes it.
  const [groupRefusal, setGroupRefusal] = useState<MemoryGroupRefusal | null>(null);
  // The reason one memory did not open, kept in the row whose eye button asked
  // (memory-file-refusal.ts): the panel never came up, so that row is the only thing left holding
  // the read's retry — and a notification would carry the reason away after six seconds.
  const [viewRefusal, setViewRefusal] = useState<MemoryFileRefusal | null>(null);
  const collapseKey = userId && projectId ? collapsedStoreKey(userId, projectId, agentId) : null;
  const [collapsed, setCollapsed] = useState<Set<string>>(() => readCollapsedScopes(collapseKey));
  const [memoryPrompt, setMemoryPrompt] = useState("");
  const [workspacePrompt, setWorkspacePrompt] = useState("");
  const mainPromptRef = useRef<HTMLTextAreaElement>(null);
  const workspacePromptRef = useRef<HTMLTextAreaElement>(null);
  // Chip clicks steal focus, so track the last-focused prompt field instead of the current one.
  const [lastPromptField, setLastPromptField] = useState<"main" | "workspace">("main");
  const { requestSave, element: saveConfirm } = useSaveConfirm();
  // Open flag and content are separate: the Sheet animates out on close, and nulling the
  // content with it would empty the panel mid-exit. The stale content is simply kept.
  const [viewOpen, setViewOpen] = useState(false);
  const [viewing, setViewing] = useState<(Selected & { content: string }) | null>(null);
  const [editing, setEditing] = useState<Selected | null>(null);
  const [editRequirement, setEditRequirement] = useState("");
  const [adding, setAdding] = useState<MemoryScopeInfo | null>(null);
  const [addContent, setAddContent] = useState("");
  // A picked document waiting for its mode, then the plan the user is being asked to confirm.
  const [importing, setImporting] = useState<{
    scope: MemoryScopeInfo;
    fileName: string;
    doc: MemoryScopeExport;
  } | null>(null);
  const [importMode, setImportMode] = useState<MemoryImportMode>("skip");
  const [importPlan, setImportPlan] = useState<MemoryImportPlan | null>(null);
  const [importBusy, setImportBusy] = useState(false);
  // The server's words for a write it refused, drawn in the surface that asked for it: an
  // import refused from the plan confirmation appears in that card, one that needed no
  // confirmation (nothing would be lost) appears in the import modal still underneath it.
  const [importRefusal, setImportRefusal] = useState<string | null>(null);
  const [removing, setRemoving] = useState<Selected | null>(null);
  // Same for a refused delete, in the confirmation that named the memory (see confirmRemove).
  const [deleteRefusal, setDeleteRefusal] = useState<string | null>(null);
  // ≥1024px the view opens as a right Drawer, below as a bottom Sheet — same live-updating
  // breakpoint as the chat page's panels; the two are mounted mutually exclusively.
  const [isDesktop, setIsDesktop] = useState(() => window.matchMedia(DESKTOP_QUERY).matches);
  const [sheetSnap, setSheetSnap] = useState<SheetSnap>("half");

  useEffect(() => {
    const mq = window.matchMedia(DESKTOP_QUERY);
    const onChange = (e: MediaQueryListEvent) => setIsDesktop(e.matches);
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, []);

  // The collapse state follows its storage slot (login/project switches swap the key in place).
  useEffect(() => {
    setCollapsed(readCollapsedScopes(collapseKey));
  }, [collapseKey]);

  const toggleCollapsed = (scopeKey: string) => {
    const next = new Set(collapsed);
    if (!next.delete(scopeKey)) next.add(scopeKey);
    writeCollapsedScopes(collapseKey, next);
    setCollapsed(next);
  };

  const load = useCallback(async () => {
    if (!projectId || !agentId) return;
    setGroups(null);
    setError(null);
    try {
      const [overview, configView] = await Promise.all([
        api.getMemoryOverview(projectId, agentId),
        api.getAgentConfig(projectId, agentId),
      ]);
      setMemoryPrompt(configView.config.memory.prompt);
      setWorkspacePrompt(configView.config.memory.workspacePrompt);
      setEnabled(overview.enabled);
      setTemplateHasMemory(overview.templateHasMemory);
      setMemoryDir(overview.memoryDir);
      // Stored collapse keys for scopes that no longer exist are pruned on sight, so the
      // entry doesn't linger forever in localStorage.
      const live = new Set(overview.scopes.map((s) => s.scopeKey));
      setCollapsed((prev) => {
        const next = new Set([...prev].filter((k) => live.has(k)));
        if (next.size === prev.size) return prev;
        writeCollapsedScopes(collapseKey, next);
        return next;
      });
      // Files are the source of truth and each scope is one request; fetch them in parallel.
      setGroups(
        await Promise.all(
          overview.scopes.map(async (scope) => {
            try {
              return {
                scope,
                files: (await api.getMemoryFiles(projectId, agentId, scope.scopeKey)).files,
              };
            } catch {
              // One unreadable scope (bad hand-made directory name, raced delete) must not
              // blank the whole tab; it lists as an empty group instead.
              return { scope, files: [] };
            }
          }),
        ),
      );
    } catch (e) {
      setError(apiErrorText(e));
    }
  }, [projectId, agentId, collapseKey]);

  useEffect(() => {
    void load();
  }, [load]);

  const toggleEnabled = async (next: boolean) => {
    if (!projectId) return;
    setSwitchBusy(true);
    setSwitchRefusal(null);
    try {
      const res = await api.putAgentConfig(projectId, agentId, {
        config: { memory: { enabled: next } },
      });
      setEnabled(res.config.memory.enabled);
      toastSuccess(S.agent.savedTakesEffect);
      onConfigChanged?.();
    } catch (e) {
      // Nothing moved: the switch shows what the server answered with, and a refused write has no
      // answer — so the reason stays under the card, where the switch that retries it is. No toast
      // beside it: that line is the whole account of the refusal, and a second copy of it that
      // dismisses itself after six seconds only adds noise above the card it came from.
      setSwitchRefusal(featureSwitchRefused(S.memory.switchNoun, next, refusalText(e)));
    } finally {
      setSwitchBusy(false);
    }
  };

  /** The explicit adoption path for an agent whose template predates Memory: one idempotent config write. */
  const insertPlaceholder = async () => {
    if (!projectId) return;
    setInsertRefusal(null);
    try {
      const overview = await api.insertMemoryPlaceholder(projectId, agentId);
      setTemplateHasMemory(overview.templateHasMemory);
      toastSuccess(S.memory.insertPlaceholderDone);
      onConfigChanged?.();
    } catch (e) {
      // Nothing was written, so the template still has no placeholder and the strip below stays —
      // that keeps the sentence next to the button that retries it (Memory has no legacy section
      // to migrate, so the verb is always "insert"). The strip and this line are on screen, so a
      // notification carrying the same words would say it twice.
      setInsertRefusal(placeholderInsertRefused(S.memory.placeholderToken, false, refusalText(e)));
    }
  };

  /** Same contract as the Prompt tab's inserter: execCommand keeps the textarea's native undo stack, with a state-splice fallback. */
  const insertPromptToken = (
    ref: RefObject<HTMLTextAreaElement | null>,
    value: string,
    setValue: (next: string) => void,
    token: string,
  ) => {
    const el = ref.current;
    if (el) {
      el.focus();
      const inserted = document.execCommand?.("insertText", false, token);
      if (inserted) return; // onChange updates state from e.target.value
    }
    const start = el ? el.selectionStart : value.length;
    const end = el ? el.selectionEnd : value.length;
    setValue(value.slice(0, start) + token + value.slice(end));
    requestAnimationFrame(() => {
      if (!el) return;
      el.focus();
      const caret = start + token.length;
      el.setSelectionRange(caret, caret);
    });
  };

  /** Saves both memory prompts through the ordinary config write (confirm-first, like the other settings tabs). */
  const savePrompts = () =>
    requestSave(() => {
      if (!projectId) return;
      return api
        .putAgentConfig(projectId, agentId, {
          config: { memory: { prompt: memoryPrompt, workspacePrompt } },
        })
        .then((res) => {
          setMemoryPrompt(res.config.memory.prompt);
          setWorkspacePrompt(res.config.memory.workspacePrompt);
          toastSuccess(S.agent.savedTakesEffect);
          onConfigChanged?.();
        })
        .catch((e: unknown) => {
          // Handed back to the save card, which keeps the reason under its own sentence
          // (save-confirm.tsx) — and nothing is toasted for it: that card is what the person is
          // reading, and a notification beside it would repeat the sentence while outliving it.
          throw e;
        });
    });

  const openView = async (scope: MemoryScopeInfo, file: MemoryFileInfo) => {
    if (!projectId) return;
    // A fresh attempt starts without the previous one's reason, whichever memory it was for.
    setViewRefusal(null);
    try {
      const res = await api.getMemoryFile(projectId, agentId, scope.scopeKey, file.name);
      setSheetSnap("half"); // Every mobile open starts at the browsing height, like the chat panels.
      setViewing({ scope, file: res.file, content: res.content });
      setViewOpen(true);
    } catch (e) {
      // Handed to this row, which keeps the reason under its eye button — and nothing is toasted
      // for it: the panel is what the person asked for, and it is not there to say anything.
      setViewRefusal({
        scopeKey: scope.scopeKey,
        fileName: file.name,
        text: memoryViewRefused(file.title, e),
      });
    }
  };

  const memoryFilePath = (scope: MemoryScopeInfo, file: MemoryFileInfo) =>
    `${memoryDir}/${scope.scopeKey}/${file.name}`;

  /** Opens the edit modal (closing the view panel if it is up): requirement field + prompt preview, then the chat jump. */
  const openEditor = (scope: MemoryScopeInfo, file: MemoryFileInfo) => {
    setViewOpen(false);
    setEditRequirement("");
    setEditing({ scope, file });
  };

  const editPrompt = editing ? buildMemoryEditPrompt(editing.file.title, editRequirement) : "";
  // Copy feedback lives at the button (the shared copy convention): its glyph flips to
  // the check while copied — no toast, and the button label never changes.
  const editCopy = useCopied();

  /**
   * The bridge-to-chat jump shared by edit and add: the AI bridge prefills the draft with the
   * prompt and pins this Agent — and for a Workspace scope pins that Workspace too, so the
   * Session reads the very index it is about to change.
   */
  const openChatWithDraft = (text: string, workspacePath: string | undefined) => {
    openAiChat({
      agentId,
      text,
      ...(workspacePath !== undefined ? { workspace: workspacePath } : {}),
    });
  };

  const openEditChat = () => {
    if (editing) openChatWithDraft(editPrompt, editing.scope.workspacePath);
  };

  /** Opens the add modal for one scope: content empty, actions disabled until it is filled. */
  const openAdd = (scope: MemoryScopeInfo) => {
    setAddContent("");
    setAdding(scope);
  };

  const addPrompt = adding ? buildMemoryAddPrompt(adding.kind, addContent) : "";
  const addCopy = useCopied();

  const openAddChat = () => {
    if (adding) openChatWithDraft(addPrompt, adding.workspacePath);
  };

  /**
   * Downloads one group as a transfer document. Fetched as JSON and saved through an object URL
   * rather than followed as a link, so a failed request stays a value this tab can show instead of
   * an error body saved to disk (the skills tab's export made the same call).
   *
   * A refusal leaves its reason in the group that asked (memory-group-refusal.ts): the group, its
   * export button and every memory are still on screen, so a six-second notification is the one
   * thing that would carry the reason away. Starting an attempt clears the previous sentence — it
   * belonged to the attempt before, not to the group this one is about.
   */
  const exportScope = async (scope: MemoryScopeInfo) => {
    if (!projectId) return;
    setGroupRefusal(null);
    try {
      const doc = await api.exportMemoryScope(projectId, agentId, scope.scopeKey);
      const url = URL.createObjectURL(
        new Blob([JSON.stringify(doc, null, 2)], { type: "application/json" }),
      );
      const anchor = document.createElement("a");
      anchor.href = url;
      anchor.download = memoryDocumentFileName(agentId, scope.scopeKey, doc.exportedAt);
      document.body.appendChild(anchor);
      anchor.click();
      anchor.remove();
      URL.revokeObjectURL(url);
    } catch (e) {
      setGroupRefusal({
        scopeKey: scope.scopeKey,
        text: memoryExportRefused(scopeTitle(scope), e),
      });
    }
  };

  /**
   * Reads the picked file and opens the import modal; a file that is not a document never gets that
   * far. That refusal is this group's too (memory-group-refusal.ts): the file input is the group's
   * own import control, so the attention line would float over a list while the reader is looking
   * at the head strip that asked — and it would be gone in six seconds, leaving a pick that did
   * nothing and nothing saying why.
   */
  const pickImport = async (scope: MemoryScopeInfo, event: ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    // Cleared so picking the same file again still fires a change event.
    event.target.value = "";
    if (!file) return;
    // A picked document starts without the previous attempt's reason, whichever direction it went.
    setGroupRefusal(null);
    try {
      const doc = parseMemoryScopeDocument(await file.text());
      setImportMode("skip");
      // A newly picked document starts the dialog without the previous attempt's reason.
      setImportRefusal(null);
      setImporting({ scope, fileName: file.name, doc });
    } catch (e) {
      setGroupRefusal({
        scopeKey: scope.scopeKey,
        text: memoryImportRefused(scopeTitle(scope), e),
      });
    }
  };

  /**
   * Runs the import the person just asked for (with `confirm` once a plan was shown). Only a
   * written import closes the surfaces: a refused one leaves whichever surface asked — the plan
   * confirmation, or the import modal when nothing would have been lost — with the server's
   * words in it, so the retry is the same button rather than a fresh file pick.
   */
  const runImport = async (confirm: boolean) => {
    if (!projectId || !importing) return;
    setImportBusy(true);
    try {
      const res = await api.importMemoryScope(projectId, agentId, importing.scope.scopeKey, {
        mode: importMode,
        confirm,
        payload: importing.doc,
      });
      const touched = res.added.length + res.overwritten.length + res.removed.length;
      if (touched === 0) toastSuccess(S.memory.importNothingNew);
      else
        toastSuccess(
          S.memory.importDone(res.added.length, res.overwritten.length, res.removed.length),
        );
      setImportPlan(null);
      setImporting(null);
      await load();
      // The agent card's memory count changed; refresh the list provider too.
      void reloadAgents();
    } catch (e) {
      setImportRefusal(apiErrorText(e));
    } finally {
      setImportBusy(false);
    }
  };

  /** Import's first click: straight through when nothing would be lost, otherwise into the confirmation. */
  const submitImport = () => {
    if (!importing) return;
    // A fresh decision starts without the previous attempt's reason.
    setImportRefusal(null);
    const group = groups?.find((g) => g.scope.scopeKey === importing.scope.scopeKey);
    const plan = planMemoryImport(
      importing.doc,
      { names: group?.files.map((f) => f.name) ?? [], hasIndex: importing.scope.hasIndex },
      importMode,
    );
    if (plan.destroys) setImportPlan(plan);
    else void runImport(false);
  };

  /**
   * A memory's delete entry — the row's trash button, the drawer's, or the sheet's: opens the
   * confirmation without the previous attempt's reason, which belonged to the memory that
   * attempt named rather than to this one.
   */
  const askRemove = (target: Selected) => {
    setRemoving(target);
    setDeleteRefusal(null);
  };

  /**
   * Confirm modal's "Delete": only a written delete closes it. A refused one leaves the memory
   * on the page and on disk exactly as it was, so the card stays open with the server's words in
   * it and the same button retries — closing as the request left used to carry that reason into
   * a toast that dismisses itself after six seconds and sits above the card.
   */
  const confirmRemove = async () => {
    if (!projectId || !removing) return;
    const target = removing;
    try {
      await api.deleteMemoryFile(projectId, agentId, target.scope.scopeKey, target.file.name);
    } catch (e) {
      setDeleteRefusal(apiErrorText(e));
      return;
    }
    toastSuccess(S.memory.deleteDone);
    if (viewing && viewing.file.name === target.file.name) setViewOpen(false);
    setRemoving(null);
    await load();
    // The agent card's memory count changed; refresh the list provider too.
    void reloadAgents();
  };

  if (error) return <p className="text-sm text-red-600 dark:text-red-400">{error}</p>;

  // Icon-only row actions (the skills tab's affordance: neutral bordered icons, danger
  // variant with red text/hover for delete); the tooltip + aria-label carry the wording.
  const rowActions = (scope: MemoryScopeInfo, file: MemoryFileInfo) => (
    <div className="flex shrink-0 items-center gap-1.5">
      <IconButton
        label={`${S.memory.view} ${file.title}`}
        title={S.memory.view}
        onClick={() => void openView(scope, file)}
      >
        <GlyphIcon d={ICONS.eye} size={14} className="text-gray-600 dark:text-gray-300" />
      </IconButton>
      <IconButton
        label={`${S.memory.edit} ${file.title}`}
        title={S.memory.edit}
        onClick={() => openEditor(scope, file)}
      >
        <GlyphIcon d={ICONS.penLine} size={14} className="text-gray-600 dark:text-gray-300" />
      </IconButton>
      <IconButton
        variant="danger"
        label={`${S.memory.delete} ${file.title}`}
        title={S.memory.delete}
        onClick={() => askRemove({ scope, file })}
      >
        <GlyphIcon d={ICONS.trash} size={14} />
      </IconButton>
    </div>
  );

  // A memory's title is its file's identifier, so it keeps the data face on the code rung.
  const fileRow = (scope: MemoryScopeInfo, file: MemoryFileInfo) => {
    const refusal = memoryFileRefusalFor(viewRefusal, scope.scopeKey, file.name);
    return (
      <ListRow
        key={file.name}
        as="li"
        title={
          <span className="font-mono text-[length:var(--ui-text-code-size)]">{file.title}</span>
        }
        description={file.description ? file.description : undefined}
        meta={
          <span className="tabular-nums">
            {file.updatedAt ?? formatRelativeDate(file.modifiedAt, locale)}
          </span>
        }
        trailing={rowActions(scope, file)}
        /* A memory that did not open: this row still holds the eye button that retries it, so the
           reason sits under the row rather than in a notification that dismisses itself
           (memory-file-refusal.ts). */
        notice={
          refusal !== undefined ? (
            <p
              role="alert"
              data-testid="memory-file-refusal"
              data-tooltip={refusal}
              data-tooltip-content="text"
              className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
            >
              {refusal}
            </p>
          ) : undefined
        }
      />
    );
  };

  /** Metadata + rendered body of the memory in view, shared by the Drawer and the Sheet. */
  const viewMeta = viewing && (
    <>
      <span className="text-xs text-gray-400 dark:text-gray-500">
        {viewing.file.updatedAt ?? formatRelativeDate(viewing.file.modifiedAt, locale)}
      </span>
      {viewing.file.description && (
        <p className="text-xs text-gray-500 dark:text-gray-400">{viewing.file.description}</p>
      )}
      <div className="md-body border-t border-gray-100 pt-3 text-sm dark:border-gray-800">
        <Md text={bodyWithoutFrontmatter(viewing.content)} />
      </div>
    </>
  );

  const viewActions = viewing && (
    <div className="flex shrink-0 justify-end gap-2 border-t border-gray-200 px-4 py-3 dark:border-gray-800">
      <Button size="sm" onClick={() => openEditor(viewing.scope, viewing.file)}>
        {S.memory.edit}
      </Button>
      <Button size="sm" variant="danger" onClick={() => askRemove(viewing)}>
        {S.memory.delete}
      </Button>
    </div>
  );

  return (
    <div className="space-y-4">
      {/* Tab-level description: no title in the panel to anchor a "?" to (see help-fold.tsx). */}
      <HelpFold label={S.agent.tabMemory}>{S.memory.desc}</HelpFold>

      <ToggleRow
        variant="card"
        label={S.memory.enable}
        checked={enabled}
        onChange={(v) => void toggleEnabled(v)}
        disabled={switchBusy}
      />

      {/* The switch shows the position the server holds (a refused write answers nothing), so this
          sentence is what says why it did not move — and the switch above it is the retry. */}
      {switchRefusal !== null && (
        <p role="alert" className={`text-xs break-words ${toneInk.danger}`}>
          {switchRefusal}
        </p>
      )}

      {!templateHasMemory && (
        <>
          <Notice
            tone="attention"
            variant="callout"
            action={{ label: S.memory.insertPlaceholder, onClick: () => void insertPlaceholder() }}
          >
            {S.memory.templateMissing}
          </Notice>
          {/* A refused write leaves the strip (and its button) in place, so the reason can sit
              right under it — the strip's own button is what retries. */}
          {insertRefusal !== null && (
            <p role="alert" className={`text-xs break-words ${toneInk.danger}`}>
              {insertRefusal}
            </p>
          )}
        </>
      )}

      {groups === null ? (
        <SkeletonList rows={4} />
      ) : (
        <div className={enabled ? "space-y-4" : "space-y-4 opacity-60"}>
          {groups.map(({ scope, files }) => {
            const open = !collapsed.has(scope.scopeKey);
            const refusal = memoryGroupRefusalFor(groupRefusal, scope.scopeKey);
            return (
              /* One collapsible section per scope: the head strip folds the group; the group's
                 own actions sit after the toggle, outside it, since a button cannot hold
                 another. The section is a size container, not a viewport breakpoint: the
                 settings panel narrows independently of the window. Below @md the three action
                 labels drop and only their icons remain — 28rem is where the English labels
                 plus the count stop fitting beside the title, and rem tracks the user's font
                 tier (state/theme.tsx), so the threshold scales with the labels it measures. No
                 action is hidden at any width; each keeps its icon, an aria-label and a
                 tooltip. */
              <CollapsibleSection
                key={scope.scopeKey}
                className="@container"
                title={
                  scope.kind === "workspace" && scope.workspacePath !== undefined ? (
                    <>
                      {scopeTitle(scope)}
                      <span className="ml-2 font-mono text-xs font-normal text-gray-400 dark:text-gray-500">
                        {scope.workspacePath}
                      </span>
                    </>
                  ) : (
                    scopeTitle(scope)
                  )
                }
                meta={S.memory.itemCount(files.length)}
                open={open}
                onOpenChange={() => toggleCollapsed(scope.scopeKey)}
                notice={
                  /* A whole-group attempt this card offered that did not land — an export the
                     server would not serve, or a file the import never got to read: the head strip
                     (and the control that retries it) is on the card whether the group is folded or
                     not, so the reason sits under that strip rather than in a notification that
                     dismisses itself (memory-group-refusal.ts). */
                  refusal !== undefined ? (
                    <p
                      role="alert"
                      data-testid="memory-refusal"
                      data-tooltip={refusal}
                      data-tooltip-content="text"
                      className={`line-clamp-2 break-words text-xs ${toneInk.danger}`}
                    >
                      {refusal}
                    </p>
                  ) : undefined
                }
                actions={
                  /* Whole-group transfer, icon + label (the labels are what say which way a
                     transfer goes, wherever the row is wide enough to keep them): export for any
                     member, import for the owner. The tooltip carries what the label cannot —
                     that the whole group travels — and on a narrow row, where the label is gone,
                     it carries the direction too, alongside the aria-label. */
                  <>
                    <Button
                      size="sm"
                      variant="ghost"
                      title={S.memory.exportScopeHint}
                      data-tooltip-extra
                      aria-label={S.memory.exportScopeLabel(scopeTitle(scope))}
                      onClick={() => void exportScope(scope)}
                    >
                      <DownloadIcon size={13} />
                      <span className="hidden @md:inline">{S.memory.exportScope}</span>
                    </Button>
                    {isOwner && (
                      <label
                        className={`${GHOST_LABEL_CLASS} shrink-0`}
                        data-tooltip={S.memory.importScopeHint}
                        data-tooltip-extra
                        aria-label={S.memory.importScopeLabel(scopeTitle(scope))}
                      >
                        <HiddenFileInput
                          accept=".json,application/json"
                          onChange={(e) => void pickImport(scope, e)}
                        />
                        <UploadIcon size={13} />
                        <span className="hidden @md:inline">{S.memory.importScope}</span>
                      </label>
                    )}
                    <Button
                      size="sm"
                      variant="ghost"
                      title={S.memory.add}
                      aria-label={S.memory.addScopeLabel(scopeTitle(scope))}
                      onClick={() => openAdd(scope)}
                    >
                      <GlyphIcon d={ICONS.plus} size={13} />
                      <span className="hidden @md:inline">{S.memory.add}</span>
                    </Button>
                  </>
                }
              >
                {files.length === 0 ? (
                  <p className="px-4 py-4 text-center text-xs text-gray-400 dark:text-gray-500">
                    {scope.kind === "user" ? S.memory.emptyUserScope : S.memory.emptyScope}
                  </p>
                ) : (
                  <ul>{files.map((file) => fileRow(scope, file))}</ul>
                )}
              </CollapsibleSection>
            );
          })}
        </div>
      )}

      <Card as="section" padding="md" className="space-y-3">
        <h3 className="flex items-center gap-1.5 text-sm font-semibold text-gray-800 dark:text-gray-200">
          {S.memory.promptSection}
          <InfoPopover label={S.memory.promptSection}>{S.memory.promptSectionHint}</InfoPopover>
        </h3>
        <Textarea
          ref={mainPromptRef}
          label={S.memory.promptLabel}
          mono
          size="sm"
          rows={12}
          value={memoryPrompt}
          onFocus={() => setLastPromptField("main")}
          onChange={(e) => setMemoryPrompt(e.target.value)}
        />
        <Textarea
          ref={workspacePromptRef}
          label={S.memory.workspacePromptLabel}
          mono
          size="sm"
          rows={6}
          value={workspacePrompt}
          onFocus={() => setLastPromptField("workspace")}
          onChange={(e) => setWorkspacePrompt(e.target.value)}
        />
        {/* Placeholder reference, the Prompt tab's convention — a chip inserts into whichever field was focused last.
            Inside the card it takes the step below the card's radius. */}
        <div className="rounded-sm border border-gray-200 bg-gray-50 p-3 dark:border-gray-800 dark:bg-gray-900">
          <p className="mb-2 text-xs font-semibold text-gray-500">{S.agent.placeholdersTitle}</p>
          <ul className="space-y-1">
            {S.memory.promptPlaceholders.map(([token, desc]) => (
              <li key={token} className="flex items-center gap-3 text-xs">
                <button
                  type="button"
                  onClick={() =>
                    lastPromptField === "main"
                      ? insertPromptToken(mainPromptRef, memoryPrompt, setMemoryPrompt, token!)
                      : insertPromptToken(
                          workspacePromptRef,
                          workspacePrompt,
                          setWorkspacePrompt,
                          token!,
                        )
                  }
                  data-tooltip={S.memory.insertToken}
                  data-tooltip-extra
                  className="shrink-0 rounded border border-gray-200 bg-white px-1.5 py-0.5 font-mono font-semibold text-gray-800 transition-colors duration-150 hover:border-gray-400 hover:bg-gray-100 dark:border-gray-700 dark:bg-gray-800 dark:text-gray-200 dark:hover:border-gray-500 dark:hover:bg-gray-700"
                >
                  {token}
                </button>
                <span className="text-gray-500 dark:text-gray-400">{desc}</span>
              </li>
            ))}
          </ul>
        </div>
        <div className="flex justify-end">
          <Button size="sm" variant="primary" onClick={savePrompts}>
            {S.common.save}
          </Button>
        </div>
      </Card>

      {saveConfirm}

      {/* The view: a right Drawer on desktop, a bottom Sheet below the breakpoint (the same split
          as the chat page's panels — Sheet brings the grab handle, snap points and swipe-down).
          Mounted mutually exclusively; the metadata + body block is shared, only the action row's
          placement differs (pinned footer vs. flowing after the content the Sheet scrolls). */}
      {isDesktop ? (
        <Drawer
          open={viewOpen}
          side="right"
          title={viewing?.file.title ?? ""}
          onClose={() => setViewOpen(false)}
          widthClass="max-w-lg"
        >
          {viewing && (
            <div className="flex h-full flex-col">
              <div className="flex-1 space-y-3 overflow-y-auto px-4 py-3">{viewMeta}</div>
              {viewActions}
            </div>
          )}
        </Drawer>
      ) : (
        <Sheet
          open={viewOpen}
          snap={sheetSnap}
          onSnapChange={setSheetSnap}
          title={viewing?.file.title ?? ""}
          onClose={() => setViewOpen(false)}
        >
          {viewing && (
            <>
              <div className="space-y-3 px-4 py-3">{viewMeta}</div>
              {viewActions}
            </>
          )}
        </Sheet>
      )}

      <Modal
        open={editing !== null}
        title={S.memory.editTitle}
        onClose={() => setEditing(null)}
        widthClass="sm:max-w-lg"
      >
        {editing && (
          <div className="space-y-3">
            <p className="text-xs text-gray-500 dark:text-gray-400">{S.memory.editWhy}</p>
            <p className="break-all font-mono text-xs text-gray-400 dark:text-gray-500">
              {memoryFilePath(editing.scope, editing.file)}
            </p>
            <Textarea
              label={S.memory.editRequirementLabel}
              size="sm"
              rows={2}
              value={editRequirement}
              onChange={(e) => setEditRequirement(e.target.value)}
              placeholder={S.memory.editRequirementPlaceholder}
            />
            <Textarea
              label={S.memory.editPromptLabel}
              size="sm"
              rows={6}
              readOnly
              value={editPrompt}
              className="text-gray-600 dark:text-gray-300"
            />
            <div className="flex gap-2">
              <Button size="sm" onClick={() => editCopy.flash(editPrompt)}>
                <CopyCheckGlyph copied={editCopy.copied} size={12} />
                {S.memory.editCopyPrompt}
              </Button>
              <CopiedStatus copied={editCopy.copied} />
              <Button size="sm" variant="primary" onClick={openEditChat}>
                {S.memory.editOpenChat}
              </Button>
            </div>
          </div>
        )}
      </Modal>

      {/* Add bridge modal: the edit modal's shape, but the content field is required — the
          prompt is meaningless without it, so both actions stay disabled until it is filled. */}
      <Modal
        open={adding !== null}
        title={S.memory.addTitle}
        onClose={() => setAdding(null)}
        widthClass="sm:max-w-lg"
      >
        {adding && (
          <div className="space-y-3">
            <p className="text-xs text-gray-500 dark:text-gray-400">{S.memory.addWhy}</p>
            <p className="break-all font-mono text-xs text-gray-400 dark:text-gray-500">
              {`${memoryDir}/${adding.scopeKey}`}
            </p>
            <Textarea
              label={S.memory.addContentLabel}
              required
              size="sm"
              rows={4}
              value={addContent}
              onChange={(e) => setAddContent(e.target.value)}
              placeholder={S.memory.addContentPlaceholder}
            />
            <Textarea
              label={S.memory.editPromptLabel}
              size="sm"
              rows={6}
              readOnly
              value={addPrompt}
              className="text-gray-600 dark:text-gray-300"
            />
            <div className="flex gap-2">
              <Button
                size="sm"
                disabled={addContent.trim() === ""}
                onClick={() => addCopy.flash(addPrompt)}
              >
                <CopyCheckGlyph copied={addCopy.copied} size={12} />
                {S.memory.editCopyPrompt}
              </Button>
              <CopiedStatus copied={addCopy.copied} />
              <Button
                size="sm"
                variant="primary"
                disabled={addContent.trim() === ""}
                onClick={openAddChat}
              >
                {S.memory.editOpenChat}
              </Button>
            </div>
          </div>
        )}
      </Modal>

      {/* Import modal: the file that was picked, then the one consequential choice — what to do
          with a name this group already has. The default loses nothing; the other two are held
          behind the confirmation below. */}
      <Modal
        open={importing !== null}
        title={S.memory.importTitle}
        onClose={() => setImporting(null)}
        widthClass="sm:max-w-lg"
      >
        {importing && (
          <div className="space-y-3">
            <p className="text-xs text-gray-500 dark:text-gray-400">{S.memory.importWhy}</p>
            <p className="break-all font-mono text-xs text-gray-500 dark:text-gray-400">
              {S.memory.importFile(importing.fileName, importing.doc.files.length)}
            </p>
            <RadioGroup
              label={S.memory.importModeLabel}
              name="memory-import-mode"
              value={importMode}
              onChange={(mode) => {
                setImportMode(mode);
                // The reason named the mode that was refused; choosing another starts clean.
                setImportRefusal(null);
              }}
              options={[
                {
                  value: "skip",
                  label: S.memory.importModeSkip,
                  hint: S.memory.importModeSkipHint,
                },
                {
                  value: "overwrite",
                  label: S.memory.importModeOverwrite,
                  hint: S.memory.importModeOverwriteHint,
                },
                {
                  value: "replace",
                  label: S.memory.importModeReplace,
                  hint: S.memory.importModeReplaceHint,
                },
              ]}
            />
            {/* This modal is where an import that needed no confirmation reports a refusal (the
                one that went through the plan confirmation prints it inside that card instead). */}
            {importRefusal !== null && importPlan === null && (
              <p className="text-xs text-red-600 dark:text-red-400">
                {S.common.refused(importRefusal)}
              </p>
            )}
            <div className="flex justify-end">
              <Button size="sm" variant="primary" disabled={importBusy} onClick={submitImport}>
                {S.memory.importAction}
              </Button>
            </div>
          </div>
        )}
      </Modal>

      {/* What the chosen mode costs, memory by memory, before it runs. The import modal stays
          underneath (the skills tab's overwrite confirmation does the same), so cancelling comes
          back to the mode choice rather than to an empty tab. */}
      <ConfirmModal
        open={importPlan !== null}
        tone="danger"
        title={S.memory.importConfirmTitle}
        confirmLabel={S.memory.importAction}
        cancelLabel={S.common.cancel}
        busy={importBusy}
        onClose={() => setImportPlan(null)}
        onConfirm={() => void runImport(true)}
        refusal={importRefusal === null ? undefined : S.common.refused(importRefusal)}
      >
        <div className="space-y-1.5 text-sm text-gray-700 dark:text-gray-300">
          {importPlan && importPlan.overwritten.length > 0 && (
            <p className="break-words">{S.memory.importWillOverwrite(importPlan.overwritten)}</p>
          )}
          {importPlan && importPlan.removed.length > 0 && (
            <p className="break-words">{S.memory.importWillRemove(importPlan.removed)}</p>
          )}
          {importPlan?.replacesIndex && <p>{S.memory.importWillReplaceIndex}</p>}
          <p className="text-xs text-gray-500 dark:text-gray-400">{S.memory.importIrreversible}</p>
        </div>
      </ConfirmModal>

      <ConfirmModal
        open={removing !== null}
        tone="danger"
        title={S.memory.deleteTitle}
        confirmLabel={S.memory.delete}
        cancelLabel={S.common.cancel}
        onClose={() => setRemoving(null)}
        onConfirm={() => void confirmRemove()}
        refusal={deleteRefusal === null ? undefined : S.common.refused(deleteRefusal)}
      >
        <p className="text-sm text-gray-700 dark:text-gray-300">
          {removing ? S.memory.deleteConfirm(removing.file.title) : ""}
        </p>
      </ConfirmModal>
    </div>
  );
}