"use client"; import dynamic from "next/dynamic"; import { useCallback, useEffect, useRef, useState } from "react"; import { BookOpen, Brain, Eraser, Loader2, RefreshCw, Save, User, } from "lucide-react"; import { useTranslation } from "react-i18next"; import { useAppShell } from "@/context/AppShellContext"; import { apiFetch, apiUrl } from "@/lib/api"; import SpaceSectionHeader from "@/components/space/SpaceSectionHeader"; const MarkdownRenderer = dynamic( () => import("@/components/common/MarkdownRenderer"), { ssr: false }, ); type MemoryFile = "summary" | "profile"; interface MemoryData { summary: string; profile: string; summary_updated_at: string | null; profile_updated_at: string | null; } interface MemoryApiData extends MemoryData { changed?: boolean; } const TABS: { key: MemoryFile; label: string; icon: typeof Brain; hint: string; placeholder: string; }[] = [ { key: "summary", label: "Summary", icon: BookOpen, hint: "Running summary of the learning journey. Auto-updated after conversations.", placeholder: "## Current Focus\n- ...\n\n## Accomplishments\n- ...\n\n## Open Questions\n- ...", }, { key: "profile", label: "Profile", icon: User, hint: "User identity, preferences, and knowledge levels. Auto-updated after conversations.", placeholder: "## Identity\n- ...\n\n## Learning Style\n- ...\n\n## Knowledge Level\n- ...\n\n## Preferences\n- ...", }, ]; const EMPTY: MemoryData = { summary: "", profile: "", summary_updated_at: null, profile_updated_at: null, }; function formatUpdatedAt( value: string | null, t: (key: string) => string, ): string { if (!value) return t("Not updated yet"); const date = new Date(value); if (Number.isNaN(date.getTime())) return t("Unknown"); return date.toLocaleString(); } async function readMemoryResponse(res: Response): Promise { const payload = (await res.json().catch(() => ({}))) as { detail?: unknown; }; if (!res.ok) { throw new Error( typeof payload.detail === "string" ? payload.detail : "Memory request failed", ); } return payload as MemoryApiData; } export default function MemorySection() { const { t } = useTranslation(); const { activeSessionId, language } = useAppShell(); const [data, setData] = useState(EMPTY); const [loading, setLoading] = useState(true); const [refreshing, setRefreshing] = useState(false); const [clearing, setClearing] = useState(false); const [saving, setSaving] = useState(false); const [activeTab, setActiveTab] = useState("summary"); const [activeView, setActiveView] = useState<"edit" | "preview">("edit"); const [editors, setEditors] = useState>({ summary: "", profile: "", }); const [toast, setToast] = useState(""); const textareaRef = useRef(null); const tab = TABS.find((tabItem) => tabItem.key === activeTab)!; const editorValue = editors[activeTab]; const hasChanges = editorValue !== data[activeTab]; const updatedAt = data[`${activeTab}_updated_at` as keyof MemoryData] as | string | null; useEffect(() => { if (!toast) return; const timer = setTimeout(() => setToast(""), 3500); return () => clearTimeout(timer); }, [toast]); const loadMemory = useCallback(async () => { setLoading(true); try { const res = await apiFetch(apiUrl("/api/v1/memory")); const d = await readMemoryResponse(res); setData(d); setEditors({ summary: d.summary || "", profile: d.profile || "" }); } catch (error) { setToast( error instanceof Error ? error.message : t("Memory request failed"), ); } finally { setLoading(false); } }, [t]); useEffect(() => { void loadMemory(); }, [loadMemory]); const saveMemory = useCallback(async () => { setSaving(true); try { const res = await apiFetch(apiUrl("/api/v1/memory"), { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ file: activeTab, content: editorValue }), }); const d = await readMemoryResponse(res); setData(d); setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" })); setToast(t("{{label}} saved", { label: t(tab.label) })); } catch (error) { setToast(error instanceof Error ? error.message : t("Memory save failed")); } finally { setSaving(false); } }, [activeTab, editorValue, t, tab.label]); const refreshMemory = useCallback(async () => { setRefreshing(true); try { const res = await apiFetch(apiUrl("/api/v1/memory/refresh"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ session_id: activeSessionId || undefined, language, }), }); const d = await readMemoryResponse(res); setData(d); setEditors({ summary: d.summary || "", profile: d.profile || "" }); setToast( d.changed === false ? t("Memory checked; no long-term updates") : t("Memory refreshed from session"), ); } catch (error) { setToast( error instanceof Error ? error.message : t("Memory refresh failed"), ); } finally { setRefreshing(false); } }, [activeSessionId, language, t]); const clearMemory = useCallback(async () => { if (!window.confirm(t("Clear {{label}}?", { label: t(tab.label) }))) return; setClearing(true); try { const res = await apiFetch(apiUrl("/api/v1/memory/clear"), { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ file: activeTab }), }); const d = await readMemoryResponse(res); setData(d); setEditors((prev) => ({ ...prev, [activeTab]: d[activeTab] || "" })); setToast(t("{{label}} cleared", { label: t(tab.label) })); } catch (error) { setToast( error instanceof Error ? error.message : t("Memory clear failed"), ); } finally { setClearing(false); } }, [activeTab, t, tab.label]); const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if ((e.metaKey || e.ctrlKey) && e.key === "s") { e.preventDefault(); void saveMemory(); } }, [saveMemory], ); return (
{toast} ) : ( {hasChanges ? t("Unsaved changes") : t("All changes saved")} ) } action={
} /> {/* Tab selector */}
{TABS.map((tabItem) => { const Icon = tabItem.icon; const active = activeTab === tabItem.key; return ( ); })}
{/* Meta & View toggle */}

{t(tab.hint)}

{(["edit", "preview"] as const).map((v) => ( ))}
{t("Updated")}: {formatUpdatedAt(updatedAt, t)}
{/* Content */} {loading ? (
) : activeView === "edit" ? (