import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog"; // SPDX-License-Identifier: AGPL-3.0-only import { Button } from "@/components/ui/button"; import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; import { Textarea } from "@/components/ui/textarea"; import { createNavigationNonce } from "@/lib/navigation-nonce"; import { authFetch } from "@/features/auth"; import { refreshContextUsage, useChatRuntimeStore } from "@/features/chat"; import { listChatProjects } from "@/features/chat/api/chat-api"; import { type ReactNode, useEffect, useId, useRef, useState } from "react"; import { type LearnedMemory, requestLearnedMemory as requestMemory, } from "../api/learned-memory"; import { useSettingsDialogStore } from "../stores/settings-dialog-store"; import { SettingsRow } from "./settings-row"; import { SettingsSection } from "./settings-section"; type MemoryDraft = { kind: "new" | "edit"; key: string; value: string }; function newMemoryDraft(): MemoryDraft { return { kind: "new", key: `note_${createNavigationNonce() .replace(/[^a-z0-9_]/gi, "") .toLowerCase() .slice(0, 59)}`, value: "", }; } export function LearnedMemorySection() { const ref = useRef(null); const scrollTarget = useSettingsDialogStore((state) => state.scrollTarget); useEffect(() => { if (scrollTarget !== "chat-memory") return; const frame = requestAnimationFrame(() => { ref.current?.scrollIntoView({ block: "start", behavior: "smooth" }); useSettingsDialogStore.getState().consumeScrollTarget("chat-memory"); }); return () => cancelAnimationFrame(frame); }, [scrollTarget]); const threadId = useChatRuntimeStore((state) => state.activeThreadId); const incognito = useChatRuntimeStore((state) => state.incognito); const memoryScopeRequested = useSettingsDialogStore( (state) => state.memoryScopeRequested, ); const [projectId, setProjectId] = useState(memoryScopeRequested?.projectId ?? ""); useEffect(() => { if (!memoryScopeRequested) return; setProjectId(memoryScopeRequested.projectId ?? ""); useSettingsDialogStore.getState().consumeMemoryScopeRequest(); }, [memoryScopeRequested]); const [projects, setProjects] = useState< Awaited> >([]); useEffect(() => { void listChatProjects() .then(setProjects) .catch(() => {}); }, []); return (
setProjectId(value === "personal" ? "" : value) } > Personal · all chats {projects.length > 0 && ( Projects {projects.map((project) => ( {project.name} ))} )} } />
); } function MemoryEditor({ projectId, threadId, scopeControl, }: { projectId: string; threadId?: string; scopeControl: ReactNode }) { const factId = useId(); const [memory, setMemory] = useState(null); const [draft, setDraft] = useState(newMemoryDraft); const [confirmClear, setConfirmClear] = useState(false); const [error, setError] = useState(""); const [busy, setBusy] = useState(false); const [omitted, setOmitted] = useState(0); const contextLength = useChatRuntimeStore( (state) => state.loadedContextLength ?? 4096, ); const query = new URLSearchParams({ ...(projectId ? { project_id: projectId } : {}), ...(threadId ? { thread_id: threadId } : {}), }).toString(); useEffect(() => { let cancelled = false; void requestMemory(query) .then((result) => { if (!cancelled) setMemory(result); }) .catch((cause: unknown) => { if (!cancelled) setError(String(cause)); }); return () => { cancelled = true; }; }, [query]); useEffect(() => { let cancelled = false; setOmitted(0); if (threadId && memory?.enabled && memory.thread_enabled) void authFetch( `/api/chat/memory-context?${new URLSearchParams({ thread_id: threadId, context_length: String(contextLength), })}`, ) .then((response) => response.json()) .then((body: unknown) => { if ( !cancelled && typeof body === "object" && body !== null && "omitted" in body && typeof body.omitted === "number" ) setOmitted(body.omitted); }) .catch(() => {}); return () => { cancelled = true; }; }, [ threadId, contextLength, memory?.enabled, memory?.thread_enabled, memory?.revision, ]); async function save(patch: object) { if (!memory || busy) return false; setBusy(true); setError(""); try { setMemory( await requestMemory(query, { revision: memory.revision, ...patch }), ); void refreshContextUsage({ invalidate: true }); return true; } catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); try { setMemory(await requestMemory(query)); } catch { /* Keep the last readable state. */ } return false; } finally { setBusy(false); } } async function saveDraft() { if (await save({ key: draft.key, value: draft.value })) { setDraft(newMemoryDraft()); } } async function deleteMemory(key: string) { if ((await save({ key, value: null })) && key === draft.key) { setDraft(newMemoryDraft()); } } const count = Object.keys(memory?.entries ?? {}).length; return (
void save({ enabled })} /> {threadId && ( void save({ thread_enabled: threadEnabled }) } /> )} {scopeControl} {omitted > 0 && (

{omitted} older memories won't be included in this chat because its context is small.

)} {memory && Object.entries(memory.entries).map(([entryKey, entry]) => (

{entry.value}

))} {memory && count === 0 && (

{projectId ? "No memories for this project yet. Add one below, or ask the model to remember something in one of this project's chats." : "No personal memories yet. Add one below, or ask the model to remember something when memory is on."}{" "} The model picks where to save: preferences go to personal, project details to the project.

)}