import type { ReactNode } from "react"; import { Loader2 } from "lucide-react"; import { useTranslation } from "react-i18next"; import type { MemoryBackendCapabilities, MemoryBackendStatus, MemoryFileInfo, MemoryRetrievalTestResult, } from "../../../api"; import { FileEditor } from "../../FileEditor"; import type { SectionBaseProps } from "./context"; import { LoadingSpinner } from "../../LoadingSpinner"; const MEMORY_FILE_OPTION_LABEL_MAX_CHARS = 72; function truncateMiddle(value: string, maxChars: number): string { if (value.length <= maxChars) { return value; } const visibleChars = Math.max(1, maxChars - 1); const startChars = Math.ceil(visibleChars / 2); const endChars = Math.floor(visibleChars / 2); return `${value.slice(0, startChars)}…${value.slice(value.length - endChars)}`; } function formatMemoryFileOptionLabel(file: MemoryFileInfo): string { const fullLabel = `${file.label} — ${file.path}`; return truncateMiddle(fullLabel, MEMORY_FILE_OPTION_LABEL_MAX_CHARS); } export interface MemorySectionMemoryProps { memoryCapabilities: MemoryBackendCapabilities | null; memoryBackendStatus: MemoryBackendStatus | null; memoryBackendLoading: boolean; memoryBackendError: string | null; memoryFiles: MemoryFileInfo[]; selectedMemoryPath: string; setSelectedMemoryPath: (path: string) => void; memoryContent: string; setMemoryContent: (content: string) => void; memoryLoading: boolean; memoryDirty: boolean; setMemoryDirty: (dirty: boolean) => void; memoryTestQuery: string; setMemoryTestQuery: (query: string) => void; memoryTestLoading: boolean; memoryTestResult: MemoryRetrievalTestResult | null; qmdInstallLoading: boolean; dreamRunning: boolean; memoryCompactLoading: boolean; onInstallQmd: () => void; onTestMemoryRetrieval: () => void; onDreamNow: () => void; onCompactMemory: () => void; onSaveMemory: () => void; } export interface MemorySectionProps extends SectionBaseProps { scopeBanner: ReactNode; memory: MemorySectionMemoryProps; } export function MemorySection({ scopeBanner, form, setForm, memory }: MemorySectionProps) { const { t } = useTranslation("app"); const { memoryCapabilities: capabilities, memoryBackendStatus: backendStatus, memoryBackendLoading: backendLoading, memoryBackendError: backendError, memoryFiles, selectedMemoryPath, setSelectedMemoryPath, memoryContent, setMemoryContent, memoryLoading, memoryDirty, setMemoryDirty, memoryTestQuery, setMemoryTestQuery, memoryTestLoading, memoryTestResult, qmdInstallLoading, dreamRunning, memoryCompactLoading, onInstallQmd, onTestMemoryRetrieval, onDreamNow, onCompactMemory, onSaveMemory, } = memory; // Determine if editing is allowed const isMemoryEnabled = form.memoryEnabled !== false; const backendStatusResolved = !backendLoading && backendStatus !== null; const isBackendWritable = backendStatusResolved ? (capabilities?.writable ?? true) : true; const isEditingAllowed = isMemoryEnabled && isBackendWritable; const selectedMemoryFile = memoryFiles.find((file) => file.path === selectedMemoryPath); const memoryLayerNames: Record = { "long-term": "Long-term", daily: "Daily", dreams: "Dreams", }; return (<> {scopeBanner}

{t("settings.memory.memory", "Memory")}

{t("settings.memory.memoryLivesIn", " Memory lives in ")}.fusion/memory/{t("settings.memory.agentsSearchWithQmdFirstFallBackTo", ". Agents search with qmd first, fall back to local files when qmd is missing, and open exact line windows only when needed. ")}
{t("settings.memory.agentsGetMemorySearchMemoryGetAndMemory", "Agents get memory_search, memory_get, and memory_append tools. Search defaults to qmd with a local file fallback.")}
{backendLoading ? (
{t("settings.memory.checkingMemoryWriteAccess", "Checking memory write access...")}
) : backendError ? (
{t("settings.memory.failedToLoadBackendStatus", "Failed to load backend status: ")}{backendError}
) : null} {backendStatusResolved && backendStatus.qmdAvailable === false && (
{t("settings.memory.qmdIsNotInstalledSearchWillUseLocal", " qmd is not installed. Search will use local files. Install indexed retrieval: ")}{backendStatus.qmdInstallCommand || "bun install -g @tobilu/qmd"}
)}
{t("settings.memory.automaticallyCompactMemoryWhenItExceedsTheThreshold", "Automatically compact memory when it exceeds the threshold on a schedule")}
{(form.memoryAutoSummarizeEnabled || false) && (<>
setForm((f) => ({ ...f, memoryAutoSummarizeThresholdChars: parseInt(e.target.value, 10) || 50000, }))} min={1000}/> {t("settings.memory.memoryWillBeCompactedWhenItExceedsThis", "Memory will be compacted when it exceeds this character count")}
setForm((f) => ({ ...f, memoryAutoSummarizeSchedule: e.target.value }))} placeholder={t("settings.memory.03", "0 3 * * *")}/> {t("settings.memory.cronExpressionForAutoSummarizeScheduleDefaultDaily", "Cron expression for auto-summarize schedule (default: daily at 3 AM)")}
)}
{t("settings.memory.turnsDailyNotesIntoDREAMSMdAndPromotes", "Turns daily notes into DREAMS.md and promotes reusable lessons into MEMORY.md.")}
{isMemoryEnabled && form.memoryDreamsEnabled === true && (<>
setForm((f) => ({ ...f, memoryDreamsSchedule: e.target.value }))}/> {t("settings.memory.cronExpressionForDreamProcessing", "Cron expression for dream processing.")}
{t("settings.memory.manuallyTriggerDreamProcessingNow", "Manually trigger dream processing now.")}
)}
setMemoryTestQuery(e.target.value)} placeholder={t("settings.memory.searchMemoryWithQmd", "Search memory with qmd")}/> {t("settings.memory.runsTheSameQmdBackedMemorySearchPath", "Runs the same qmd-backed memory_search path agents use.")}
{memoryTestResult && (
{memoryTestResult.results.length}{t("settings.memory.result", " result")}{memoryTestResult.results.length === 1 ? "" : "s"} {" "}{t("settings.memory.for", "for \"")}{memoryTestResult.query}" {t("settings.memory.qmd", " qmd ")}{memoryTestResult.qmdAvailable ? "available" : "missing"} · {memoryTestResult.usedFallback ? "local fallback used" : "qmd path used"} {memoryTestResult.results.length > 0 ? (
    {memoryTestResult.results.map((result, index) => (
  • {result.path}:{result.lineStart}

    {result.snippet}

  • ))}
) : ({t("settings.memory.noMatchingMemoryFound", "No matching memory found.")})}
)}
{!isMemoryEnabled && (
{t("settings.memory.memoryIsCurrentlyDisabledYouCanViewThe", " Memory is currently disabled. You can view the file, but editing is read-only until memory is re-enabled. ")}
)} {isMemoryEnabled && backendStatusResolved && !isBackendWritable && (
{t("settings.memory.memoryIsConfiguredWithAReadOnlyBackend", " Memory is configured with a read-only backend. You can view the file, but saving is disabled. ")}
)} {memoryLoading ? (
) : (
{memoryDirty ? "Save or discard the current edits before switching files." : "Choose any project memory file to view or edit. Dreams is selected by default."}
{selectedMemoryFile && (
{memoryLayerNames[selectedMemoryFile.layer]} {selectedMemoryFile.path} {selectedMemoryFile.size.toLocaleString()}{t("settings.memory.bytesUpdated", " bytes \u00B7 updated ")}{new Date(selectedMemoryFile.updatedAt).toLocaleString()}
)}
{selectedMemoryFile?.layer === "long-term" && "Curated durable decisions, conventions, constraints, and pitfalls promoted from dreams."} {selectedMemoryFile?.layer === "daily" && "Raw daily observations, open loops, and running context for dream processing."} {selectedMemoryFile?.layer === "dreams" && "Synthesized patterns and open loops promoted from daily memory."} {!selectedMemoryFile && "Edits the selected memory file."}
{ setMemoryContent(content); setMemoryDirty(true); }} readOnly={!isEditingAllowed} filePath={selectedMemoryPath}/>
)} {!memoryLoading && (
{memoryDirty ? "Save or discard edits before compacting this file." : `Compacts ${selectedMemoryPath} and writes the result back to the same file.`}
)} {memoryDirty && isEditingAllowed && (
)} {memoryDirty && !isEditingAllowed && (
{t("settings.memory.cannotSave", "Cannot save: ")}{isMemoryEnabled ? "Backend is read-only" : "Memory is disabled"}
)} ); } export default MemorySection;