"use client"; import { useEffect, useMemo, useRef } from "react"; import { useForm } from "react-hook-form"; import { zodResolver } from "@hookform/resolvers/zod"; import { Info, RotateCcw, Pencil } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { Form } from "@/components/ui/form"; import type { FilterBuilderHandle } from "@/components/retrieval/filter-builder"; import { RetrievalParamsFields } from "@/components/retrieval/retrieval-params-fields"; import { retrievalSchema, type RetrievalInput } from "@/schemas/retrieval"; import { DEFAULT_PER_KB_TOP_K, useChatConfig, type MountItem, } from "@/components/chat/chat-config-context"; import type { ChatRetrievalConfig } from "@/hooks/use-chat-history"; import { useI18n } from "@/i18n/i18n-context"; import type { KnowledgeBase } from "@/types/knowledge-base"; /* -------------------------------------------------------------------------- */ /* Pure helpers (also unit-tested in __tests__/mount-retrieval-dialog.test.tsx) /* -------------------------------------------------------------------------- */ /** A mount is in "inherit-from-global" mode iff it has no per-KB override at all. */ export function isInheritMode(mount: MountItem): boolean { return mount.retrieval === undefined && mount.topK === undefined; } /** * Compute the initial form snapshot when the user explicitly switches the * mount from inherit-mode to custom-mode. Mount-local override (when present) * wins over the global session defaults; otherwise the global defaults are * shallow-copied so subsequent form mutation cannot leak back into the * shared `cfg.retrieval` reference. */ export function deriveCustomDefaults( mount: MountItem, globalRetrieval: ChatRetrievalConfig, globalPerKbTopK: number, ): { retrieval: ChatRetrievalConfig; topK: number } { return { retrieval: mount.retrieval ?? { ...globalRetrieval }, topK: mount.topK ?? globalPerKbTopK, }; } /** * Multimodal KBs only have one supported MODEL-rerank model: `qwen3-vl-rerank` * served by the Bailian provider. RRF / WEIGHT remain unrestricted because * they don't load a rerank model at all. */ export function lockMultimodalRerank( retrieval: ChatRetrievalConfig, isMultimodal: boolean, ): ChatRetrievalConfig { if (!isMultimodal) return retrieval; if (retrieval.rerankType !== "MODEL") return retrieval; return { ...retrieval, modelProvider: "bailian", modelName: "qwen3-vl-rerank", }; } /* -------------------------------------------------------------------------- */ /* Component */ /* -------------------------------------------------------------------------- */ /** Subset of `RetrievalInput` keys persisted back to a `ChatRetrievalConfig`. */ const RETRIEVAL_CFG_KEYS = [ "searchType", "rerankType", "rrfK", "rrfDenseWeight", "rrfFullTextWeight", "weightDense", "weightFullText", "modelName", "modelProvider", ] as const satisfies readonly (keyof RetrievalInput & keyof ChatRetrievalConfig)[]; export interface MountRetrievalDialogProps { mount: MountItem; knowledgeBase: KnowledgeBase; open: boolean; onOpenChange: (open: boolean) => void; } /** * Per-KB retrieval parameter editor. Opens from the gear icon on a `MountRow`. * * Behavior contract: * - When `mount.retrieval` and `mount.topK` are both undefined the form * renders read-only and the header advertises 「当前:继承全局默认」. * Switching to custom-mode requires an explicit click on * 「使用自定义配置」 — no implicit drift. * - In custom-mode, the form is seeded from the current global defaults * (or the existing override) and auto-commits on field blur via * `cfg.updateMount(...)`. * - Multimodal KBs lock the MODEL rerank to `qwen3-vl-rerank` via * `lockMultimodalRerank`; the rest of the form is unconstrained. * - Metadata FilterBuilder is *not* rendered here (we deliberately skip * `knowledgeBase` to `RetrievalParamsFields` to suppress it). */ export function MountRetrievalDialog({ mount, knowledgeBase, open, onOpenChange, }: MountRetrievalDialogProps) { const { t } = useI18n(); const cfg = useChatConfig(); const inherit = isInheritMode(mount); const isMultimodal = !!knowledgeBase.multimodal; // FilterBuilder is structurally required by RetrievalParamsFields' API even // though we don't render it here. const filterRef = useRef(null); // Effective values used to populate the form: mount override falls back to // the global session defaults so the UI shows what would actually be sent // for this KB even in inherit-mode. const effective = useMemo( () => deriveCustomDefaults(mount, cfg.retrieval, cfg.perKbTopK), [mount, cfg.retrieval, cfg.perKbTopK], ); const form = useForm({ resolver: zodResolver(retrievalSchema), defaultValues: { knowledgeBaseName: knowledgeBase.knowledgeBaseName, queryType: "TEXT" as const, query: "__mount_dialog_placeholder__", subspace: [], topK: effective.topK, searchType: effective.retrieval.searchType ?? [ "DENSE_VECTOR", "FULL_TEXT", ], rerankType: effective.retrieval.rerankType, rrfK: effective.retrieval.rrfK, rrfDenseWeight: effective.retrieval.rrfDenseWeight, rrfFullTextWeight: effective.retrieval.rrfFullTextWeight, weightDense: effective.retrieval.weightDense, weightFullText: effective.retrieval.weightFullText, modelName: effective.retrieval.modelName, modelProvider: effective.retrieval.modelProvider, }, }); // RHF does not observe defaultValues after mount; mirror context updates // and inherit/custom transitions through reset() so the form always // reflects what would actually be sent. useEffect(() => { form.reset({ knowledgeBaseName: knowledgeBase.knowledgeBaseName, queryType: "TEXT" as const, query: "__mount_dialog_placeholder__", subspace: [], topK: effective.topK, searchType: effective.retrieval.searchType ?? [ "DENSE_VECTOR", "FULL_TEXT", ], rerankType: effective.retrieval.rerankType, rrfK: effective.retrieval.rrfK, rrfDenseWeight: effective.retrieval.rrfDenseWeight, rrfFullTextWeight: effective.retrieval.rrfFullTextWeight, weightDense: effective.retrieval.weightDense, weightFullText: effective.retrieval.weightFullText, modelName: effective.retrieval.modelName, modelProvider: effective.retrieval.modelProvider, }); // form is stable; we want this to fire whenever the effective payload // changes, including when the user toggles inherit -> custom. // eslint-disable-next-line react-hooks/exhaustive-deps }, [effective, knowledgeBase.knowledgeBaseName]); // Persist the current form snapshot back to the mount as a custom override. // No-op while we're still in inherit-mode (the form is read-only then). const commit = () => { if (inherit) return; const values = form.getValues(); let next: ChatRetrievalConfig = {}; for (const k of RETRIEVAL_CFG_KEYS) { const v = values[k]; if (v !== undefined && !(Array.isArray(v) && v.length === 0)) { (next as Record)[k] = v; } } next = lockMultimodalRerank(next, isMultimodal); cfg.updateMount(mount.id, { retrieval: next, topK: typeof values.topK === "number" && values.topK >= 0 ? values.topK : DEFAULT_PER_KB_TOP_K, }); }; // When the user switches to MODEL on a multimodal KB, immediately lock the // provider/model. Mirrors the unified-section auto-fill but with the // multimodal constraint applied. const watchedRerank = form.watch("rerankType"); useEffect(() => { if (inherit) return; if (watchedRerank !== "MODEL") return; let touched = false; if (isMultimodal) { if (form.getValues("modelProvider") !== "bailian") { form.setValue("modelProvider", "bailian"); touched = true; } if (form.getValues("modelName") !== "qwen3-vl-rerank") { form.setValue("modelName", "qwen3-vl-rerank"); touched = true; } } else { if (!form.getValues("modelProvider")) { form.setValue("modelProvider", "bailian"); touched = true; } if (!form.getValues("modelName")) { form.setValue("modelName", "gte-rerank-v2"); touched = true; } } if (touched) commit(); // eslint-disable-next-line react-hooks/exhaustive-deps }, [watchedRerank, isMultimodal, inherit]); const handleSwitchToCustom = () => { const seeds = deriveCustomDefaults(mount, cfg.retrieval, cfg.perKbTopK); const sealed = lockMultimodalRerank(seeds.retrieval, isMultimodal); cfg.updateMount(mount.id, { retrieval: sealed, topK: seeds.topK }); }; const handleResetToDefault = () => { cfg.resetMountRetrieval(mount.id); }; return ( {t("chat.retrievalDialog.title")} {knowledgeBase.knowledgeBaseName} {isMultimodal ? ( {t("chat.retrievalDialog.multimodalBadge")} ) : null}
{inherit ? ( {t("chat.retrievalDialog.inheritCurrentPrefix")} {t("chat.retrievalDialog.inheritLabel")} {t("chat.retrievalDialog.inheritSuffix")} ) : ( {t("chat.retrievalDialog.inheritCurrentPrefix")} {t("chat.retrievalDialog.customLabel")} {t("chat.retrievalDialog.customSuffix")} )}
{isMultimodal && !inherit && form.watch("rerankType") === "MODEL" ? (
{t("chat.retrievalDialog.multimodalLockPrefix")}{" "} qwen3-vl-rerank {t("chat.retrievalDialog.multimodalLockSuffix")}
) : null}
e.preventDefault()} onBlur={commit} // 继承模式:整个表单只读 + 灰态预览。 className={ "space-y-4 " + (inherit ? "pointer-events-none select-none opacity-60" : "") } aria-disabled={inherit} >
{inherit ? ( ) : ( )}
); }