Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(web): rebuild agent knowledge base dialog on inline combobox (#44928)
yyh41a136014da2
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 251fb177a3e..40b8563e372 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -6511,11 +6511,6 @@"count": 5}},- "web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 2- }- },"web/features/agent-v2/agent-detail/configure/components/orchestrate/prompt-editor/slash.tsx": {"better-tailwindcss/enforce-logical-properties": {"count": 30diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/knowledge-entrypoints.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/knowledge-entrypoints.spec.tsxindex 7736df152d8..721c3ce1cd6 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/knowledge-entrypoints.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/__tests__/knowledge-entrypoints.spec.tsx@@ -121,7 +121,7 @@ function setup({async function confirmSpace(user: ReturnType<typeof userEvent.setup>) {const dialog = await screen.findByRole('dialog', { name: /knowledgeFs.title/ })- await user.click(within(dialog).getByRole('checkbox', { name: 'Product manual' }))+ await user.click(within(dialog).getByRole('option', { name: /Product manual/ }))await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))await waitFor(() => expect(dialog).not.toBeInTheDocument())}@@ -140,8 +140,8 @@ describe('KnowledgeFS entry points in the real Agent configuration panel', () =>expect(screen.getByText('Product manual')).toBeInTheDocument()await user.click(screen.getByRole('button', { name: /knowledgeFs.add/ }))const dialog = await screen.findByRole('dialog', { name: /knowledgeFs.title/ })- expect(within(dialog).getByRole('checkbox', { name: 'Product manual' })).toHaveAttribute(- 'aria-checked',+ expect(within(dialog).getByRole('option', { name: /Product manual/ })).toHaveAttribute(+ 'aria-selected','true',)},diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsxindex 8bf0baf8fde..83dff873ec3 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/__tests__/index.spec.tsx@@ -107,6 +107,7 @@ function setup()}const snapshot = () => JSON.parse(screen.getByLabelText('snapshot').textContent ?? '{}')+const optionName = (name: string) => new RegExp(`^${name}(?: |$)`)const open = async (user: ReturnType<typeof userEvent.setup>) => {await user.click(screen.getByRole('button', { name: /knowledgeFs.add/ }))return screen.findByRole('dialog')@@ -117,8 +118,8 @@ describe('KnowledgeFS composer interaction', () => {const user = userEvent.setup()setup()const dialog = await open(user)- await user.click(within(dialog).getByRole('checkbox', { name: 'Product manual' }))- await user.click(within(dialog).getByRole('checkbox', { name: 'Engineering' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Product manual') }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Engineering') }))expect(snapshot().knowledge.spaces).toEqual([])expect(within(dialog).queryByText(/retrievalSetting/)).not.toBeInTheDocument()expect(@@ -137,12 +138,13 @@ describe('KnowledgeFS composer interaction', () => {const user = userEvent.setup()setup([], { spaces: [space()] })const dialog = await open(user)- const list = within(dialog).getByRole('group', { name: /knowledgeFs.select/ })+ const list = within(dialog).getByRole('listbox', { name: /knowledgeFs.select/ })expect(within(list).queryByRole('button')).not.toBeInTheDocument()- const checkbox = within(list).getByRole('checkbox', { name: 'Product manual' })- expect(checkbox).toHaveAccessibleDescription('A real knowledge space')- await user.click(checkbox)- expect(checkbox).toHaveAttribute('aria-checked', 'true')+ const option = within(list).getByRole('option', {+ name: 'Product manual A real knowledge space',+ })+ await user.click(option)+ expect(option).toHaveAttribute('aria-selected', 'true')await user.click(within(dialog).getByRole('button', { name: /advancedSettings.label/ }))expect(within(dialog).getByRole('textbox', { name: /knowledgeFs.alias/ })).toHaveValue('Product manual',@@ -165,17 +167,17 @@ describe('KnowledgeFS composer interaction', () => {})const dialog = await open(user)for (let index = 1; index <= 10; index++) {- await user.click(within(dialog).getByRole('checkbox', { name: `Space ${index}` }))+ await user.click(within(dialog).getByRole('option', { name: optionName(`Space ${index}`) }))}- const search = within(dialog).getByRole('searchbox')+ const search = within(dialog).getByRole('combobox', { name: /knowledgeFs.filter/ })await user.type(search, 'Space 11')- expect(within(dialog).getByRole('checkbox', { name: 'Space 11' })).toHaveAttribute(+ expect(within(dialog).getByRole('option', { name: optionName('Space 11') })).toHaveAttribute('aria-disabled','true',)await user.clear(search)- await user.click(within(dialog).getByRole('checkbox', { name: 'Space 1' }))- await user.click(within(dialog).getByRole('checkbox', { name: 'Space 11' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Space 1') }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Space 11') }))await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(snapshot().knowledge.spaces).toHaveLength(10)expect(snapshot().knowledge.sets).toHaveLength(1)@@ -193,7 +195,8 @@ describe('KnowledgeFS composer interaction', () => {await user.clear(within(dialog).getByRole('textbox', { name: /knowledgeFs.alias/ }))await user.click(advanced)await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))- expect(advanced).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ await user.click(advanced)expect(within(dialog).getByRole('textbox', { name: /knowledgeFs.alias/ })).toHaveValue('')expect(within(dialog).getByRole('alert')).toBeInTheDocument()expect(snapshot().knowledge.spaces[0].name).toBe('Product manual')@@ -251,7 +254,7 @@ describe('KnowledgeFS composer interaction', () => {await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(screen.getByRole('dialog')).toBeInTheDocument()expect(snapshot().knowledge.spaces[0].is_missing).toBe(true)- await user.click(within(dialog).getByRole('checkbox', { name: 'Product manual' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Product manual') }))await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(snapshot().knowledge.spaces[0].is_missing).toBe(false)})@@ -270,7 +273,7 @@ describe('KnowledgeFS composer interaction', () => {],})const dialog = await open(user)- await user.click(within(dialog).getByRole('checkbox', { name: 'Product manual' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Product manual') }))await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(snapshot().knowledge.spaces).toEqual([expect.objectContaining({ control_space_id: SPACE, name: 'Product manual' }),@@ -287,10 +290,13 @@ describe('KnowledgeFS composer interaction', () => {restricted.permission_keys = restricted.permission_keys.filter((key) => key !== permission)setup([], { spaces: [space(), restricted] })const dialog = await open(user)- expect(within(dialog).getAllByRole('checkbox')).toHaveLength(1)+ expect(within(dialog).getAllByRole('option')).toHaveLength(1)expect(within(dialog).queryByText('Restricted')).not.toBeInTheDocument()- await user.type(within(dialog).getByRole('searchbox'), 'Restricted')- expect(within(dialog).queryByRole('checkbox')).not.toBeInTheDocument()+ await user.type(+ within(dialog).getByRole('combobox', { name: /knowledgeFs.filter/ }),+ 'Restricted',+ )+ expect(within(dialog).queryByRole('option')).not.toBeInTheDocument()expect(within(dialog).getByText(/knowledgeFs.empty/)).toBeVisible()expect(within(dialog).queryByText(/knowledgeFs.publishPermission/)).not.toBeInTheDocument()},@@ -302,7 +308,7 @@ describe('KnowledgeFS composer interaction', () => {spaces: [space(SPACE, 'Unavailable', false), { ...space(SECOND), state: 'deleting' }],})const dialog = await open(user)- expect(within(dialog).queryByRole('checkbox')).not.toBeInTheDocument()+ expect(within(dialog).queryByRole('option')).not.toBeInTheDocument()expect(within(dialog).getByText(/knowledgeFs.empty/)).toBeVisible()})@@ -314,15 +320,17 @@ describe('KnowledgeFS composer interaction', () => {spaces: status === 'missing' ? [] : [{ ...space(), permission_keys: [] }],})const dialog = await open(user)- expect(within(dialog).queryByRole('checkbox')).not.toBeInTheDocument()+ expect(+ within(dialog).getByRole('option', { name: optionName('Product manual') }),+ ).toHaveAttribute('aria-selected', 'true')expect(snapshot().knowledge.spaces[0]).toMatchObject({ id: binding.id })await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(dialog).toBeInTheDocument()expect(within(dialog).getByRole('alert').textContent).toMatch(/knowledgeFs.unavailable/)const advanced = within(dialog).getByRole('button', { name: /advancedSettings.label/ })- expect(advanced).toHaveAttribute('aria-expanded', 'true')+ await user.click(advanced)expect(within(dialog).queryByText(SPACE)).not.toBeInTheDocument()- await user.click(within(dialog).getByRole('button', { name: /knowledgeRetrieval.remove/ }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Product manual') }))expect(snapshot().knowledge.spaces).toHaveLength(1)await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(snapshot().knowledge.spaces).toEqual([])@@ -343,7 +351,7 @@ describe('KnowledgeFS composer interaction', () => {const user = userEvent.setup()const { queryClient } = setup([], { spaces: [space()] })const dialog = await open(user)- await user.click(within(dialog).getByRole('checkbox', { name: 'Product manual' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Product manual') }))const options = consoleQuery.knowledgeFs.spaces.get.infiniteOptions({input: (pageParam) => ({ query: { limit: 50, page: pageParam } }),initialPageParam: 1,@@ -362,18 +370,22 @@ describe('KnowledgeFS composer interaction', () => {pageParams: [1],})refresh([{ ...space(), permission_keys: ['knowledge_space_read'] }])- await waitFor(() => expect(within(dialog).queryByRole('checkbox')).not.toBeInTheDocument())+ await waitFor(() =>+ expect(+ within(dialog).getByRole('option', { name: /knowledgeFs.unavailable/ }),+ ).toHaveAttribute('aria-selected', 'true'),+ )await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(within(dialog).getByRole('alert').textContent).toMatch(/knowledgeFs.unavailable/)+ await user.click(within(dialog).getByRole('button', { name: /advancedSettings.label/ }))expect(within(dialog).getByRole('textbox', { name: /knowledgeFs.alias/ })).toHaveValue('Product manual',)expect(snapshot().knowledge.spaces).toEqual([])refresh([space()])- expect(await within(dialog).findByRole('checkbox', { name: 'Product manual' })).toHaveAttribute(- 'aria-checked',- 'true',- )+ expect(+ await within(dialog).findByRole('option', { name: optionName('Product manual') }),+ ).toHaveAttribute('aria-selected', 'true')await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(snapshot().knowledge.spaces[0]).toMatchObject({control_space_id: SPACE,@@ -387,7 +399,7 @@ describe('KnowledgeFS composer interaction', () => {const dialog = await open(user)expect(within(dialog).queryByRole('alert')).not.toBeInTheDocument()expect(snapshot().knowledge.sets).toHaveLength(1)- await user.click(within(dialog).getByRole('checkbox', { name: 'Product manual' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Product manual') }))await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(snapshot().knowledge.sets[0]).toMatchObject({id: 'legacy',@@ -446,7 +458,7 @@ describe('KnowledgeFS composer interaction', () => {if (!firstAdd) throw new Error('First composer must expose an add button')await user.click(firstAdd)const dialog = await screen.findByRole('dialog')- await user.click(within(dialog).getByRole('checkbox', { name: 'Engineering' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Engineering') }))await user.click(within(dialog).getByRole('button', { name: /operation.confirm/ }))expect(JSON.parse(screen.getByLabelText('first').textContent ?? '{}').knowledge.spaces,@@ -468,7 +480,7 @@ describe('KnowledgeFS composer interaction', () => {const user = userEvent.setup()setup([binding])const dialog = await open(user)- await user.click(within(dialog).getByRole('checkbox', { name: 'Engineering' }))+ await user.click(within(dialog).getByRole('option', { name: optionName('Engineering') }))await user.click(within(dialog).getByRole('button', { name: /advancedSettings.label/ }))const aliases = within(dialog).getAllByRole('textbox', { name: /knowledgeFs.alias/ })const secondAlias = aliases[1]diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsxindex a49b32f77bc..4eb61dfe9fe 100644--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/knowledge/dialog.tsx@@ -1,12 +1,26 @@'use client'-import type { KnowledgeFsSpaceListItemResponse } from '@dify/contracts/api/console/knowledge-fs/types.gen'+import type {+ KnowledgeFsSpaceListItemResponse,+ KnowledgeFsTechnicalSummary,+} from '@dify/contracts/api/console/knowledge-fs/types.gen'import type { RefObject } from 'react'import type { AgentKnowledgeRetrievalItem } from '@/features/agent-v2/agent-composer/form-state'import { Button } from '@langgenius/dify-ui/button'-import { Checkbox } from '@langgenius/dify-ui/checkbox'import { cn } from '@langgenius/dify-ui/cn'import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dify-ui/collapsible'+import {+ Combobox,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxInputGroup,+ ComboboxItem,+ ComboboxItemIndicator,+ ComboboxItemText,+ ComboboxList,+ ComboboxStatus,+ createComboboxItems,+} from '@langgenius/dify-ui/combobox'import {Dialog,DialogContent,@@ -16,14 +30,11 @@ import {DialogTitle,} from '@langgenius/dify-ui/dialog'import { Field, FieldLabel } from '@langgenius/dify-ui/field'-import { IconButton } from '@langgenius/dify-ui/icon-button'-import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'import { Input } from '@langgenius/dify-ui/input'import { Textarea } from '@langgenius/dify-ui/textarea'import { useInfiniteQuery } from '@tanstack/react-query'-import { useId, useRef, useState } from 'react'+import { useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { SearchInput } from '@/app/components/base/search-input'import {useKnowledgeValidationMessage,validateKnowledgeRetrievals,@@ -38,7 +49,7 @@ type Props = {}type FormProps = Omit<Props, 'open' | 'onOpenChange'> & {- searchRef: RefObject<HTMLInputElement | null>+ filterRef: RefObject<HTMLInputElement | null>onClose: () => void}@@ -48,78 +59,69 @@ const canBindSpace = (space: KnowledgeFsSpaceListItemResponse) =>space.permission_keys.includes('knowledge_space_read') &&space.permission_keys.includes('knowledge_space_query')-function KnowledgeSpaceOption({- space,- checked,+type SpaceOption = {+ id: string+ name: string+ description?: KnowledgeFsTechnicalSummary['description']+ unavailable: boolean+}++function KnowledgeSpaceOptionItem({+ option,disabled,- onCheckedChange,}: {- space: KnowledgeFsSpaceListItemResponse- checked: boolean+ option: SpaceOptiondisabled: boolean- onCheckedChange: (checked: boolean) => void}) {const { t } = useTranslation(['agentV2'])- const id = useId()- const name =- space.technical_summary?.name || t(($) => $['agentDetail.configure.knowledgeFs.title'])- const description = space.technical_summary?.description+ const description = option.unavailable+ ? t(($) => $['agentDetail.configure.knowledgeFs.unavailable'])+ : option.descriptionreturn (- <div- className={cn(- 'group/space flex h-14 min-w-0 items-center gap-2 rounded-lg px-2 transition-colors motion-reduce:transition-none',- checked- ? 'bg-state-accent-active'- : 'focus-within:bg-state-base-hover hover:bg-state-base-hover',- )}+ <ComboboxItem<string>+ value={option.id}+ disabled={disabled}+ className="group/space min-h-12 gap-3">- <label- htmlFor={id}- className={cn(- 'flex h-full min-w-0 flex-1 items-center gap-3',- disabled ? 'cursor-not-allowed' : 'cursor-pointer',- )}- >+ <span className="flex min-w-0 items-center gap-2.5"><spanaria-hidden- className="flex size-8 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-divider-regular bg-components-panel-on-panel-item-bg text-text-secondary shadow-xs group-focus-within/space:text-text-accent group-hover/space:text-text-accent"+ className={cn(+ 'flex size-7 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-divider-regular bg-components-panel-on-panel-item-bg shadow-xs',+ option.unavailable ? 'text-text-warning' : 'text-text-tertiary',+ )}>- <span className="i-ri-book-open-line size-4" />- </span>- <span className="min-w-0 flex-1"><span- id={`${id}-name`}className={cn(- 'block truncate system-sm-medium',- disabled- ? 'text-text-tertiary'- : 'text-text-secondary group-focus-within/space:text-text-primary group-hover/space:text-text-primary',+ 'size-4',+ option.unavailable ? 'i-ri-error-warning-line' : 'i-ri-book-open-line',)}- >- {name}- </span>+ />+ </span>+ <span className="min-w-0 flex-1">+ <ComboboxItemText className="block">{option.name}</ComboboxItemText>{!!description && (- <span className="grid grid-rows-[0fr] opacity-0 transition-[grid-template-rows,opacity] duration-150 group-focus-within/space:grid-rows-[1fr] group-focus-within/space:opacity-100 group-hover/space:grid-rows-[1fr] group-hover/space:opacity-100 motion-reduce:transition-none">- <span- id={`${id}-description`}- className="min-h-0 truncate overflow-hidden system-xs-regular text-text-tertiary"- >- {description}- </span>+ <span+ className={cn(+ 'block truncate system-xs-regular',+ option.unavailable ? 'text-text-warning' : 'text-text-tertiary',+ )}+ >+ {description}</span>)}</span>- <Checkbox- id={id}- aria-labelledby={`${id}-name`}- aria-describedby={description ? `${id}-description` : undefined}- checked={checked}- disabled={disabled}- onCheckedChange={onCheckedChange}- />- </label>- </div>+ </span>+ <span+ aria-hidden+ className="inline-flex size-4 shrink-0 items-center justify-center rounded-sm border border-components-checkbox-border bg-components-checkbox-bg-unchecked text-components-checkbox-icon shadow-xs shadow-shadow-shadow-3 group-data-disabled/space:border-components-checkbox-border-disabled group-data-disabled/space:bg-components-checkbox-bg-disabled group-data-selected/space:border-transparent group-data-selected/space:bg-components-checkbox-bg"+ >+ <ComboboxItemIndicator className="ms-0 text-components-checkbox-icon">+ <span className="i-ri-check-line size-3" />+ </ComboboxItemIndicator>+ </span>+ </ComboboxItem>)}@@ -128,14 +130,12 @@ function AgentKnowledgeRetrievalForm({initialBindings,onConfirm,onClose,- searchRef,+ filterRef,}: FormProps) {const { t } = useTranslation(['agentV2'])const { t: tc } = useTranslation(['common'])const [draft, setDraft] = useState(initialBindings)- const [filter, setFilter] = useState('')const [submitted, setSubmitted] = useState(false)- const [advancedOpen, setAdvancedOpen] = useState(false)const validationMessage = useKnowledgeValidationMessage()const spacesQuery = useInfiniteQuery({...consoleQuery.knowledgeFs.spaces.get.infiniteOptions({@@ -144,53 +144,105 @@ function AgentKnowledgeRetrievalForm({initialPageParam: 1,}),})- const spaces = spacesQuery.data?.pages.flatMap((page) => page.data) ?? []- const spacesById = new Map(spaces.map((space) => [space.control_space_id, space]))- const visibleSpaces = spaces.filter(- (space) =>- canBindSpace(space) &&- (space.technical_summary?.name ?? '')- .toLocaleLowerCase()- .includes(filter.toLocaleLowerCase()),+ const spaces = useMemo(+ () => spacesQuery.data?.pages.flatMap((page) => page.data) ?? [],+ [spacesQuery.data],+ )+ const spacesById = useMemo(+ () => new Map(spaces.map((space) => [space.control_space_id, space])),+ [spaces],)// A later catalog page may contain a saved binding; absence is conclusive only// after a successful, complete listing. Never discard a binding on query refresh.- const unavailableBindingIds = new Set(- draft- .filter((item) => {- if (!item.controlSpaceId || item.isMissing) return false- const space = spacesById.get(item.controlSpaceId)- return space ? !canBindSpace(space) : spacesQuery.isSuccess && !spacesQuery.hasNextPage+ const catalogComplete = spacesQuery.isSuccess && !spacesQuery.hasNextPage+ const unavailableBindingIds = useMemo(+ () =>+ new Set(+ draft+ .filter((item) => {+ if (!item.controlSpaceId) return false+ const space = spacesById.get(item.controlSpaceId)+ return space ? !canBindSpace(space) : catalogComplete+ })+ .map((item) => item.id),+ ),+ [catalogComplete, draft, spacesById],+ )+ const fallbackName = t(($) => $['agentDetail.configure.knowledgeFs.title'])+ const spaceName = (space?: KnowledgeFsSpaceListItemResponse) =>+ space?.technical_summary?.name || fallbackName+ // Unavailable bindings stay listed as selected options, so deselecting one is how it is removed.+ const optionItems = useMemo(() => {+ const options = new Map<string, SpaceOption>()+ for (const space of spaces) {+ if (!canBindSpace(space)) continue+ options.set(space.control_space_id, {+ id: space.control_space_id,+ name: space.technical_summary?.name || fallbackName,+ description: space.technical_summary?.description,+ unavailable: false,+ })+ }+ for (const item of draft) {+ if (!item.controlSpaceId || !unavailableBindingIds.has(item.id)) continue+ if (options.has(item.controlSpaceId)) continue+ options.set(item.controlSpaceId, {+ id: item.controlSpaceId,+ name:+ item.name || spacesById.get(item.controlSpaceId)?.technical_summary?.name || fallbackName,+ unavailable: true,})- .map((item) => item.id),+ }+ return createComboboxItems([...options.values()], {+ getValue: (option) => option.id,+ getLabel: (option) => option.name,+ })+ }, [draft, fallbackName, spaces, spacesById, unavailableBindingIds])+ const selectedIds = useMemo(+ () => [+ ...new Set(+ draft.flatMap((item) =>+ item.controlSpaceId && (!item.isMissing || unavailableBindingIds.has(item.id))+ ? [item.controlSpaceId]+ : [],+ ),+ ),+ ],+ [draft, unavailableBindingIds],)const validation = validateKnowledgeRetrievals(draft)const spaceCount = draft.filter((item) => item.controlSpaceId).lengthconst update = (id: string, patch: Partial<AgentKnowledgeRetrievalItem>) =>setDraft((current) => current.map((item) => (item.id === id ? { ...item, ...patch } : item)))- const toggle = (space: KnowledgeFsSpaceListItemResponse, checked: boolean) => {+ const select = (nextIds: string[]) => {+ const removed = new Set(selectedIds.filter((id) => !nextIds.includes(id)))+ const added = nextIds.filter((id) => !selectedIds.includes(id))setDraft((current) => {- const existing = current.find((item) => item.controlSpaceId === space.control_space_id)- if (!checked) return current.filter((item) => item !== existing)- if (!canBindSpace(space)) return current- if (existing)- return current.map((item) => (item === existing ? { ...item, isMissing: false } : item))- if (current.filter((item) => item.controlSpaceId).length >= 10) return current- const title =- space.technical_summary?.name || t(($) => $['agentDetail.configure.knowledgeFs.title'])- const name = current.some((item) => item.name?.toLowerCase() === title.toLowerCase())- ? `${title.slice(0, 109)} (${space.control_space_id.slice(0, 8)})`- : title.slice(0, 120)- return [- ...current,- {+ const next = current+ .filter((item) => !item.controlSpaceId || !removed.has(item.controlSpaceId))+ .map((item) =>+ item.controlSpaceId && item.isMissing && added.includes(item.controlSpaceId)+ ? { ...item, isMissing: false }+ : item,+ )+ for (const id of added) {+ const space = spacesById.get(id)+ if (!space || !canBindSpace(space) || next.some((item) => item.controlSpaceId === id))+ continue+ if (next.filter((item) => item.controlSpaceId).length >= 10) break+ const title = spaceName(space)+ const name = next.some((item) => item.name?.toLowerCase() === title.toLowerCase())+ ? `${title.slice(0, 109)} (${id.slice(0, 8)})`+ : title.slice(0, 120)+ next.push({id: crypto.randomUUID(),- controlSpaceId: space.control_space_id,+ controlSpaceId: id,name,description: space.technical_summary?.description?.slice(0, 2000) ?? '',isMissing: false,- },- ]+ })+ }+ return next})}@@ -202,187 +254,175 @@ function AgentKnowledgeRetrievalForm({event.preventDefault()setSubmitted(true)if (validation.isValid && unavailableBindingIds.size === 0) onConfirm(draft)- else setAdvancedOpen(true)}}><DialogHeader>- <div className="flex items-center gap-2">- <DialogTitle>{t(($) => $['agentDetail.configure.knowledgeFs.title'])}</DialogTitle>- <Infotip>- <InfotipTrigger- aria-label={t(($) => $['agentDetail.configure.knowledgeFs.description'])}- />- <InfotipContent>- {t(($) => $['agentDetail.configure.knowledgeFs.description'])}- </InfotipContent>- </Infotip>- </div>+ <DialogTitle>{t(($) => $['agentDetail.configure.knowledgeFs.title'])}</DialogTitle><DialogDescription>{t(($) => $['agentDetail.configure.knowledgeFs.select'])}</DialogDescription><DialogHeaderCloseButton aria-label={tc(($) => $['operation.close'])} /></DialogHeader>- <div className="shrink-0 px-6 pb-4">- <SearchInput- ref={searchRef}- value={filter}- onValueChange={setFilter}- aria-label={t(($) => $['agentDetail.configure.knowledgeFs.filter'])}- />- </div>- <div className="min-h-0 space-y-3 overflow-y-auto overscroll-contain px-4 pb-4 system-sm-regular">- {draft.some((item) => item.isMissing) && (- <p role="alert" className="px-2 system-xs-regular text-text-warning">- {t(($) => $['agentDetail.configure.knowledgeFs.rebind'])}- </p>- )}- {unavailableBindingIds.size > 0 && (- <p role="alert" className="px-2 system-xs-regular text-text-warning">- {t(($) => $['agentDetail.configure.knowledgeFs.unavailable'])}- </p>- )}- {spacesQuery.isPending && (- <div role="status" className="space-y-1">- <span className="sr-only">- {t(($) => $['agentDetail.configure.knowledgeFs.loading'])}- </span>- {Array.from({ length: 5 }, (_, index) => (- <div- key={index}- aria-hidden- className="flex h-14 items-center gap-3 px-2 motion-safe:animate-pulse"+ <Combobox<string, true, SpaceOption>+ inline+ open+ multiple+ items={optionItems}+ value={selectedIds}+ onValueChange={select}+ >+ <div className="shrink-0 px-6 pb-3">+ <ComboboxInputGroup>+ <span+ aria-hidden+ className="i-ri-search-line size-4 shrink-0 text-components-input-text-placeholder"+ />+ <ComboboxInput+ ref={filterRef}+ enterKeyHint="search"+ aria-label={t(($) => $['agentDetail.configure.knowledgeFs.filter'])}+ placeholder={t(($) => $['agentDetail.configure.knowledgeFs.filter'])}+ />+ </ComboboxInputGroup>+ </div>+ <div className="min-h-0 space-y-3 overflow-y-auto overscroll-contain px-6 pb-4 system-sm-regular">+ {draft.some((item) => item.isMissing && !unavailableBindingIds.has(item.id)) && (+ <p role="alert" className="system-xs-regular text-text-warning">+ {t(($) => $['agentDetail.configure.knowledgeFs.rebind'])}+ </p>+ )}+ <ComboboxStatus className="sr-only">+ {spacesQuery.isPending && t(($) => $['agentDetail.configure.knowledgeFs.loading'])}+ </ComboboxStatus>+ {spacesQuery.isPending && (+ <div aria-hidden className="space-y-1">+ {Array.from({ length: 5 }, (_, index) => (+ <div+ key={index}+ className="flex h-14 items-center gap-3 px-2 motion-safe:animate-pulse"+ >+ <span className="size-8 rounded-lg bg-background-section" />+ <span className="h-4 w-1/2 rounded bg-background-section" />+ </div>+ ))}+ </div>+ )}+ {spacesQuery.isError && (+ <div role="alert" className="space-y-2 py-3 system-sm-regular text-text-destructive">+ <p>{t(($) => $['agentDetail.configure.knowledgeFs.loadError'])}</p>+ <Button onClick={() => void spacesQuery.refetch()} loading={spacesQuery.isFetching}>+ {t(($) => $['agentDetail.configure.knowledgeFs.retry'])}+ </Button>+ </div>+ )}+ {!spacesQuery.isPending && !spacesQuery.isError && (+ <>+ <ComboboxList<SpaceOption>+ aria-label={t(($) => $['agentDetail.configure.knowledgeFs.select'])}+ className="max-h-none overflow-visible p-0">- <span className="size-8 rounded-lg bg-background-section" />- <span className="h-4 w-1/2 rounded bg-background-section" />- </div>- ))}- </div>- )}- {spacesQuery.isError && (- <div role="alert" className="space-y-2 p-3 system-sm-regular text-text-destructive">- <p>{t(($) => $['agentDetail.configure.knowledgeFs.loadError'])}</p>- <Button onClick={() => void spacesQuery.refetch()} loading={spacesQuery.isFetching}>- {t(($) => $['agentDetail.configure.knowledgeFs.retry'])}+ {(option) => (+ <KnowledgeSpaceOptionItem+ key={option.id}+ option={option}+ disabled={!selectedIds.includes(option.id) && spaceCount >= 10}+ />+ )}+ </ComboboxList>+ <ComboboxEmpty className="px-0 py-8 text-center">+ {t(($) => $['agentDetail.configure.knowledgeFs.empty'])}+ </ComboboxEmpty>+ </>+ )}+ {spacesQuery.hasNextPage && (+ <Button+ onClick={() => void spacesQuery.fetchNextPage()}+ loading={spacesQuery.isFetchingNextPage}+ >+ {t(($) => $['agentDetail.configure.knowledgeFs.loadMore'])}</Button>- </div>- )}- {!spacesQuery.isPending && !spacesQuery.isError && visibleSpaces.length === 0 && (- <p className="px-2 py-8 text-center system-sm-regular text-text-tertiary">- {t(($) => $['agentDetail.configure.knowledgeFs.empty'])}- </p>- )}- <fieldset className="min-w-0 space-y-1">- <legend className="sr-only">- {t(($) => $['agentDetail.configure.knowledgeFs.select'])}- </legend>- {visibleSpaces.map((space) => {- const binding = draft.find((item) => item.controlSpaceId === space.control_space_id)- const checked = !!binding && !binding.isMissing- return (- <KnowledgeSpaceOption- key={space.control_space_id}- space={space}- checked={checked}- disabled={!checked && !binding && spaceCount >= 10}- onCheckedChange={(next) => toggle(space, next)}- />- )- })}- </fieldset>- {spacesQuery.hasNextPage && (- <Button- className="ml-2"- onClick={() => void spacesQuery.fetchNextPage()}- loading={spacesQuery.isFetchingNextPage}- >- {t(($) => $['agentDetail.configure.knowledgeFs.loadMore'])}- </Button>- )}- {draft.length > 0 && (- <Collapsible- open={advancedOpen}- onOpenChange={setAdvancedOpen}- className="border-t border-divider-subtle pt-2"- >- <CollapsibleTrigger className="group flex min-h-8 w-full touch-manipulation items-center justify-between gap-2 rounded-lg px-2.5 text-start system-sm-medium text-text-secondary select-none hover:bg-components-panel-on-panel-item-bg-hover hover:text-text-primary data-panel-open:text-text-primary">- <span>- {t(($) => $['agentDetail.configure.advancedSettings.label'])}{' '}- <span className="system-xs-regular text-text-tertiary">- {tc(($) => $['label.optional'])}+ )}+ {draft.length > 0 && (+ <Collapsible className="border-t-[0.5px] border-divider-subtle pt-3">+ <CollapsibleTrigger className="group -mx-2 flex h-8 w-[calc(100%+1rem)] touch-manipulation items-center gap-1 rounded-lg px-2 text-start system-sm-medium text-text-secondary select-none hover:bg-state-base-hover">+ <span className="flex-1">+ {t(($) => $['agentDetail.configure.advancedSettings.label'])}</span>- </span>- <span- aria-hidden- className="i-ri-arrow-right-s-line size-4 shrink-0 transition-transform group-data-panel-open:rotate-90 motion-reduce:transition-none"- />- </CollapsibleTrigger>- <CollapsiblePanel>- <div className="space-y-3 px-2 pt-3">- {draft.map((item) => (- <fieldset- key={item.id}- className="min-w-0 space-y-3 rounded-xl bg-background-section p-3"- >- <legend className="sr-only">- {item.name || t(($) => $['agentDetail.configure.knowledgeFs.title'])}- </legend>- <div className="flex items-center gap-2">- <span className="min-w-0 flex-1 truncate system-sm-medium">- {item.name || t(($) => $['agentDetail.configure.knowledgeFs.title'])}- </span>- <IconButton- aria-label={t(($) => $['agentDetail.configure.knowledgeRetrieval.remove'], {- name: item.name || t(($) => $['agentDetail.configure.knowledgeFs.title']),- })}- tone="destructive"- onClick={() =>- setDraft((current) => current.filter((row) => row.id !== item.id))- }+ <span+ aria-hidden+ className="i-ri-arrow-down-s-line size-4 shrink-0 text-text-tertiary transition-transform group-data-panel-open:rotate-180 motion-reduce:transition-none"+ />+ </CollapsibleTrigger>+ <CollapsiblePanel>+ <div className="space-y-2 pt-2">+ {draft.map((item) => {+ const title = item.controlSpaceId+ ? spaceName(spacesById.get(item.controlSpaceId))+ : item.name || fallbackName+ const unavailable = unavailableBindingIds.has(item.id)+ return (+ <fieldset+ key={item.id}+ className="min-w-0 space-y-3 rounded-xl border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg p-3 shadow-xs">- <span aria-hidden className="i-ri-delete-bin-line size-4" />- </IconButton>- </div>- {unavailableBindingIds.has(item.id) && (- <p className="system-xs-regular text-text-warning">- {t(($) => $['agentDetail.configure.knowledgeFs.unavailable'])}- </p>- )}- <Field invalid={submitted && !!validation.byId[item.id]?.name}>- <FieldLabel>- {t(($) => $['agentDetail.configure.knowledgeFs.alias'])}- </FieldLabel>- <Input- required- maxLength={120}- value={item.name ?? ''}- onChange={(event) => update(item.id, { name: event.target.value })}- />- </Field>- <Field>- <FieldLabel>- {t(($) => $['agentDetail.configure.knowledgeFs.bindingDescription'])}- </FieldLabel>- <Textarea- rows={3}- maxLength={2000}- value={item.description ?? ''}- onValueChange={(value) => update(item.id, { description: value })}- />- </Field>- </fieldset>- ))}- </div>- </CollapsiblePanel>- </Collapsible>- )}- {submitted && validation.firstIssue && (- <p role="alert" className="px-2 system-xs-regular text-text-destructive">- {validationMessage(validation.firstIssue.code)}- </p>- )}- </div>+ <legend className="sr-only">{title}</legend>+ <div aria-hidden className="flex min-w-0 items-center gap-2">+ <span+ className={cn(+ 'flex size-6 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-components-panel-bg',+ unavailable ? 'text-text-warning' : 'text-text-tertiary',+ )}+ >+ <span+ className={cn(+ 'size-3.5',+ unavailable ? 'i-ri-error-warning-line' : 'i-ri-book-open-line',+ )}+ />+ </span>+ <span className="min-w-0 truncate system-sm-semibold text-text-primary">+ {title}+ </span>+ </div>+ <Field invalid={submitted && !!validation.byId[item.id]?.name}>+ <FieldLabel className="system-xs-medium text-text-tertiary">+ {t(($) => $['agentDetail.configure.knowledgeFs.alias'])}+ </FieldLabel>+ <Input+ required+ maxLength={120}+ value={item.name ?? ''}+ onChange={(event) => update(item.id, { name: event.target.value })}+ />+ </Field>+ <Field>+ <FieldLabel className="system-xs-medium text-text-tertiary">+ {t(($) => $['agentDetail.configure.knowledgeFs.bindingDescription'])}+ </FieldLabel>+ <Textarea+ maxLength={2000}+ value={item.description ?? ''}+ onValueChange={(value) => update(item.id, { description: value })}+ />+ </Field>+ </fieldset>+ )+ })}+ </div>+ </CollapsiblePanel>+ </Collapsible>+ )}+ {submitted && (validation.firstIssue || unavailableBindingIds.size > 0) && (+ <p role="alert" className="system-xs-regular text-text-destructive">+ {validation.firstIssue+ ? validationMessage(validation.firstIssue.code)+ : t(($) => $['agentDetail.configure.knowledgeFs.unavailable'])}+ </p>+ )}+ </div>+ </Combobox><div className="flex shrink-0 items-center justify-end gap-2 border-t border-divider-subtle px-6 py-4">- <span role="status" className="mr-auto system-xs-medium text-text-tertiary tabular-nums">+ <span role="status" className="me-auto system-xs-medium text-text-tertiary tabular-nums">{spaceCount} / 10</span><Button onClick={onClose}>{tc(($) => $['operation.cancel'])}</Button>@@ -401,14 +441,14 @@ export function AgentKnowledgeRetrievalDialog({onConfirm,onOpenChange,}: Props) {- const searchRef = useRef<HTMLInputElement>(null)+ const filterRef = useRef<HTMLInputElement>(null)return (<Dialog open={open} onOpenChange={onOpenChange}>- <DialogContent initialFocus={searchRef} className="w-144 overflow-hidden">+ <DialogContent initialFocus={filterRef} className="w-xl overflow-hidden"><AgentKnowledgeRetrievalForminitialBindings={initialBindings}- searchRef={searchRef}+ filterRef={filterRef}onConfirm={onConfirm}onClose={() => onOpenChange(false)}/>