RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
/*
* Copyright 2026 The InfiniFlow Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Button } from '@/components/ui/button';
import {
Command,
CommandEmpty,
CommandGroup,
CommandInput,
CommandItem,
CommandList,
CommandSeparator,
} from '@/components/ui/command';
import { MultiSelectOptionType } from '@/components/ui/multi-select';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { Separator } from '@/components/ui/separator';
import {
useAllTestingResult,
useChunkIsTesting,
useSelectTestingResult,
} from '@/hooks/use-knowledge-request';
import { cn } from '@/lib/utils';
import { CheckIcon, ChevronDown, Files, XIcon } from 'lucide-react';
import { useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
interface IProps {
onTesting(documentIds: string[]): void;
setSelectedDocumentIds(documentIds: string[]): void;
selectedDocumentIds: string[];
setLoading?: (loading: boolean) => void;
}
const RetrievalDocuments = ({
onTesting,
selectedDocumentIds,
setSelectedDocumentIds,
setLoading,
}: IProps) => {
const { t } = useTranslation();
const { documents: documentsAll } = useAllTestingResult();
const { documents } = useSelectTestingResult();
const isTesting = useChunkIsTesting();
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
useEffect(() => {
if (isTesting) {
setLoading?.(true);
} else {
setLoading?.(false);
}
}, [isTesting, setLoading]);
const latestDocuments =
documentsAll?.length > documents?.length ? documentsAll : documents;
// Keep the last non-empty list so the popover anchor is not unmounted
// while a new testing request is pending.
const documentsRef = useRef(latestDocuments);
if (latestDocuments?.length) {
documentsRef.current = latestDocuments;
}
const useDocuments = documentsRef.current;
const [selectedValues, setSelectedValues] =
useState<string[]>(selectedDocumentIds);
useEffect(() => {
setSelectedValues(selectedDocumentIds);
}, [selectedDocumentIds]);
const multiOptions = useMemo(() => {
if (!useDocuments || !useDocuments.length) {
return [];
}
return useDocuments?.map((item) => {
return {
label: item.doc_name,
value: item.doc_id,
disabled: item.doc_name === 'Disabled User',
// suffix: (
// <div className="flex justify-between gap-3 ">
// <div>{item.count}</div>
// <div>
// <Eye />
// </div>
// </div>
// ),
};
});
}, [useDocuments]);
// The last selection handed to the parent. Compared on close so a re-render
// with fresh props cannot make us fire the search twice.
const committedIdsRef = useRef<string[]>(selectedDocumentIds);
useEffect(() => {
committedIdsRef.current = selectedDocumentIds;
}, [selectedDocumentIds]);
const isSelectionChanged = (value: string[]) => {
const committed = committedIdsRef.current;
return (
value.length !== committed.length ||
value.some((id) => !committed.includes(id))
);
};
const commitSelection = (value: string[]) => {
if (!isSelectionChanged(value)) {
return;
}
committedIdsRef.current = value;
setSelectedDocumentIds(value);
onTesting(value);
};
// While the popover is open, interactions only update the draft; the search
// is re-triggered once it blurs and the draft differs from the committed ids.
const handleOpenChange = (open: boolean) => {
if (!open) {
commitSelection(selectedValues);
}
setIsPopoverOpen(open);
};
const handleTogglePopover = () => {
handleOpenChange(!isPopoverOpen);
};
const onValueChange = (value: string[]) => {
setSelectedValues(value);
if (!isPopoverOpen) {
commitSelection(value);
}
// handleDatasetSelectChange(value, field.onChange);
};
const handleClear = () => {
onValueChange([]);
};
const handleInputKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
if (event.key === 'Enter') {
setIsPopoverOpen(true);
} else if (event.key === 'Backspace' && !event.currentTarget.value) {
const newSelectedValues = [...selectedValues];
newSelectedValues.pop();
onValueChange(newSelectedValues);
}
};
const toggleOption = (option: string) => {
const newSelectedValues = selectedValues.includes(option)
? selectedValues.filter((value) => value !== option)
: [...selectedValues, option];
onValueChange(newSelectedValues);
};
return (
<Popover open={isPopoverOpen} onOpenChange={handleOpenChange}>
<PopoverTrigger asChild>
{useDocuments?.length > 0 && (
<Button
onClick={handleTogglePopover}
className={cn(
'flex w-full p-1 rounded-md text-base text-text-primary border min-h-10 h-auto items-center justify-between bg-inherit hover:bg-inherit [&_svg]:pointer-events-auto',
)}
>
<div className="flex justify-between items-center w-full">
<div className="flex flex-wrap items-center gap-2">
<Files />
<span>
{selectedDocumentIds?.length ?? 0}/{useDocuments?.length ?? 0}
</span>
{t('knowledgeDetails.subbarFiles')}
</div>
<div className="flex items-center justify-between">
<XIcon
className="h-4 mx-2 cursor-pointer text-muted-foreground"
onClick={(event) => {
event.stopPropagation();
handleClear();
}}
/>
<Separator
orientation="vertical"
className="flex min-h-6 h-full"
/>
<ChevronDown className="h-4 mx-2 cursor-pointer text-muted-foreground" />
</div>
</div>
</Button>
)}
</PopoverTrigger>
<PopoverContent
className="w-auto p-0"
align="start"
onEscapeKeyDown={() => handleOpenChange(false)}
>
<Command>
<CommandInput
placeholder={t('common.search')}
onKeyDown={handleInputKeyDown}
/>
<CommandList>
<CommandEmpty>{t('common.noResults')}</CommandEmpty>
<CommandGroup>
{!multiOptions.some((x) => 'options' in x) &&
(multiOptions as unknown as MultiSelectOptionType[]).map(
(option) => {
const isSelected = selectedValues.includes(option.value);
return (
<CommandItem
key={option.value}
onSelect={() => {
if (option.disabled) return false;
toggleOption(option.value);
}}
className={cn('cursor-pointer', {
'cursor-not-allowed text-text-disabled':
option.disabled,
})}
>
<div
className={cn(
'mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary',
isSelected
? 'bg-primary '
: 'opacity-50 [&_svg]:invisible',
{ 'text-primary-foreground': !option.disabled },
{ 'text-text-disabled': option.disabled },
)}
>
<CheckIcon className="h-4 w-4" />
</div>
{option.icon && (
<option.icon
className={cn('mr-2 h-4 w-4 ', {
'text-text-disabled': option.disabled,
'text-muted-foreground': !option.disabled,
})}
/>
)}
<span
className={cn({
'text-text-disabled': option.disabled,
})}
>
{option.label}
</span>
{option.suffix && (
<span
className={cn({
'text-text-disabled': option.disabled,
})}
>
{option.suffix}
</span>
)}
</CommandItem>
);
},
)}
</CommandGroup>
<CommandSeparator />
<CommandGroup>
<div className="flex items-center justify-between">
{selectedValues.length > 0 && (
<>
<CommandItem
onSelect={handleClear}
className="flex-1 justify-center cursor-pointer"
>
{t('common.clear')}
</CommandItem>
<Separator
orientation="vertical"
className="flex min-h-6 h-full"
/>
</>
)}
<CommandItem
onSelect={() => handleOpenChange(false)}
className="flex-1 justify-center cursor-pointer max-w-full"
>
{t('common.close')}
</CommandItem>
</div>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
};
export default RetrievalDocuments;