"use client"; import { useMemo, useState } from "react"; import { ChevronsUpDown } from "lucide-react"; import { Button } from "@/components/ui/button"; import { Command, CommandInput, CommandList } from "@/components/ui/command"; import { Popover, PopoverContent, PopoverTrigger, } from "@/components/ui/popover"; import { useAllMemoryStoreScopes } from "@/hooks/use-memory-store-scopes"; import { scopeLabel } from "@/lib/memory"; import { cn } from "@/lib/utils"; import { useI18n, type MessageKey } from "@/i18n/i18n-context"; import type { MemoryScope } from "@/types/memory"; import { ScopeHierarchyPicker } from "./scope-hierarchy-picker"; import type { ScopeLevel } from "@/lib/scope-hierarchy"; const WILDCARD: MemoryScope = { appId: "*", tenantId: "*", agentId: "*", runId: "*", }; /** Stable identity so the memoized filter isn't invalidated every render. */ const NO_SCOPES: MemoryScope[] = []; /** How many rows to render at once, and how many more each "show more" adds. */ export const SCOPE_WINDOW_SIZE = 100; /** Distance from the bottom (px) at which scrolling grows the window. */ const NEAR_BOTTOM_PX = 64; /** * Case-insensitive substring match over the scope label, where every * whitespace-separated term must hit somewhere — so `ots claude` narrows * across two dimensions without caring about their order. * * We filter here rather than letting cmdk do it because cmdk's default is a * fuzzy subsequence score, and run ids are uuids: almost any short query * finds scattered hex characters in an unrelated tuple, so the "matches" * drown out the real ones. Owning the filter also keeps DOM order equal to * JSX order, which is what lets the window below stay correct. */ export function filterScopes( scopes: readonly MemoryScope[], query: string, ): MemoryScope[] { const terms = query.toLowerCase().split(/\s+/).filter(Boolean); if (terms.length === 0) return [...scopes]; return scopes.filter((scope) => { const label = scopeLabel(scope).toLowerCase(); return terms.every((term) => label.includes(term)); }); } export function isNearListBottom(el: { scrollTop: number; clientHeight: number; scrollHeight: number; }): boolean { return el.scrollHeight - el.scrollTop - el.clientHeight <= NEAR_BOTTOM_PX; } /** * Which message the status bar shows. Windowing and server-side truncation are * independent and, on a big enough store, simultaneous — truncation in fact * implies windowing — so they get a combined message rather than an either/or * that would hide "· 已截断" in the one case it matters. */ export function scopeStatusKey(state: { loading: boolean; error: boolean; hasMore: boolean; truncated: boolean; }): MessageKey { if (state.loading) return "memory.common.querying"; if (state.error) return "memory.scopeCombobox.loadFailed"; if (state.hasMore) { return state.truncated ? "memory.scopeCombobox.windowCountTruncated" : "memory.scopeCombobox.windowCount"; } return state.truncated ? "memory.common.scopeCountTruncated" : "memory.common.scopeCount"; } /** * 通过 ListScopes 拉取某记忆库里真实存在的 scope 元组,供下拉选择。选中后回调 * `onPick(完整 scope)`,由上层决定填哪些字段。对话配置的记忆 scope、Dream 任务 * 的 scope 输入共用它,避免用户手动逐字段敲。 * * scope 多起来时的三件事:列表本身要能滚(见下方 `modal` 注释)、一次只渲染 * 一屏窗口(滚到底或点「显示更多」再追加),以及搜索由本组件负责而不是 cmdk。 */ export function ScopeCombobox({ memoryStoreName, onPick, disabled, placeholder, className, allowPartial = false, currentScope = WILDCARD, maxLevel = "run", }: { memoryStoreName: string | undefined; onPick: (scope: MemoryScope) => void; disabled?: boolean; placeholder?: string; className?: string; allowPartial?: boolean; currentScope?: MemoryScope; maxLevel?: ScopeLevel; }) { const { t } = useI18n(); const [open, setOpen] = useState(false); const [search, setSearch] = useState(""); const [windowSize, setWindowSize] = useState(SCOPE_WINDOW_SIZE); // 只在弹层打开时才查。Dream 创建对话框最多同时挂 20 个 ScopeCombobox, // 抽屉/对话框一打开就全量拉 scope 是白花的往返。 const query = useAllMemoryStoreScopes(memoryStoreName ?? "", WILDCARD, { enabled: open, }); const scopes = query.data?.items ?? NO_SCOPES; const truncated = query.data?.truncated ?? false; const resolvedPlaceholder = placeholder ?? t("memory.scopeCombobox.defaultPlaceholder"); const matches = useMemo(() => filterScopes(scopes, search), [scopes, search]); const shownCount = Math.min(matches.length, windowSize); const hasMore = shownCount < matches.length; const showMore = () => setWindowSize((n) => n + SCOPE_WINDOW_SIZE); const handleOpenChange = (next: boolean) => { setOpen(next); if (!next) { setSearch(""); setWindowSize(SCOPE_WINDOW_SIZE); } }; return ( // `modal` is load-bearing, not decoration. Both call sites live inside a // Radix Dialog (the chat config Sheet / the Dream create dialog), whose // overlay wraps everything in with no // `noIsolation`. That cancels wheel events on any portalled node the // dialog doesn't own — and PopoverContent portals to document.body, so // the list silently refused to scroll and only the first ~10 rows were // ever reachable. `modal` gives the popover its own scroll lock, which // sits on top of react-remove-scroll's lockStack and hands scrolling // back. See components/ui/__tests__/popover-in-dialog.test.ts. { setSearch(v); setWindowSize(SCOPE_WINDOW_SIZE); }} /> { if (hasMore && isNearListBottom(e.currentTarget)) showMore(); }} > { onPick(scope); handleOpenChange(false); }} loading={query.isLoading} error={query.isError} truncated={truncated} onRetry={() => query.refetch()} allowPartial={allowPartial} optionLimit={windowSize} maxLevel={maxLevel} t={t} /> {/* 状态条留在 CommandList 之外:它不属于 [cmdk-list],因此永远不会 被搜索过滤掉或被 cmdk 的排序搬走。 */}
{t( scopeStatusKey({ loading: query.isLoading, error: query.isError, hasMore, truncated, }), // 各 key 只会用到其中一部分占位符,多余的会被 interpolate 忽略。 { shown: shownCount, total: matches.length, count: matches.length, }, )} {hasMore ? ( ) : null}
); }