"use client"; import { useEffect, useRef } from "react"; import { useSearchParams } from "next/navigation"; import { useChatConfig } from "@/components/chat/chat-config-context"; import { useWiki } from "@/hooks/use-wikis"; import { decideChatScopeHydration, parseChatScopeEntry, type ChatScopeEntry, } from "@/lib/chat-scope-entry"; import { resolveRetrievalMode } from "@/lib/memory-storage-mode"; export interface ChatScopeEntryHydratorProps { activeSessionId: string | null; messageCount: number; activeInstanceReady: boolean; projectIdentity: string; } export function ChatScopeEntryHydrator(props: ChatScopeEntryHydratorProps) { const searchParams = useSearchParams(); const entry = parseChatScopeEntry( new URLSearchParams(searchParams.toString()), ); const latestChatRef = useRef({ activeSessionId: props.activeSessionId, messageCount: props.messageCount, }); latestChatRef.current = { activeSessionId: props.activeSessionId, messageCount: props.messageCount, }; const identity = JSON.stringify([ props.projectIdentity, entry ? [ entry.memoryStoreName, entry.storageMode, entry.scope.appId, entry.scope.tenantId, entry.scope.agentId, entry.scope.runId, entry.wiki, ] : null, ]); const handledRef = useRef({ identity, handled: false }); if (handledRef.current.identity !== identity) { handledRef.current = { identity, handled: false }; } if (!props.activeInstanceReady || !entry) return null; return ( ); } function ReadyChatScopeEntryHydrator({ entry, identity, latestChatRef, handledRef, }: { entry: ChatScopeEntry; identity: string; latestChatRef: { current: { activeSessionId: string | null; messageCount: number }; }; handledRef: { current: { identity: string; handled: boolean } }; }) { const cfg = useChatConfig(); const query = useWiki(entry.memoryStoreName, entry.scope); useEffect(() => { if (query.status === "pending") return; if (handledRef.current.identity !== identity) return; const latestChat = latestChatRef.current; const decision = decideChatScopeHydration({ entry, activeSessionId: latestChat.activeSessionId, messageCount: latestChat.messageCount, wikiReady: query.data?.status === "ready", handled: handledRef.current.handled, }); handledRef.current.handled = true; if (decision.action === "ignore") return; cfg.setMemory({ memoryStoreName: entry.memoryStoreName, storageMode: entry.storageMode, scope: entry.scope, autoSave: true, topK: 5, retrievalMode: resolveRetrievalMode(undefined, entry.storageMode), }); cfg.setWikiEnabled(decision.enableWiki); }, [ cfg, entry, handledRef, identity, latestChatRef, query.data?.status, query.status, ]); return null; }