"use client"; import { useEffect, useId, useMemo, useRef, useState, type ReactNode, } from "react"; import { usePathname, useRouter, useSearchParams } from "next/navigation"; import { Bot, Check, ChevronDown, ChevronsUpDown, ChevronUp, MessageSquare, RotateCcw, } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Card, CardContent } from "@/components/ui/card"; import { Command, CommandGroup, CommandInput, CommandItem, CommandList, } from "@/components/ui/command"; import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { buildMemoryScope } from "@/lib/memory"; import { clearRecentMemoryScopes, readRecentMemoryScopes, rememberRecentMemoryScope, } from "@/lib/memory-scope-history"; import { useAllMemoryStoreScopes } from "@/hooks/use-memory-store-scopes"; import { memoryScopeNavigationParams } from "@/lib/memory-navigation"; import { MEMORY_RANGE_FIELDS, normalizeMemoryRange, memoryRangeOptions, } from "@/lib/memory-range"; import { cn } from "@/lib/utils"; import { useI18n } from "@/i18n/i18n-context"; import type { MessageKey, TranslateFn } from "@/i18n/i18n-context"; import { useDataScopeKey } from "@/providers/runtime-context-provider"; import type { MemoryScope } from "@/types/memory"; import { scopeWithSelection, type ScopeLevel } from "@/lib/scope-hierarchy"; const FIELD_KEYS: Array<{ key: keyof MemoryScope; labelKey: "app" | "tenant" | "agent" | "run"; placeholderKey: | "appPlaceholder" | "tenantPlaceholder" | "agentPlaceholder" | "runPlaceholder"; }> = [ { key: "appId", labelKey: "app", placeholderKey: "appPlaceholder" }, { key: "tenantId", labelKey: "tenant", placeholderKey: "tenantPlaceholder" }, { key: "agentId", labelKey: "agent", placeholderKey: "agentPlaceholder" }, { key: "runId", labelKey: "run", placeholderKey: "runPlaceholder" }, ]; const WILDCARD_SCOPE: MemoryScope = { appId: "*", tenantId: "*", agentId: "*", runId: "*", }; const NO_SCOPES: MemoryScope[] = []; const ALL_CHILDREN_KEY: Record = { app: "memory.scopeHierarchy.allApps", tenant: "memory.scopeHierarchy.allTenants", agent: "memory.scopeHierarchy.allAgents", run: "memory.scopeHierarchy.allRuns", }; type RecentMemoryScopeStorage = Pick< Storage, "getItem" | "setItem" | "removeItem" >; const unavailableLocalStorage: RecentMemoryScopeStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {}, }; function getLocalStorage(): RecentMemoryScopeStorage { try { return window.localStorage; } catch { return unavailableLocalStorage; } } export function memoryScopeIdentity(scope: MemoryScope): string { return JSON.stringify([ scope.appId, scope.tenantId ?? "", scope.agentId ?? "", scope.runId ?? "", ]); } export function isMemoryScopeSelected( scope: MemoryScope, currentScope: MemoryScope, ): boolean { return memoryScopeIdentity(scope) === memoryScopeIdentity(currentScope); } export function normalizeMemoryScopeForApply( scope: MemoryScope, ): MemoryScope | null { return normalizeMemoryRange(scope); } export function MemoryScopeBar({ variant = "all", allowScopeDiscovery = true, allowIndependentSelection = false, }: { variant?: "all" | "agent" | "session"; allowScopeDiscovery?: boolean; allowIndependentSelection?: boolean; }) { const { t } = useI18n(); const instanceId = useId(); const visibleFields = FIELD_KEYS.filter(({ key }) => variant === "agent" ? key !== "runId" : variant === "session" ? key === "runId" : true, ); const FIELDS = visibleFields.map((f) => ({ key: f.key, label: t(`memory.scopeField.${f.labelKey}`), placeholder: t(`memory.scopeBar.${f.placeholderKey}`), })); const router = useRouter(); const pathname = usePathname(); const searchParams = useSearchParams(); const dataScopeKey = useDataScopeKey(); const searchParamsString = searchParams.toString(); const currentScope = useMemo( () => normalizeMemoryRange( buildMemoryScope(new URLSearchParams(searchParamsString)), ) ?? WILDCARD_SCOPE, [searchParamsString], ); const [expanded, setExpanded] = useState(false); const [draft, setDraft] = useState(currentScope); const [error, setError] = useState(null); const storeName = pathname.split("/").filter(Boolean)[1]; const recentScopeId = storeName ? JSON.stringify([dataScopeKey, storeName]) : null; const [recentState, setRecentState] = useState<{ scopeId: string | null; scopes: MemoryScope[]; }>({ scopeId: recentScopeId, scopes: [] }); const recentScopes = recentState.scopeId === recentScopeId ? recentState.scopes : NO_SCOPES; // Hydrate browser history separately from the online inventory. Carrying // the composite identity in state prevents one render of the old runtime or // store while this effect catches up after a route/context switch. useEffect(() => { if (!recentScopeId || !storeName) { setRecentState({ scopeId: recentScopeId, scopes: [] }); return; } setRecentState({ scopeId: recentScopeId, scopes: readRecentMemoryScopes( getLocalStorage(), dataScopeKey, storeName, ), }); }, [dataScopeKey, recentScopeId, storeName]); // Make “All” explicit in bookmarks without discarding search or page settings. useEffect(() => { if (!storeName || pathname.includes("/create")) return; const sp = new URLSearchParams(searchParamsString); const range = buildMemoryScope(sp); // Wiki URL cleanup belongs to the layout, which also mounts when this // picker is hidden in a collapsed sidebar. if (variant === "session" || pathname.endsWith("/wiki")) return; if (MEMORY_RANGE_FIELDS.some((key) => sp.get(key) !== range[key])) { for (const key of MEMORY_RANGE_FIELDS) sp.set(key, range[key] ?? "*"); router.replace(`${pathname}?${sp.toString()}`); } }, [searchParamsString, pathname, router, storeName, variant]); // Sync draft from URL whenever the URL changes; typing into the // expanded inputs is the only thing that should diverge draft from URL. useEffect(() => { setDraft((prev) => isMemoryScopeSelected(prev, currentScope) ? prev : currentScope, ); setError(null); }, [currentScope]); // Pull real scope tuples only for storage modes that expose ListMemoryScopes. // Writable filemem deliberately disables this query and uses manual + local // recent scopes instead; no server-discovered data is implied in that mode. const scopeQuery = useAllMemoryStoreScopes(storeName ?? "", WILDCARD_SCOPE, { enabled: allowScopeDiscovery, }); const knownScopes = scopeQuery.data?.items ?? NO_SCOPES; const knownTruncated = scopeQuery.data?.truncated ?? false; function applyScope(scope: MemoryScope): boolean { scope = variant === "agent" ? { ...scope, runId: "*" } : scope; const trimmed = normalizeMemoryScopeForApply(scope); if (!trimmed) { setError(t("memory.scopeBar.appRequired")); return false; } setError(null); const params = memoryScopeNavigationParams(searchParamsString, trimmed); if (pathname.endsWith("/wiki")) params.delete("runId"); if (recentScopeId && storeName) { setRecentState({ scopeId: recentScopeId, scopes: rememberRecentMemoryScope( getLocalStorage(), dataScopeKey, storeName, trimmed, ), }); } router.replace(`${pathname}?${params.toString()}`); return true; } function applyDraft() { if (applyScope(draft)) { setExpanded(false); } } function resetScope() { const reset = variant === "session" ? { ...currentScope, runId: "*" } : WILDCARD_SCOPE; setDraft(reset); setError(null); const params = memoryScopeNavigationParams(searchParamsString, reset); if (pathname.endsWith("/wiki")) params.delete("runId"); router.replace(`${pathname}?${params.toString()}`); } function clearRecentScopes() { if (!recentScopeId || !storeName) return; clearRecentMemoryScopes(getLocalStorage(), dataScopeKey, storeName); setRecentState({ scopeId: recentScopeId, scopes: [] }); } function updateField(key: keyof MemoryScope, value: string) { if (variant === "agent") { setDraft((prev) => scopeWithSelection(prev, key, value)); } else if (key === "appId") { setDraft((prev) => ({ ...prev, appId: value })); } else { setDraft((prev) => ({ ...prev, [key]: value || undefined })); } } function pickFromList(scope: MemoryScope) { if (!applyScope(scope)) return; setDraft(normalizeMemoryRange(scope) ?? scope); setExpanded(false); } function renderPicker( { key, labelKey }: (typeof FIELD_KEYS)[number], overrides: Partial = {}, ) { const index = FIELD_KEYS.findIndex((field) => field.key === key); const missingAncestor = FIELD_KEYS.slice(0, index).find( ({ key }) => currentScope[key] === "*", ); const selectionBlocked = !allowIndependentSelection && !!missingAncestor; const disabled = selectionBlocked && currentScope[key] === "*"; return ( { if (selectionBlocked && value !== "*") return; if (value !== currentScope[key]) pickFromList( allowIndependentSelection || selectionBlocked ? { ...currentScope, [key]: value } : scopeWithSelection(currentScope, key, value), ); }} onClearRecent={clearRecentScopes} onRefresh={() => scopeQuery.refetch()} allowCustomValue={variant !== "all"} {...overrides} t={t} /> ); } if (variant === "agent") { const agentLabel = currentScope.agentId !== "*" ? currentScope.agentId : t("memory.scopeHierarchy.allAgents"); const parentLabel = [ currentScope.appId === "*" ? t("memory.scopeHierarchy.allApps") : currentScope.appId, currentScope.tenantId === "*" ? t("memory.scopeHierarchy.allTenants") : currentScope.tenantId, ].join(" / "); return (
{renderPicker(FIELD_KEYS[2], { triggerClassName: "h-auto min-h-16 gap-2.5 rounded-xl border-border/70 bg-background px-2.5 py-2.5 shadow-none hover:border-primary/30 hover:bg-accent/40", triggerContent: ( <> {agentLabel} {parentLabel} ), header: (
{t("memory.scopeBar.switchAgent")}
{FIELD_KEYS.slice(0, 2).map((field) => renderPicker(field))}
), })}
); } if (variant === "session") { const selected = currentScope.runId !== "*" ? currentScope.runId : t( pathname.endsWith("/messages") ? "memory.scopeBar.chooseSession" : "memory.scopeHierarchy.allRuns", ); return (
{renderPicker(FIELD_KEYS[3], { triggerClassName: "h-9 rounded-lg border-border/70 bg-background shadow-none hover:border-primary/30", triggerContent: ( <> {selected} ), // The selector stays reachable to explain which parent is missing. })}
); } return (
{visibleFields.map((field) => renderPicker(field))}
{/* Expanded editor for hand-tuning a custom scope (write ops still need a precise scope, so we keep input-by-input editing as the escape hatch for tuples not yet in the engine). */} {expanded && (
{FIELDS.map(({ key, label, placeholder }) => (
updateField(key, e.target.value)} className="h-8 text-sm" />
))}
{error ? (

{error}

) : (

{t("memory.scopeBar.writeHint")}

)}
)}
); } interface ScopeFieldPickerProps { triggerContent?: ReactNode; triggerClassName?: string; header?: ReactNode; allowCustomValue?: boolean; label: string; allLabel: string; value: string; disabled: boolean; clearOnly?: boolean; disabledHint?: string; knownValues: string[]; recentValues: string[]; discoveryEnabled: boolean; isLoading: boolean; isError: boolean; isFetching: boolean; truncated: boolean; onPick: (value: string) => void; onClearRecent: () => void; onRefresh: () => void; t: TranslateFn; } export function ScopeFieldPicker({ triggerContent, triggerClassName, header, allowCustomValue = false, label, allLabel, value, disabled, clearOnly = false, disabledHint, knownValues, recentValues, discoveryEnabled, isLoading, isError, isFetching, truncated, onPick, onClearRecent, onRefresh, t, }: ScopeFieldPickerProps) { const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const searchInputRef = useRef(null); const matchesSearch = (candidate: string) => candidate.toLocaleLowerCase().includes(search.trim().toLocaleLowerCase()); const visibleKnown = clearOnly ? [] : knownValues.filter(matchesSearch); const visibleRecent = (clearOnly ? [] : recentValues) .filter( (candidate) => !knownValues.includes(candidate) && candidate !== value, ) .filter(matchesSearch); const showCurrent = !clearOnly && value !== "*" && !knownValues.includes(value) && matchesSearch(value); const selectedLabel = value === "*" ? allLabel : value; function pick(candidate: string) { onPick(candidate); setOpen(false); setSearch(""); } function option(candidate: string, text: string = candidate) { return ( pick(candidate)} className="min-h-9 text-xs" > {text} ); } return ( { setOpen(next); if (!next) setSearch(""); }} > { if (!clearOnly) { event.preventDefault(); searchInputRef.current?.focus(); } }} className="w-[min(360px,calc(100vw-2rem))] overflow-hidden rounded-xl p-0 shadow-lg" > {header} {clearOnly ? (

{disabledHint}

) : ( )} {(matchesSearch(allLabel) || search.trim() === "*") && ( {option("*", allLabel)} )} {showCurrent && ( {option(value)} )} {visibleRecent.length > 0 && ( {visibleRecent.map((candidate) => option(candidate))} )} {visibleKnown.length > 0 && ( {visibleKnown.map((candidate) => option(candidate))} )} {!clearOnly && !showCurrent && visibleKnown.length === 0 && visibleRecent.length === 0 && !isLoading && (

{t( search ? "memory.scopeBar.noMatches" : "memory.scopeBar.noOptions", )}

)} {allowCustomValue && !clearOnly && search.trim() && search.trim() !== "*" && !knownValues.includes(search.trim()) && !recentValues.includes(search.trim()) && search.trim() !== value && ( {option( search.trim(), t("memory.scopeBar.useId", { value: search.trim() }), )} )}
{!clearOnly && (
{discoveryEnabled && (isLoading || isError || truncated) && (

{t( isLoading ? "memory.common.querying" : isError ? "memory.scopeBar.optionsFailed" : "memory.scopeBar.optionsIncomplete", )}

)}
{recentValues.length > 0 && ( )} {discoveryEnabled && ( )}
)}
); }