'use client' import type { DialogContentProps, DialogProps } from '@langgenius/dify-ui/dialog' import type { UseInfiniteQueryResult } from '@tanstack/react-query' import { Button } from '@langgenius/dify-ui/button' import { Checkbox } from '@langgenius/dify-ui/checkbox' import { Combobox, ComboboxCollection, ComboboxEmpty, ComboboxGroup, ComboboxGroupLabel, ComboboxInput, ComboboxInputGroup, ComboboxItem, ComboboxList, ComboboxPopup, ComboboxPortal, ComboboxPositioner, ComboboxStatus, ComboboxTrigger, } from '@langgenius/dify-ui/combobox' import { Dialog, DialogBody, DialogClose, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogHeaderCloseButton, DialogTitle, } from '@langgenius/dify-ui/dialog' import { IconButton } from '@langgenius/dify-ui/icon-button' import { Radio, RadioGroup } from '@langgenius/dify-ui/radio-group' import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query' import { useId, useMemo, useRef, useState } from 'react' import { useTranslation } from 'react-i18next' import { consoleQuery } from '@/service/console' type Scope = 'all' | 'specific' // Legacy knowledge bases (datasets) and KnowledgeFS spaces live in different tables, so // a selection keeps track of which kind each entry is and reports the ids separately. type KnowledgeBaseKind = 'dataset' | 'knowledge_space' type SelectedKb = { id: string; name: string; kind: KnowledgeBaseKind } export type DatasetApiKeyScopeSelection = { datasetIds: string[] knowledgeSpaceIds: string[] } const PICKER_PAGE_SIZE = 20 type DatasetScopeDialogProps = Required> & Pick & { isCreating: boolean createDisabled: boolean // Emits the knowledge-base ids to scope the new key to, split by kind. Both lists empty // means the key can access every knowledge base in the workspace (the "all" scope). onConfirm: (selection: DatasetApiKeyScopeSelection) => void } export function DatasetScopeDialog({ open, finalFocus, onOpenChange, ...props }: DatasetScopeDialogProps) { return ( { if (!nextOpen && props.isCreating) details.cancel() else onOpenChange(nextOpen, details) }} > ) } type PickerPageQuery = Pick< UseInfiniteQueryResult, | 'fetchNextPage' | 'hasNextPage' | 'isError' | 'isFetchNextPageError' | 'isFetchingNextPage' | 'isRefetching' | 'refetch' > // Each picker source pages independently: a failed source shows its own retry, and a source with // more matches offers the next page so every match stays selectable. function PickerPagination({ query, errorLabel, loadMoreLabel, onSettled, }: { query: PickerPageQuery errorLabel: string loadMoreLabel: string // Returns focus to the picker input once the pagination control may have unmounted. onSettled: () => void }) { const { t } = useTranslation(['common']) if (query.isError) { const retry = async () => { await (query.isFetchNextPageError ? query.fetchNextPage() : query.refetch()) onSettled() } return (
{errorLabel}
) } if (!query.hasNextPage) return null return (
) } function DatasetScopeContent({ isCreating, createDisabled, onConfirm, }: Omit) { const { t } = useTranslation(['appApi', 'common']) const scopeId = useId() const { data: knowledgeFsEnabled } = useSuspenseQuery( consoleQuery.features.get.queryOptions({ select: (features) => features.enable_knowledge_fs, }), ) const [scope, setScope] = useState('all') const [selected, setSelected] = useState([]) const [keyword, setKeyword] = useState('') const pickerInputRef = useRef(null) const focusPickerInput = () => pickerInputRef.current?.focus() const datasetsQuery = useInfiniteQuery( consoleQuery.datasets.get.infiniteOptions({ input: (page: number) => ({ query: { page, ...(keyword ? { keyword } : {}) } }), getNextPageParam: (lastPage) => (lastPage.has_more ? lastPage.page + 1 : undefined), initialPageParam: 1, enabled: scope === 'specific', staleTime: 0, refetchOnMount: 'always', }), ) const datasets = useMemo( () => (datasetsQuery.data?.pages ?? []).flatMap((page) => page.data.map(({ id, name }) => ({ id, name, kind: 'dataset' })), ), [datasetsQuery.data], ) // KnowledgeFS spaces come from their own list endpoint, which only exists when the // workspace has KnowledgeFS enabled. const knowledgeSpacesQuery = useInfiniteQuery({ ...consoleQuery.knowledgeFs.spaces.get.infiniteOptions({ input: (pageParam) => ({ query: { limit: PICKER_PAGE_SIZE, page: pageParam, ...(keyword ? { query: keyword } : {}), }, }), getNextPageParam: (lastPage) => (lastPage.has_more ? lastPage.page + 1 : undefined), initialPageParam: 1, }), enabled: scope === 'specific' && knowledgeFsEnabled, }) const knowledgeSpaces = useMemo( () => (knowledgeSpacesQuery.data?.pages ?? []) .flatMap((page) => page.data) .map((space) => ({ kind: 'knowledge_space', id: space.control_space_id, name: space.technical_summary?.name ?? space.control_space_id, })), [knowledgeSpacesQuery.data], ) const pickerItems = useMemo(() => [...knowledgeSpaces, ...datasets], [knowledgeSpaces, datasets]) const isLoading = datasetsQuery.isLoading || (knowledgeFsEnabled && knowledgeSpacesQuery.isLoading) // "No data" is only true once every enabled lookup succeeded; a failed lookup gets its own // error state so it is not mistaken for an empty search. const hasLookupError = datasetsQuery.isError || (knowledgeFsEnabled && knowledgeSpacesQuery.isError) const selectedIds = useMemo(() => new Set(selected.map((kb) => kb.id)), [selected]) const addLabel = t(($) => $['apiKeyModal.addKnowledgeBase'], { ns: 'appApi' }) const searchLabel = t(($) => $['apiKeyModal.searchKnowledgeBases'], { ns: 'appApi' }) const removeKb = (id: string) => setSelected((prev) => prev.filter((kb) => kb.id !== id)) const canCreate = !createDisabled && (scope === 'all' || selected.length > 0) const handleConfirm = () => { if (!canCreate || isCreating) return if (scope !== 'specific') { onConfirm({ datasetIds: [], knowledgeSpaceIds: [] }) return } onConfirm({ datasetIds: selected.filter((kb) => kb.kind === 'dataset').map((kb) => kb.id), knowledgeSpaceIds: selected.filter((kb) => kb.kind === 'knowledge_space').map((kb) => kb.id), }) } const renderPickerOption = (kb: SelectedKb) => ( key={kb.id} value={kb} className="grid-cols-[auto_1fr]"> {/* Visual only: the option owns the click target and the selected state. */} {kb.name} ) return (
{ event.preventDefault() handleConfirm() }} > {t(($) => $['apiKeyModal.addTitle'], { ns: 'appApi' })} {t(($) => $['apiKeyModal.addSubtitle'], { ns: 'appApi' })} $['operation.close'], { ns: 'common' })} disabled={isCreating} />
{t(($) => $['apiKeyModal.knowledgeBaseAccess'], { ns: 'appApi' })}
name="knowledgeBaseScope" aria-labelledby={scopeId} disabled={isCreating} value={scope} onValueChange={setScope} >
{scope === 'specific' && (
{t(($) => $['apiKeyModal.selectedKnowledgeBases'], { ns: 'appApi' })}
{selected.length === 0 ? (
{t(($) => $['apiKeyModal.noKnowledgeBasesSelected'], { ns: 'appApi' })}
) : (
{t(($) => $['apiKeyModal.selectedKnowledgeBasesCount'], { ns: 'appApi', count: selected.length, })}
{selected.map((kb) => (
{kb.name} {kb.kind === 'knowledge_space' && ( {t(($) => $['apiKeyModal.knowledgeSpaceBadge'], { ns: 'appApi' })} )} $['operation.remove'], { ns: 'common' })} ${kb.name}`} className="shrink-0" onClick={() => removeKb(kb.id)} >
))}
)} multiple disabled={isCreating} items={pickerItems} filter={null} value={selected} inputValue={keyword} itemToStringLabel={(kb) => kb.name} isItemEqualToValue={(item, value) => item.id === value.id} onValueChange={setSelected} onInputValueChange={(value, details) => { // Keep the query so several results of one search can be picked. if (details.isItemPress) details.cancel() else setKeyword(value) }} > } > {addLabel} {isLoading ? t(($) => $.loading, { ns: 'common' }) : null} aria-label={t(($) => $['apiKeyModal.scopeSpecificDatasets'], { ns: 'appApi', })} > {knowledgeFsEnabled && ( {t(($) => $['apiKeyModal.pickerKnowledgeSpaces'], { ns: 'appApi' })} > {renderPickerOption} )} {knowledgeFsEnabled && ( {t(($) => $['apiKeyModal.pickerLegacyDatasets'], { ns: 'appApi' })} )} >{renderPickerOption} {isLoading || hasLookupError ? null : t(($) => $.noData, { ns: 'common' })} {knowledgeFsEnabled && ( $['apiKeyModal.loadKnowledgeSpacesError'], { ns: 'appApi', })} loadMoreLabel={t(($) => $['apiKeyModal.loadMoreKnowledgeSpaces'], { ns: 'appApi', })} onSettled={focusPickerInput} /> )} $['apiKeyModal.loadDatasetsError'], { ns: 'appApi' })} loadMoreLabel={t(($) => $['apiKeyModal.loadMoreDatasets'], { ns: 'appApi', })} onSettled={focusPickerInput} />
)}
}> {t(($) => $['operation.cancel'], { ns: 'common' })}
) }