"use client"; import Link from "next/link"; import { useEffect, useId, useState } from "react"; import { Brain, Check, Copy, FolderTree, Plus, Sparkles, Trash2, } from "lucide-react"; import { toast } from "sonner"; import { useMemoryStores } from "@/hooks/use-memory-stores"; import { Button } from "@/components/ui/button"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Switch } from "@/components/ui/switch"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "@/components/ui/select"; import { useChatConfig } from "@/components/chat/chat-config-context"; import { MemoryFilesDialog } from "@/components/chat/memory-files-dialog"; import { WikiBindSection } from "@/components/chat/wiki-bind-section"; import { ScopeCombobox } from "@/components/memory/scope-combobox"; import { useI18n } from "@/i18n/i18n-context"; import { cn } from "@/lib/utils"; import { normalizeStorageMode, parseKnownStorageMode, resolveRetrievalMode, storageModeCapabilities, type StorageMode, } from "@/lib/memory-storage-mode"; /** * 抽屉里的「记忆库」区块。 * * 骨架与同抽屉里的「挂载的知识库 / 统一检索参数」section 严格对齐: * - 同样的 `border-t pt-4` 外壳 + 「标题 + 副标题 + 右侧紧凑数字输入」的 header * - 未绑定 → 与 MountEmptyState 同款 hero 卡片(gradient bg、primary-soft icon tile) * - 已绑定 → 与 MountRow 同款单行 chip 展示选中的 store;下方独立配置子区 * * 绑定状态来自抽屉 reducer(跨会话 hydrate),故继续用受控 Input/Select, * 不迁 react-hook-form —— 双向同步成本远高于收益。 */ export function MemoryBindSection() { const { t } = useI18n(); const cfg = useChatConfig(); const { data: storesPage, isLoading, isSuccess } = useMemoryStores(); const stores = storesPage?.items ?? []; const binding = cfg.memory; const topKId = useId(); const boundStore = binding ? stores.find((s) => s.memoryStoreName === binding.memoryStoreName) : undefined; const boundStoreFound = !!boundStore; const authoritativeStorageMode = parseKnownStorageMode( boundStore?.storageMode, ); const storageMode = normalizeStorageMode( boundStore?.storageMode ?? binding?.storageMode, ); const capabilities = storageModeCapabilities(storageMode); const autoSaveAllowed = capabilities.structuredAutoSave || capabilities.writableFiles; // 纠偏:绑定的库不是文件型却残留 retrievalMode=local(切换了库、或载入了旧会话) // 时,强制回落 search,避免对话时走文件记忆分支报错。等库列表就绪后再纠偏, // 防止加载态误判。 const currentMode = binding?.retrievalMode; useEffect(() => { if (!binding || !isSuccess || !boundStore) return; const corrected = resolveRetrievalMode(currentMode, storageMode); const nextStorageMode = authoritativeStorageMode ?? undefined; const patch = { ...(currentMode !== corrected ? { retrievalMode: corrected } : {}), ...(binding.storageMode !== nextStorageMode ? { storageMode: nextStorageMode } : {}), }; if (Object.keys(patch).length > 0) { cfg.updateMemory(patch); } // cfg.updateMemory 稳定;仅依赖会影响判定的原始量 // eslint-disable-next-line react-hooks/exhaustive-deps }, [ binding?.memoryStoreName, binding?.storageMode, currentMode, authoritativeStorageMode, storageMode, isSuccess, boundStoreFound, ]); return (

{binding ? t("chat.memoryBind.descBound", { topK: binding.topK ?? 5 }) : t("chat.memoryBind.descUnbound")}

{binding && (
{ const n = parseInt(e.target.value, 10); const clamped = Number.isFinite(n) && n >= 1 && n <= 50 ? n : 5; cfg.updateMemory({ topK: clamped }); }} />
)}
{!binding ? ( { const authoritativeStorageMode = parseKnownStorageMode( stores[0]?.storageMode, ); cfg.setMemory({ memoryStoreName: stores[0]?.memoryStoreName ?? "", ...(authoritativeStorageMode !== null ? { storageMode: authoritativeStorageMode } : {}), scope: { appId: "", tenantId: "", agentId: "", runId: "" }, autoSave: true, topK: 5, }); }} /> ) : ( <> { const rawMode = stores.find( (store) => store.memoryStoreName === v, )?.storageMode; const authoritativeStorageMode = parseKnownStorageMode(rawMode); const runtimeStorageMode = normalizeStorageMode(rawMode); cfg.updateMemory({ memoryStoreName: v, storageMode: authoritativeStorageMode ?? undefined, retrievalMode: resolveRetrievalMode( binding.retrievalMode, runtimeStorageMode, ), }); }} onUnbind={() => cfg.setMemory(undefined)} /> cfg.updateMemory({ retrievalMode: m })} memoryStoreName={binding.memoryStoreName} scope={binding.scope} /> cfg.updateMemory({ scope: patch })} onAutoSaveChange={(v) => cfg.updateMemory({ autoSave: v })} /> )}
); } /** * 记忆检索模式二选一 + 文件记忆入口。 * - 「语义检索」:服务端每轮向量检索(原行为)。 * - 「文件记忆」:把该范围的服务端文件投影同步到 * 本地镜像目录,在文件上做词法检索,并可「查看记忆文件」浏览目录结构。 */ function RetrievalModeRow(props: { mode: "search" | "local"; storageMode: StorageMode; fileMemoryAllowed: boolean; onChange: (mode: "search" | "local") => void; memoryStoreName: string; scope: { appId: string; tenantId: string; agentId: string; runId: string }; }) { const { mode, storageMode, fileMemoryAllowed, onChange, memoryStoreName, scope, } = props; const { t } = useI18n(); const [filesOpen, setFilesOpen] = useState(false); const scopeComplete = !!scope.appId && !!scope.tenantId && !!scope.agentId && !!scope.runId; // scope 变得不完整(用户清空某字段)时,条件卸载 MemoryFilesDialog 会让 filesOpen // 残留 true;一旦 scope 再次补全对话框会意外弹出。这里同步复位。 useEffect(() => { if (!memoryStoreName || !scopeComplete) setFilesOpen(false); }, [memoryStoreName, scopeComplete]); return (
onChange("search")} /> onChange("local")} />
{mode === "local" ? (

{t("chat.memoryBind.localHint")}

{memoryStoreName && scopeComplete ? ( ) : null}
) : null}
); } function ModeButton(props: { active: boolean; title: string; desc: string; onClick: () => void; disabled?: boolean; }) { return ( ); } /** * 未绑定时的 hero 空态。结构、token、动效与 `MountEmptyState` 一致: * gradient 背景 + dashed primary 边框 + 居中 icon tile + 行动按钮。 */ function MemoryBindEmptyState(props: { stores: ReadonlyArray<{ memoryStoreName: string }>; isLoading: boolean; onBind: () => void; }) { const { stores, isLoading, onBind } = props; const { t } = useI18n(); const hasNoStores = !isLoading && stores.length === 0; return (

{hasNoStores ? t("chat.memoryBind.emptyNoStoresTitle") : t("chat.memoryBind.emptyBindTitle")}

{hasNoStores ? t("chat.memoryBind.emptyNoStoresDesc") : t("chat.memoryBind.emptyBindDesc")}

{hasNoStores ? ( ) : ( )} {!hasNoStores && !isLoading ? (

{t("chat.memoryBind.selectFromExistingPrefix")}{" "} {stores.length} {" "} {t("chat.memoryBind.selectFromExistingSuffix")}

) : null}
); } /** * 已绑定时展示选中的 store —— 与 MountRow 同款 chip:圆角浅 muted 背景 + * 单行 + 末尾删除(解除绑定)。把"切换 store"做成行内 Select,避免再起一行。 */ function MemoryStoreRow(props: { value: string; stores: ReadonlyArray<{ memoryStoreName: string }>; onChange: (v: string) => void; onUnbind: () => void; }) { const { t } = useI18n(); return (
); } /** * 写 scope + autoSave + runId 的配置子区。 * * 视觉对齐 UnifiedRetrievalSection:浅分割线起头,本区共享同一种「次级 * label」节奏(`text-xs font-medium uppercase tracking-wider text-muted-foreground`)。 */ function MemoryBindingForm(props: { memoryStoreName: string; exactReadScope: boolean; appId: string; tenantId: string; agentId: string; runId: string; autoSave: boolean; autoSaveAllowed: boolean; fileAutoSave: boolean; onScopeChange: (patch: { appId?: string; tenantId?: string; agentId?: string; runId?: string; }) => void; onAutoSaveChange: (v: boolean) => void; }) { const { t } = useI18n(); return (

{props.exactReadScope ? ( t("chat.memoryBind.exactReadScope") ) : ( <> {t("chat.memoryBind.writeScopeDesc")}{" "} * {t("chat.memoryBind.writeScopeDescSuffix")} )}

props.onScopeChange({ appId: s.appId ?? "", tenantId: s.tenantId ?? "", agentId: s.agentId ?? "", runId: s.runId ?? "", }) } />
props.onScopeChange({ appId: v })} /> props.onScopeChange({ tenantId: v })} />
props.onScopeChange({ agentId: v })} />

{props.fileAutoSave ? t("chat.memoryBind.autoSaveFilememDesc") : t("chat.memoryBind.autoSaveDesc")}

); } function ScopeField(props: { label: string; value: string; onChange: (v: string) => void; }) { const id = useId(); const invalid = !props.value; return (
props.onChange(e.target.value)} aria-invalid={invalid} className={cn("h-9", invalid && "border-[hsl(var(--destructive))]")} />
); } function RunIdField({ runId }: { runId: string }) { const { t } = useI18n(); const [copied, setCopied] = useState(false); async function handleCopy() { if (!runId) return; try { await navigator.clipboard.writeText(runId); setCopied(true); toast.success(t("chat.memoryBind.runIdCopied")); setTimeout(() => setCopied(false), 1500); } catch { toast.error(t("chat.memoryBind.runIdCopyFailed")); } } return (
{t("chat.memoryBind.runIdAuto")}
{runId || "—"}
); }