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): align plugin search composition and ref utilities (#43820)
yyh307b3b8ecfa9
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 15f670553bd..da81f8dc8a8 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -1373,11 +1373,6 @@"count": 3}},- "web/app/components/base/search-input/index.tsx": {- "dify/require-disable-directive-description": {- "count": 1- }- },"web/app/components/base/tag-input/index.stories.tsx": {"jsx-a11y/label-has-associated-control": {"count": 12@@ -2108,11 +2103,6 @@"count": 1}},- "web/app/components/plugins/marketplace/search-box/index.tsx": {- "dify/require-disable-directive-description": {- "count": 1- }- },"web/app/components/plugins/plugin-auth/authorized/index.tsx": {"no-restricted-imports": {"count": 1@@ -2581,11 +2571,6 @@"count": 3}},- "web/app/components/workflow/block-selector/tool-picker.tsx": {- "dify/require-disable-directive-description": {- "count": 1- }- },"web/app/components/workflow/comment/comment-input.tsx": {"jsx-a11y/no-autofocus": {"count": 1diff --git a/packages/dify-ui/README.md b/packages/dify-ui/README.mdindex 52d1775cb85..44c1bee059e 100644--- a/packages/dify-ui/README.md+++ b/packages/dify-ui/README.md@@ -52,6 +52,8 @@ Utilities:- `./direction-provider` exports Base UI `DirectionProvider` and `useDirection`. Set HTML `dir` as well for CSS layout; pickers propagate their resolved direction to their trigger and portaled content.- `./cn` re-exports `cn` from the `cn` package through Dify UI's public subpath.+- `./use-merged-refs` exports `useMergedRefs` for combining internal and caller refs, including callback cleanup.+- `./use-ref-with-init` exports `useRefWithInit` for lazy ref initialization. Later initializer or argument changes do not reset the ref; initialization runs during render and must be safe to retry or discard.- `./styles.css` provides design tokens, theme variables, and shared utilities.## Guidesdiff --git a/packages/dify-ui/package.json b/packages/dify-ui/package.jsonindex 9ef9a16d00f..4bb1321d102 100644--- a/packages/dify-ui/package.json+++ b/packages/dify-ui/package.json@@ -9,6 +9,14 @@"types": "./src/cn.ts","import": "./src/cn.ts"},+ "./use-merged-refs": {+ "types": "./src/use-merged-refs.ts",+ "import": "./src/use-merged-refs.ts"+ },+ "./use-ref-with-init": {+ "types": "./src/use-ref-with-init.ts",+ "import": "./src/use-ref-with-init.ts"+ },"./alert-dialog": {"types": "./src/alert-dialog/index.tsx","import": "./src/alert-dialog/index.tsx"diff --git a/packages/dify-ui/src/use-merged-refs.ts b/packages/dify-ui/src/use-merged-refs.tsnew file mode 100644index 00000000000..9b9a27dbcc8--- /dev/null+++ b/packages/dify-ui/src/use-merged-refs.ts@@ -0,0 +1,3 @@+'use client'++export { useMergedRefs } from '@base-ui/utils/useMergedRefs'diff --git a/packages/dify-ui/src/use-ref-with-init.ts b/packages/dify-ui/src/use-ref-with-init.tsnew file mode 100644index 00000000000..9f0921e72a7--- /dev/null+++ b/packages/dify-ui/src/use-ref-with-init.ts@@ -0,0 +1,3 @@+'use client'++export { useRefWithInit } from '@base-ui/utils/useRefWithInit'diff --git a/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts b/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.tsindex b46287494e8..78614a1cdeb 100644--- a/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts+++ b/web/app/components/app/app-publisher/hooks/use-refresh-app-environments-after-deployment-polling.ts@@ -1,11 +1,11 @@'use client'import { DeploymentOperationStatus } from '@dify/contracts/enterprise-app-deploy/types.gen'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useQueryClient } from '@tanstack/react-query'import { useAtomValue, useSetAtom } from 'jotai'import { useEffect } from 'react'import { shouldPollEnvironmentDeployment } from '@/app/components/app/deploy/utils/environment-deployment'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { consoleQuery } from '@/service/console'import {appPublisherOpenAtom,diff --git a/web/app/components/base/keyboard-sortable/use-keyboard-sortable.tsx b/web/app/components/base/keyboard-sortable/use-keyboard-sortable.tsxindex 497e03e0758..b05c1f6af63 100644--- a/web/app/components/base/keyboard-sortable/use-keyboard-sortable.tsx+++ b/web/app/components/base/keyboard-sortable/use-keyboard-sortable.tsx@@ -1,8 +1,8 @@'use client'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useId, useLayoutEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useRefWithInit } from '@/hooks/use-ref-with-init'type Options<T> = {items: T[]diff --git a/web/app/components/base/search-input/__tests__/index.spec.tsx b/web/app/components/base/search-input/__tests__/index.spec.tsxindex 445819f89b4..1564f67d621 100644--- a/web/app/components/base/search-input/__tests__/index.spec.tsx+++ b/web/app/components/base/search-input/__tests__/index.spec.tsx@@ -39,6 +39,24 @@ describe('SearchInput', () => {expect(ref.current).toBe(screen.getByRole('searchbox', { name: 'common.operation.search' }))})+ it('cleans up callback refs when the owner replaces the ref or unmounts', () => {+ const cleanup = vi.fn()+ const ref = vi.fn(() => cleanup)+ const nextRef = createRef<HTMLInputElement>()+ const { rerender, unmount } = render(+ <SearchInput ref={ref} value="" onValueChange={() => {}} />,+ )+ const input = screen.getByRole('searchbox')+ expect(ref).toHaveBeenCalledWith(input)++ rerender(<SearchInput ref={nextRef} value="" onValueChange={() => {}} />)+ expect(cleanup).toHaveBeenCalledOnce()+ expect(nextRef.current).toBe(input)++ unmount()+ expect(nextRef.current).toBeNull()+ })+it('focuses the searchbox when autoFocus is enabled', () => {// oxlint-disable-next-line jsx-a11y/no-autofocusrender(<SearchInput value="" onValueChange={() => {}} autoFocus />)diff --git a/web/app/components/base/search-input/index.tsx b/web/app/components/base/search-input/index.tsxindex 2dfa3f12f0e..dc3e4e52c5e 100644--- a/web/app/components/base/search-input/index.tsx+++ b/web/app/components/base/search-input/index.tsx@@ -2,8 +2,8 @@ import type { InputGroupInputProps } from '@langgenius/dify-ui/input-group'import type { Ref } from 'react'import { IconButton } from '@langgenius/dify-ui/icon-button'import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'-import { useImperativeHandle, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useSearchInput } from './use-search-input'type SearchInputProps = {ref?: Ref<HTMLInputElement>@@ -29,64 +29,21 @@ export function SearchInput({'aria-label': ariaLabel,}: SearchInputProps) {const { t } = useTranslation(['common'])- const inputRef = useRef<HTMLInputElement>(null)- const isComposingRef = useRef<boolean>(false)- const compositionCommitRef = useRef<string | null>(null)- const [compositionValue, setCompositionValue] = useState('')- const inputValue = isComposingRef.current ? compositionValue : value- useImperativeHandle(ref, () => inputRef.current as HTMLInputElement, [])-- const handleClear = () => {- isComposingRef.current = false- compositionCommitRef.current = null- setCompositionValue('')- onValueChange('')- inputRef.current?.focus()- }+ const { inputProps, clear } = useSearchInput({ value, onValueChange, ref })return (<InputGroup className={className}><InputGroupInput- ref={inputRef}+ {...inputProps}type="search"name={name}aria-describedby={ariaDescribedBy}aria-label={ariaLabel ?? t(($) => $['operation.search'], { ns: 'common' })}className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"placeholder={placeholder ?? t(($) => $['operation.search'], { ns: 'common' })}- value={inputValue}disabled={disabled}- onValueChange={(nextValue) => {- if (isComposingRef.current) {- setCompositionValue(nextValue)- return- }- if (compositionCommitRef.current !== null) {- if (compositionCommitRef.current !== nextValue) {- compositionCommitRef.current = null- onValueChange(nextValue)- return- }- compositionCommitRef.current = null- return- }- onValueChange(nextValue)- }}- onCompositionStart={() => {- isComposingRef.current = true- compositionCommitRef.current = null- setCompositionValue(value)- }}- onCompositionEnd={(e) => {- if (!isComposingRef.current) return-- isComposingRef.current = false- setCompositionValue('')- compositionCommitRef.current = e.currentTarget.value- onValueChange(e.currentTarget.value)- }}autoComplete="off"- // oxlint-disable-next-line jsx-a11y/no-autofocus+ // oxlint-disable-next-line jsx-a11y/no-autofocus -- The caller owns initial focus for its search surface.autoFocus={autoFocus}enterKeyHint="search"/>@@ -96,13 +53,13 @@ export function SearchInput({aria-hidden="true"/></InputGroupAddon>- {!!inputValue && !disabled && (+ {!!inputProps.value && !disabled && (<InputGroupAddon align="inline-end" className="ps-0.75 pe-1.25"><IconButtonsize="sm"aria-label={t(($) => $['operation.clear'], { ns: 'common' })}className="text-text-quaternary hover:bg-transparent hover:text-text-tertiary focus-visible:bg-components-input-bg-hover focus-visible:ring-inset"- onClick={handleClear}+ onClick={clear}><span className="i-ri-close-circle-fill size-4" aria-hidden="true" /></IconButton>diff --git a/web/app/components/base/search-input/use-search-input.ts b/web/app/components/base/search-input/use-search-input.tsnew file mode 100644index 00000000000..7732ddc537d--- /dev/null+++ b/web/app/components/base/search-input/use-search-input.ts@@ -0,0 +1,58 @@+import type { CompositionEvent, Ref } from 'react'+import { useMergedRefs } from '@langgenius/dify-ui/use-merged-refs'+import { useRef, useState } from 'react'++type SearchInputOptions = {+ value: string+ onValueChange: (value: string) => void+ ref?: Ref<HTMLInputElement>+}++export function useSearchInput({ value, onValueChange, ref }: SearchInputOptions) {+ const inputRef = useRef<HTMLInputElement>(null)+ const mergedRef = useMergedRefs(inputRef, ref)+ const isComposingRef = useRef(false)+ const compositionCommitRef = useRef<string | null>(null)+ const [compositionValue, setCompositionValue] = useState<string | null>(null)++ const clear = () => {+ isComposingRef.current = false+ compositionCommitRef.current = null+ setCompositionValue(null)+ onValueChange('')+ inputRef.current?.focus()+ }++ return {+ clear,+ inputProps: {+ ref: mergedRef,+ value: compositionValue ?? value,+ onValueChange: (nextValue: string) => {+ if (isComposingRef.current) {+ setCompositionValue(nextValue)+ return+ }+ if (compositionCommitRef.current !== null) {+ const committedValue = compositionCommitRef.current+ compositionCommitRef.current = null+ if (committedValue === nextValue) return+ }+ onValueChange(nextValue)+ },+ onCompositionStart: () => {+ isComposingRef.current = true+ compositionCommitRef.current = null+ setCompositionValue(value)+ },+ onCompositionEnd: (event: CompositionEvent<HTMLInputElement>) => {+ if (!isComposingRef.current) return++ isComposingRef.current = false+ setCompositionValue(null)+ compositionCommitRef.current = event.currentTarget.value+ onValueChange(event.currentTarget.value)+ },+ },+ }+}diff --git a/web/app/components/datasets/documents/create-from-pipeline/data-source/store/provider.tsx b/web/app/components/datasets/documents/create-from-pipeline/data-source/store/provider.tsxindex 73d35069920..5ab080601b1 100644--- a/web/app/components/datasets/documents/create-from-pipeline/data-source/store/provider.tsx+++ b/web/app/components/datasets/documents/create-from-pipeline/data-source/store/provider.tsx@@ -1,5 +1,5 @@+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { createContext } from 'react'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { createDataSourceStore } from './'type DataSourceStoreApi = ReturnType<typeof createDataSourceStore>diff --git a/web/app/components/plugins/marketplace/__tests__/search-input.spec.tsx b/web/app/components/plugins/marketplace/__tests__/search-input.spec.tsxnew file mode 100644index 00000000000..3953a8811f1--- /dev/null+++ b/web/app/components/plugins/marketplace/__tests__/search-input.spec.tsx@@ -0,0 +1,36 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { describe, expect, it, vi } from 'vite-plus/test'+import { renderWithNuqs } from '@/test/nuqs-testing'+import { MarketplacePluginSearch } from '../search-input'++const markFilter = vi.hoisted(() => vi.fn())+vi.mock('@/utils/marketplace-site-track', () => ({+ markMarketplaceSiteFilter: markFilter,+}))++describe('MarketplacePluginSearch', () => {+ it('clears the query and tags independently in the URL and tracks tag changes', async () => {+ const user = userEvent.setup()+ const { onUrlUpdate } = renderWithNuqs(<MarketplacePluginSearch />, {+ searchParams: '?q=agent&tags=rag',+ })+ await user.click(screen.getByRole('button', { name: /^plugin\.clearSearch/ }))+ await waitFor(() => {+ const params = onUrlUpdate.mock.calls.at(-1)?.[0].searchParams+ expect(params?.get('q')).toBeNull()+ expect(params?.get('tags')).toBe('rag')+ })+ expect(markFilter).not.toHaveBeenCalled()+ await user.click(screen.getByRole('button', { name: /^pluginTags\.clearSelectedTags/ }))+ await waitFor(() => {+ expect(onUrlUpdate.mock.calls.at(-1)?.[0].searchParams.get('tags')).toBeNull()+ })+ expect(markFilter).toHaveBeenCalledExactlyOnceWith({+ filter_type: 'category',+ selection_mode: 'multi',+ filter_value: 'rag',+ selected_values: [],+ })+ })+})diff --git a/web/app/components/plugins/marketplace/description/index.tsx b/web/app/components/plugins/marketplace/description/index.tsxindex 97cedf6f825..7aa6c9d2fc1 100644--- a/web/app/components/plugins/marketplace/description/index.tsx+++ b/web/app/components/plugins/marketplace/description/index.tsx@@ -9,7 +9,7 @@ import { DifyLogo } from '@/app/components/base/logo/dify-logo'import { SubmitRequestDropdown } from '@/app/components/plugins/plugin-page/nav-operations'import { MARKETPLACE_CONTAINER_ID } from '../constants'import PluginTypeSwitch from '../plugin-type-switch'-import SearchBoxWrapper from '../search-box/search-box-wrapper'+import { MarketplaceSearchInput } from '../search-input'type DescriptionProps = {isMarketplacePlatform?: boolean@@ -238,15 +238,7 @@ const Description = ({</span></div></div>- <SearchBoxWrapper- wrapperClassName="z-11 w-64 shrink-0"- inputClassName="h-9 w-full rounded-[10px]"- inputElementClassName="text-[14px] leading-5 font-normal"- searchIconClassName="size-4"- placeholder={tCommon(($) => $['placeholder.search'])}- showTags={false}- usedInMarketplace={false}- />+ <MarketplaceSearchInput className="w-64 shrink-0" /><div className="flex h-full shrink-0 items-center justify-end gap-4 pr-3.5 pl-4"><Separator decorative orientation="vertical" className="mx-0 h-4" /><SubmitRequestDropdown dividerAfterFirst />diff --git a/web/app/components/plugins/marketplace/detail-dialog/index.tsx b/web/app/components/plugins/marketplace/detail-dialog/index.tsxindex fa9976d5711..087bd092466 100644--- a/web/app/components/plugins/marketplace/detail-dialog/index.tsx+++ b/web/app/components/plugins/marketplace/detail-dialog/index.tsx@@ -1,11 +1,11 @@'use client'import type { Plugin } from '@/app/components/plugins/types'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useTheme } from 'next-themes'import { useCallback, useEffect, useRef } from 'react'import { useLocale, useTranslation } from '#i18n'import { useOptionalPluginInstallPermission } from '@/app/components/plugins/install-plugin/hooks/use-plugin-install-permission'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { getPluginLinkInMarketplace } from '../utils'import MarketplaceDetailDialogFrame from './frame'import { useSilentMarketplaceInstall } from './use-silent-install'diff --git a/web/app/components/plugins/marketplace/home/catalog-tags-filter.tsx b/web/app/components/plugins/marketplace/home/catalog-tags-filter.tsxindex d0ee51665e3..a835c96c49e 100644--- a/web/app/components/plugins/marketplace/home/catalog-tags-filter.tsx+++ b/web/app/components/plugins/marketplace/home/catalog-tags-filter.tsx@@ -1,15 +1,9 @@'use client'-import { useFilterPluginTags } from '../atoms'-import TagsFilter from '../search-box/tags-filter'+import { PluginTagsFilter } from '../../plugin-tags-filter'+import { useMarketplaceTagsFilter } from '../use-marketplace-tags-filter'export default function CatalogTagsFilter() {- const [tags, setTags] = useFilterPluginTags()- return (- <TagsFilter- tags={tags}- onTagsChange={(next) => setTags(next.length ? next : null)}- usedInMarketplace- />- )+ const { tags, onTagsChange } = useMarketplaceTagsFilter()+ return <PluginTagsFilter value={tags} onValueChange={onTagsChange} variant="labeled" />}diff --git a/web/app/components/plugins/marketplace/home/home-trending-navigation.tsx b/web/app/components/plugins/marketplace/home/home-trending-navigation.tsxindex 1e9ad0986f3..7a86be5d3f1 100644--- a/web/app/components/plugins/marketplace/home/home-trending-navigation.tsx+++ b/web/app/components/plugins/marketplace/home/home-trending-navigation.tsx@@ -3,9 +3,9 @@import type { PluginBanner } from '@dify/contracts/marketplace'import type { RefObject } from 'react'import { cn } from '@langgenius/dify-ui/cn'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from '#i18n'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { MARKETPLACE_CONTAINER_ID } from '../constants'import styles from './home-trending.module.css'diff --git a/web/app/components/plugins/marketplace/search-box/__tests__/index.spec.tsx b/web/app/components/plugins/marketplace/search-box/__tests__/index.spec.tsxdeleted file mode 100644index 826de10f224..00000000000--- a/web/app/components/plugins/marketplace/search-box/__tests__/index.spec.tsx+++ /dev/null@@ -1,84 +0,0 @@-import { render, screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { createRef, useState } from 'react'-import { describe, expect, it, vi } from 'vite-plus/test'-import SearchBox from '../index'--vi.mock('../tags-filter', () => ({- default: () => <div>Tag filter</div>,-}))--const SearchHarness = ({ usedInMarketplace }: { usedInMarketplace: boolean }) => {- const [search, setSearch] = useState('')- return (- <SearchBox- search={search}- onSearchChange={setSearch}- tags={[]}- onTagsChange={vi.fn()}- placeholder="Search plugins"- showTags={false}- usedInMarketplace={usedInMarketplace}- />- )-}--describe('SearchBox', () => {- it.each([true, false])('updates and clears search in marketplace mode %s', async (mode) => {- const user = userEvent.setup()- render(<SearchHarness usedInMarketplace={mode} />)-- const input = screen.getByRole('searchbox', { name: 'Search plugins' })- await user.type(input, 'agent')- expect(input).toHaveValue('agent')-- await user.tab()- const clearButton = screen.getByRole('button', {- name: /^plugin\.clearSearch/,- })- expect(clearButton).toHaveFocus()- await user.keyboard('{Enter}')- expect(input).toHaveValue('')- expect(input).toHaveFocus()- })-- it('opens the custom tool flow from the add button', async () => {- const user = userEvent.setup()- const onShowAddCustomCollectionModal = vi.fn()-- render(- <SearchBox- search=""- onSearchChange={vi.fn()}- tags={[]}- onTagsChange={vi.fn()}- showTags={false}- supportAddCustomTool- onShowAddCustomCollectionModal={onShowAddCustomCollectionModal}- />,- )-- const addButton = screen.getByRole('button', { name: 'tools.addToolModal.custom.tip' })- addButton.focus()- await user.keyboard('{Enter}')- expect(onShowAddCustomCollectionModal).toHaveBeenCalledOnce()- })-- it('exposes the input element through its ref', () => {- const ref = createRef<HTMLInputElement>()-- render(- <SearchBox- ref={ref}- search=""- onSearchChange={vi.fn()}- tags={[]}- onTagsChange={vi.fn()}- placeholder="Search plugins"- showTags={false}- />,- )-- expect(ref.current).toBe(screen.getByRole('searchbox', { name: 'Search plugins' }))- })-})diff --git a/web/app/components/plugins/marketplace/search-box/__tests__/search-box-wrapper.spec.tsx b/web/app/components/plugins/marketplace/search-box/__tests__/search-box-wrapper.spec.tsxdeleted file mode 100644index e888aac2653..00000000000--- a/web/app/components/plugins/marketplace/search-box/__tests__/search-box-wrapper.spec.tsx+++ /dev/null@@ -1,39 +0,0 @@-import { render, screen } from '@testing-library/react'-import { describe, expect, it, vi } from 'vite-plus/test'-import SearchBoxWrapper from '../search-box-wrapper'--const mockHandleSearchPluginTextChange = vi.fn()-const mockHandleFilterPluginTagsChange = vi.fn()-const mockSearchBox = vi.fn()-vi.mock('../../atoms', () => ({- useSearchPluginText: () => ['plugin search', mockHandleSearchPluginTextChange],- useFilterPluginTags: () => [['agent', 'rag'], mockHandleFilterPluginTagsChange],-}))--vi.mock('../index', () => ({- default: (props: Record<string, unknown>) => {- mockSearchBox(props)- return <div data-testid="search-box">search-box</div>- },-}))--describe('SearchBoxWrapper', () => {- it('passes marketplace search state into SearchBox', () => {- render(<SearchBoxWrapper searchIconName="i-ri-search-line" />)-- expect(screen.getByTestId('search-box')).toBeInTheDocument()- expect(mockSearchBox).toHaveBeenCalledWith(- expect.objectContaining({- wrapperClassName: 'z-11 mx-auto w-[640px] shrink-0',- inputClassName: 'w-full',- search: 'plugin search',- onSearchChange: mockHandleSearchPluginTextChange,- tags: ['agent', 'rag'],- onTagsChange: mockHandleFilterPluginTagsChange,- placeholder: 'plugin.searchPlugins',- searchIconName: 'i-ri-search-line',- usedInMarketplace: true,- }),- )- })-})diff --git a/web/app/components/plugins/marketplace/search-box/index.tsx b/web/app/components/plugins/marketplace/search-box/index.tsxdeleted file mode 100644index 6487ac2e16d..00000000000--- a/web/app/components/plugins/marketplace/search-box/index.tsx+++ /dev/null@@ -1,181 +0,0 @@-'use client'-import type { Ref } from 'react'-import { cn } from '@langgenius/dify-ui/cn'-import { IconButton } from '@langgenius/dify-ui/icon-button'-import { Separator } from '@langgenius/dify-ui/separator'-import { useImperativeHandle, useRef } from 'react'-import { useTranslation } from 'react-i18next'-import TagsFilter from './tags-filter'--type SearchBoxProps = {- ref?: Ref<HTMLInputElement>- search: string- onSearchChange: (search: string) => void- wrapperClassName?: string- inputClassName?: string- inputElementClassName?: string- searchIconName?: string- searchIconClassName?: string- tags: string[]- onTagsChange: (tags: string[]) => void- placeholder?: string- supportAddCustomTool?: boolean- usedInMarketplace?: boolean- onShowAddCustomCollectionModal?: () => void- autoFocus?: boolean- showTags?: boolean-}-function SearchBox({- ref,- search,- onSearchChange,- wrapperClassName,- inputClassName,- inputElementClassName,- searchIconName = 'i-ri-search-line',- searchIconClassName,- tags,- onTagsChange,- placeholder = '',- usedInMarketplace = false,- supportAddCustomTool,- onShowAddCustomCollectionModal,- autoFocus = false,- showTags = true,-}: SearchBoxProps) {- const { t } = useTranslation(['plugin', 'tools'])- const accessibleLabel = placeholder || t(($) => $.searchTools, { ns: 'plugin' })!- const inputRef = useRef<HTMLInputElement>(null)- useImperativeHandle(ref, () => inputRef.current as HTMLInputElement, [])-- const handleClear = () => {- onSearchChange('')- inputRef.current?.focus()- }-- return (- <div className={cn('z-11 flex items-center', wrapperClassName)}>- <div- className={cn(- 'flex items-center',- usedInMarketplace &&- 'rounded-xl border border-components-chat-input-border bg-components-panel-bg-blur p-1.5 shadow-md',- !usedInMarketplace &&- 'rounded-lg border border-transparent bg-components-input-bg-normal focus-within:border-components-input-border-active hover:border-components-input-border-hover',- inputClassName,- )}- >- {usedInMarketplace && (- <>- {showTags && (- <>- <TagsFilter tags={tags} onTagsChange={onTagsChange} usedInMarketplace />- <Separator decorative orientation="vertical" className="mx-1 h-3.5" />- </>- )}- <div className="flex grow items-center gap-x-2 p-1">- <input- ref={inputRef}- type="search"- name="query"- autoComplete="off"- aria-label={accessibleLabel}- className={cn(- 'inline-block grow appearance-none bg-transparent body-md-medium text-text-secondary outline-hidden [&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none',- inputElementClassName,- )}- value={search}- onChange={(e) => {- onSearchChange(e.target.value)- }}- placeholder={placeholder}- />- {search && (- <IconButton- variant="ghost"- size="md"- aria-label={t(($) => $.clearSearch, {- ns: 'plugin',- label: accessibleLabel,- })}- onClick={handleClear}- className="shrink-0 focus-visible:ring-inset"- >- <span className="i-ri-close-line size-4" aria-hidden />- </IconButton>- )}- </div>- </>- )}- {!usedInMarketplace && (- <>- <div className="flex h-8 min-w-0 grow items-center pr-2 pl-2">- <span- aria-hidden- className={cn(- searchIconName,- 'size-4 text-components-input-text-placeholder',- searchIconClassName,- )}- />- <input- ref={inputRef}- type="search"- name="query"- autoComplete="off"- aria-label={accessibleLabel}- // oxlint-disable-next-line jsx-a11y/no-autofocus- autoFocus={autoFocus}- className={cn(- 'mr-1 ml-1.5 inline-block min-w-0 grow appearance-none truncate bg-transparent system-sm-regular text-components-input-text-filled caret-primary-600 outline-hidden placeholder:text-components-input-text-placeholder [&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none',- search && 'mr-2',- inputElementClassName,- )}- value={search}- onChange={(e) => {- onSearchChange(e.target.value)- }}- placeholder={placeholder}- />- {search && (- <IconButton- variant="ghost"- size="md"- aria-label={t(($) => $.clearSearch, {- ns: 'plugin',- label: accessibleLabel,- })}- onClick={handleClear}- className="shrink-0 focus-visible:ring-inset"- >- <span className="i-ri-close-line size-4" aria-hidden />- </IconButton>- )}- </div>- {showTags && (- <>- <Separator decorative orientation="vertical" className="mx-0 mr-0.5 h-3.5" />- <TagsFilter tags={tags} onTagsChange={onTagsChange} />- </>- )}- </>- )}- </div>- {supportAddCustomTool && (- <div className="flex shrink-0 items-center">- <IconButton- variant="primary"- size="md"- aria-label={t(($) => $['addToolModal.custom.tip'], { ns: 'tools' })}- className="ml-2 rounded-full"- onClick={onShowAddCustomCollectionModal}- >- <span className="i-ri-add-line size-4" aria-hidden />- </IconButton>- </div>- )}- </div>- )-}--export default SearchBoxdiff --git a/web/app/components/plugins/marketplace/search-box/search-box-wrapper.tsx b/web/app/components/plugins/marketplace/search-box/search-box-wrapper.tsxdeleted file mode 100644index 4d27c3aa78b..00000000000--- a/web/app/components/plugins/marketplace/search-box/search-box-wrapper.tsx+++ /dev/null@@ -1,50 +0,0 @@-'use client'--import { useTranslation } from '#i18n'-import { useFilterPluginTags, useSearchPluginText } from '../atoms'-import SearchBox from './index'--type SearchBoxWrapperProps = {- wrapperClassName?: string- inputClassName?: string- inputElementClassName?: string- searchIconName?: string- searchIconClassName?: string- placeholder?: string- showTags?: boolean- usedInMarketplace?: boolean-}--const SearchBoxWrapper = ({- wrapperClassName = 'z-11 mx-auto w-[640px] shrink-0',- inputClassName = 'w-full',- inputElementClassName,- searchIconName,- searchIconClassName,- placeholder,- showTags = true,- usedInMarketplace = true,-}: SearchBoxWrapperProps) => {- const { t } = useTranslation(['plugin'])- const [searchPluginText, handleSearchPluginTextChange] = useSearchPluginText()- const [filterPluginTags, handleFilterPluginTagsChange] = useFilterPluginTags()-- return (- <SearchBox- wrapperClassName={wrapperClassName}- inputClassName={inputClassName}- inputElementClassName={inputElementClassName}- searchIconName={searchIconName}- searchIconClassName={searchIconClassName}- search={searchPluginText}- onSearchChange={handleSearchPluginTextChange}- tags={filterPluginTags}- onTagsChange={handleFilterPluginTagsChange}- placeholder={placeholder ?? t(($) => $.searchPlugins, { ns: 'plugin' })}- showTags={showTags}- usedInMarketplace={usedInMarketplace}- />- )-}--export default SearchBoxWrapperdiff --git a/web/app/components/plugins/marketplace/search-input.tsx b/web/app/components/plugins/marketplace/search-input.tsxnew file mode 100644index 00000000000..6966fa30435--- /dev/null+++ b/web/app/components/plugins/marketplace/search-input.tsx@@ -0,0 +1,67 @@+'use client'++import { cn } from '@langgenius/dify-ui/cn'+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'+import { Separator } from '@langgenius/dify-ui/separator'+import { useTranslation } from '#i18n'+import { SearchInput } from '@/app/components/base/search-input'+import { useSearchInput } from '@/app/components/base/search-input/use-search-input'+import { PluginTagsFilter } from '../plugin-tags-filter'+import { useSearchPluginText } from './atoms'+import { useMarketplaceTagsFilter } from './use-marketplace-tags-filter'++export function MarketplaceSearchInput({ className }: { className?: string }) {+ const { t } = useTranslation(['common'])+ const [value, onValueChange] = useSearchPluginText()+ const label = t(($) => $['placeholder.search'], { ns: 'common' })++ return (+ <SearchInput+ value={value}+ onValueChange={onValueChange}+ aria-label={label}+ placeholder={label}+ className={cn('h-9 rounded-[10px] [&>input]:text-sm [&>input]:leading-5', className)}+ />+ )+}++export function MarketplacePluginSearch() {+ const { t } = useTranslation(['plugin'])+ const [value, onValueChange] = useSearchPluginText()+ const { tags, onTagsChange } = useMarketplaceTagsFilter()+ const { inputProps, clear } = useSearchInput({ value, onValueChange })+ const label = t(($) => $.searchPlugins, { ns: 'plugin' })++ return (+ <InputGroup className="rounded-xl p-1.5 shadow-md [&>input]:py-1.5 [&>input]:body-md-medium">+ <InputGroupInput+ {...inputProps}+ type="search"+ name="query"+ autoComplete="off"+ enterKeyHint="search"+ aria-label={label}+ placeholder={label}+ className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"+ />+ <InputGroupAddon className="ps-0 pe-2">+ <PluginTagsFilter value={tags} onValueChange={onTagsChange} variant="labeled" />+ <Separator decorative orientation="vertical" className="mx-1 h-3.5" />+ </InputGroupAddon>+ {!!inputProps.value && (+ <InputGroupAddon align="inline-end" className="ps-2 pe-1">+ <IconButton+ size="sm"+ aria-label={t(($) => $.clearSearch, { ns: 'plugin', label })}+ className="text-text-quaternary hover:bg-transparent hover:text-text-tertiary focus-visible:bg-components-input-bg-hover focus-visible:ring-inset"+ onClick={clear}+ >+ <span aria-hidden className="i-ri-close-circle-fill size-4" />+ </IconButton>+ </InputGroupAddon>+ )}+ </InputGroup>+ )+}diff --git a/web/app/components/plugins/marketplace/sticky-search-and-switch-wrapper.tsx b/web/app/components/plugins/marketplace/sticky-search-and-switch-wrapper.tsxindex 099564c425f..eec9359b770 100644--- a/web/app/components/plugins/marketplace/sticky-search-and-switch-wrapper.tsx+++ b/web/app/components/plugins/marketplace/sticky-search-and-switch-wrapper.tsx@@ -2,7 +2,7 @@import { cn } from '@langgenius/dify-ui/cn'import PluginTypeSwitch from './plugin-type-switch'-import SearchBoxWrapper from './search-box/search-box-wrapper'+import { MarketplacePluginSearch } from './search-input'type StickySearchAndSwitchWrapperProps = {pluginTypeSwitchClassName?: string@@ -21,7 +21,9 @@ const StickySearchAndSwitchWrapper = ({pluginTypeSwitchClassName,)}>- <SearchBoxWrapper />+ <div className="mx-auto w-160 max-w-full shrink-0">+ <MarketplacePluginSearch />+ </div><PluginTypeSwitch /></div>)diff --git a/web/app/components/plugins/marketplace/use-marketplace-tags-filter.ts b/web/app/components/plugins/marketplace/use-marketplace-tags-filter.tsnew file mode 100644index 00000000000..a5ef494c713--- /dev/null+++ b/web/app/components/plugins/marketplace/use-marketplace-tags-filter.ts@@ -0,0 +1,19 @@+import { markMarketplaceSiteFilter } from '@/utils/marketplace-site-track'+import { useFilterPluginTags } from './atoms'++export function useMarketplaceTagsFilter() {+ const [tags, setTags] = useFilterPluginTags()+ const onTagsChange = (nextTags: string[]) => {+ const addedTag = nextTags.find((tag) => !tags.includes(tag))+ const removedTag = tags.find((tag) => !nextTags.includes(tag))+ markMarketplaceSiteFilter({+ filter_type: 'category',+ selection_mode: 'multi',+ filter_value: addedTag ?? removedTag ?? nextTags.at(-1) ?? '',+ selected_values: nextTags,+ })+ void setTags(nextTags.length ? nextTags : null)+ }++ return { tags, onTagsChange }+}diff --git a/web/app/components/plugins/plugin-detail-panel/multiple-tool-selector/index.tsx b/web/app/components/plugins/plugin-detail-panel/multiple-tool-selector/index.tsxindex 8b2c36c5361..f9678e93958 100644--- a/web/app/components/plugins/plugin-detail-panel/multiple-tool-selector/index.tsx+++ b/web/app/components/plugins/plugin-detail-panel/multiple-tool-selector/index.tsx@@ -6,11 +6,11 @@ import { Collapsible, CollapsiblePanel, CollapsibleTrigger } from '@langgenius/dimport { IconButton } from '@langgenius/dify-ui/icon-button'import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'import { Separator } from '@langgenius/dify-ui/separator'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import * as React from 'react'import { useTranslation } from 'react-i18next'import ToolSelector from '@/app/components/plugins/plugin-detail-panel/tool-selector'import { useMCPToolAvailability } from '@/app/components/workflow/nodes/_base/components/mcp-tool-availability'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { useAllMCPTools } from '@/service/use-tools'type Props = Readonly<{diff --git a/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsxnew file mode 100644index 00000000000..3b2e0946d9e--- /dev/null+++ b/web/app/components/plugins/plugin-search-input/__tests__/index.spec.tsx@@ -0,0 +1,81 @@+import { fireEvent, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { createRef, useState } from 'react'+import { describe, expect, it, vi } from 'vite-plus/test'+import { PluginSearchInput } from '..'++function SearchHarness() {+ const [value, setValue] = useState('agent')+ const [tags, setTags] = useState(['rag'])+ return (+ <PluginSearchInput+ value={value}+ onValueChange={setValue}+ tags={tags}+ onTagsChange={setTags}+ placeholder="Search plugins"+ />+ )+}++describe('PluginSearchInput', () => {+ it('clears search from the keyboard without clearing tags, and restores input focus', async () => {+ const user = userEvent.setup()+ render(<SearchHarness />)+ const input = screen.getByRole('searchbox', { name: 'Search plugins' })+ await user.click(input)+ await user.tab()+ expect(screen.getByRole('button', { name: /^plugin\.clearSearch/ })).toHaveFocus()+ await user.keyboard('{Enter}')+ expect(input).toHaveValue('')+ expect(input).toHaveFocus()+ expect(screen.getByRole('button', { name: 'pluginTags.tags.rag' })).toBeInTheDocument()+ })++ it('keeps tag selection, popup search and tag clearing independent of the main input', async () => {+ const user = userEvent.setup()+ render(<SearchHarness />)+ const input = screen.getByRole('searchbox', { name: 'Search plugins' })+ const trigger = screen.getByRole('button', { name: 'pluginTags.tags.rag' })+ await user.click(trigger)+ const tagSearch = await screen.findByRole('searchbox', { name: 'pluginTags.searchTags' })+ await user.type(tagSearch, 'agent')+ expect(tagSearch).toHaveFocus()+ await user.click(screen.getByRole('checkbox', { name: 'pluginTags.tags.agent' }))+ await user.keyboard('{Escape}')+ expect(trigger).toHaveFocus()+ expect(input).toHaveValue('agent')+ await user.tab()+ expect(screen.getByRole('button', { name: /^pluginTags\.clearSelectedTags/ })).toHaveFocus()+ await user.keyboard('{Enter}')+ expect(screen.getByRole('button', { name: 'pluginTags.allTags' })).toHaveFocus()+ expect(input).toHaveValue('agent')+ expect(+ screen.queryByRole('searchbox', { name: 'pluginTags.searchTags' }),+ ).not.toBeInTheDocument()+ })++ it('commits composed text once and exposes the native input for picker focus', () => {+ const onValueChange = vi.fn()+ const ref = createRef<HTMLInputElement>()+ render(+ <PluginSearchInput+ ref={ref}+ value=""+ onValueChange={onValueChange}+ tags={[]}+ onTagsChange={vi.fn()}+ placeholder="Search plugins"+ />,+ )+ const input = screen.getByRole('searchbox', { name: 'Search plugins' })+ expect(ref.current).toBe(input)+ fireEvent.compositionStart(input)+ fireEvent.change(input, { target: { value: '搜索' } })+ expect(input).toHaveValue('搜索')+ expect(onValueChange).not.toHaveBeenCalled()+ fireEvent.compositionEnd(input)+ fireEvent.change(input, { target: { value: '搜索' } })+ expect(onValueChange).toHaveBeenCalledExactlyOnceWith('搜索')+ })+})diff --git a/web/app/components/plugins/plugin-search-input/index.tsx b/web/app/components/plugins/plugin-search-input/index.tsxnew file mode 100644index 00000000000..ebe9cd6c0ab--- /dev/null+++ b/web/app/components/plugins/plugin-search-input/index.tsx@@ -0,0 +1,71 @@+'use client'++import type { Ref } from 'react'+import { IconButton } from '@langgenius/dify-ui/icon-button'+import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'+import { Separator } from '@langgenius/dify-ui/separator'+import { useTranslation } from 'react-i18next'+import { useSearchInput } from '@/app/components/base/search-input/use-search-input'+import { PluginTagsFilter } from '../plugin-tags-filter'++type PluginSearchInputProps = {+ ref?: Ref<HTMLInputElement>+ value: string+ onValueChange: (value: string) => void+ tags: string[]+ onTagsChange: (tags: string[]) => void+ placeholder: string+ className?: string+ autoFocus?: boolean+}++export function PluginSearchInput({+ ref,+ value,+ onValueChange,+ tags,+ onTagsChange,+ placeholder,+ className,+ autoFocus,+}: PluginSearchInputProps) {+ const { t } = useTranslation(['plugin'])+ const { inputProps, clear } = useSearchInput({ value, onValueChange, ref })++ return (+ <InputGroup className={className}>+ <InputGroupInput+ {...inputProps}+ type="search"+ name="query"+ autoComplete="off"+ enterKeyHint="search"+ aria-label={placeholder}+ placeholder={placeholder}+ // oxlint-disable-next-line jsx-a11y/no-autofocus -- Picker owners request focus when replacing an already-focused menu.+ autoFocus={autoFocus}+ className="[&::-webkit-search-cancel-button]:appearance-none [&::-webkit-search-decoration]:appearance-none"+ />+ <InputGroupAddon className="ps-1.75 pe-1.25">+ <span+ aria-hidden+ className="i-ri-search-line size-4 text-components-input-text-placeholder"+ />+ </InputGroupAddon>+ <InputGroupAddon align="inline-end" className="gap-1 ps-0.75 pe-0.5">+ {!!inputProps.value && (+ <IconButton+ size="sm"+ aria-label={t(($) => $.clearSearch, { ns: 'plugin', label: placeholder })}+ className="text-text-quaternary hover:bg-transparent hover:text-text-tertiary focus-visible:bg-components-input-bg-hover focus-visible:ring-inset"+ onClick={clear}+ >+ <span aria-hidden className="i-ri-close-circle-fill size-4" />+ </IconButton>+ )}+ <Separator decorative orientation="vertical" className="mx-0 h-3.5" />+ <PluginTagsFilter value={tags} onValueChange={onTagsChange} />+ </InputGroupAddon>+ </InputGroup>+ )+}diff --git a/web/app/components/plugins/marketplace/search-box/trigger/__tests__/tool-selector.spec.tsx b/web/app/components/plugins/plugin-tags-filter/__tests__/compact-trigger.spec.tsxsimilarity index 80%rename from web/app/components/plugins/marketplace/search-box/trigger/__tests__/tool-selector.spec.tsxrename to web/app/components/plugins/plugin-tags-filter/__tests__/compact-trigger.spec.tsxindex ceaf6ba0bff..673222f0805 100644--- a/web/app/components/plugins/marketplace/search-box/trigger/__tests__/tool-selector.spec.tsx+++ b/web/app/components/plugins/plugin-tags-filter/__tests__/compact-trigger.spec.tsx@@ -1,10 +1,10 @@-import type { Tag } from '../../../../hooks'+import type { Tag } from '../../hooks'import { Popover, PopoverContent } from '@langgenius/dify-ui/popover'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { describe, expect, it, vi } from 'vite-plus/test'-import ToolSelectorTrigger from '../tool-selector'+import CompactTrigger from '../compact-trigger'const tagsMap: Record<string, Tag> = {agent: { name: 'agent', label: 'Agent' },@@ -12,16 +12,11 @@ const tagsMap: Record<string, Tag> = {search: { name: 'search', label: 'Search' },}-describe('ToolSelectorTrigger', () => {+describe('CompactTrigger', () => {it('renders only icon when no tags are selected', () => {render(<Popover>- <ToolSelectorTrigger- selectedTagsLength={0}- tags={[]}- tagsMap={tagsMap}- onTagsChange={vi.fn()}- />+ <CompactTrigger tags={[]} tagsMap={tagsMap} onTagsChange={vi.fn()} /></Popover>,)@@ -35,8 +30,7 @@ describe('ToolSelectorTrigger', () => {it('renders selected tag labels and overflow count', () => {render(<Popover>- <ToolSelectorTrigger- selectedTagsLength={3}+ <CompactTriggertags={['agent', 'rag', 'search']}tagsMap={tagsMap}onTagsChange={vi.fn()}@@ -57,12 +51,7 @@ describe('ToolSelectorTrigger', () => {render(<Popover>- <ToolSelectorTrigger- selectedTagsLength={0}- tags={[]}- tagsMap={tagsMap}- onTagsChange={vi.fn()}- />+ <CompactTrigger tags={[]} tagsMap={tagsMap} onTagsChange={vi.fn()} /><PopoverContent>Tag options</PopoverContent></Popover>,)@@ -84,12 +73,7 @@ describe('ToolSelectorTrigger', () => {const [tags, setTags] = useState(['agent'])return (<Popover>- <ToolSelectorTrigger- selectedTagsLength={tags.length}- tags={tags}- tagsMap={tagsMap}- onTagsChange={setTags}- />+ <CompactTrigger tags={tags} tagsMap={tagsMap} onTagsChange={setTags} /></Popover>)}diff --git a/web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsx b/web/app/components/plugins/plugin-tags-filter/__tests__/index.spec.tsxsimilarity index 88%rename from web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsxrename to web/app/components/plugins/plugin-tags-filter/__tests__/index.spec.tsxindex 57eba333983..6889ae311d5 100644--- a/web/app/components/plugins/marketplace/search-box/__tests__/tags-filter.spec.tsx+++ b/web/app/components/plugins/plugin-tags-filter/__tests__/index.spec.tsx@@ -1,7 +1,7 @@import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import TagsFilter from '../tags-filter'+import { PluginTagsFilter } from '..'const { mockTranslate } = vi.hoisted(() => ({mockTranslate: vi.fn((key: string, options?: { ns?: string }) =>@@ -33,7 +33,7 @@ vi.mock('@/app/components/plugins/hooks', () => ({}),}))-describe('TagsFilter', () => {+describe('PluginTagsFilter', () => {const ensurePopoverOpen = async (user: ReturnType<typeof userEvent.setup>) => {if (!screen.queryByRole('searchbox', { name: 'pluginTags.searchTags' }))await user.click(screen.getByRole('button', { name: 'pluginTags.allTags' }))@@ -50,7 +50,7 @@ describe('TagsFilter', () => {it('filters tag options by search text', async () => {const user = userEvent.setup()- render(<TagsFilter tags={[]} onTagsChange={vi.fn()} />)+ render(<PluginTagsFilter value={[]} onValueChange={vi.fn()} />)const search = await ensurePopoverOpen(user)expect(screen.getByRole('checkbox', { name: 'Agent' })).toBeInTheDocument()@@ -67,13 +67,13 @@ describe('TagsFilter', () => {it('adds and removes selected tags when options are clicked', async () => {const user = userEvent.setup()const onTagsChange = vi.fn()- const { rerender } = render(<TagsFilter tags={['agent']} onTagsChange={onTagsChange} />)+ const { rerender } = render(<PluginTagsFilter value={['agent']} onValueChange={onTagsChange} />)await user.click(screen.getByRole('button', { name: 'Agent' }))await user.click(screen.getByRole('checkbox', { name: 'Agent' }))expect(onTagsChange).toHaveBeenCalledWith([])- rerender(<TagsFilter tags={['agent']} onTagsChange={onTagsChange} />)+ rerender(<PluginTagsFilter value={['agent']} onValueChange={onTagsChange} />)await user.click(screen.getByRole('checkbox', { name: 'RAG' }))expect(onTagsChange).toHaveBeenCalledWith(['agent', 'rag'])})@@ -82,7 +82,7 @@ describe('TagsFilter', () => {const user = userEvent.setup()mockTranslate.mockImplementation(() => undefined as unknown as string)- render(<TagsFilter tags={[]} onTagsChange={vi.fn()} />)+ render(<PluginTagsFilter value={[]} onValueChange={vi.fn()} />)await user.click(screen.getByRole('button'))expect(screen.getByRole('searchbox')).toHaveAttribute('placeholder', '')diff --git a/web/app/components/plugins/marketplace/search-box/trigger/__tests__/marketplace.spec.tsx b/web/app/components/plugins/plugin-tags-filter/__tests__/labeled-trigger.spec.tsxsimilarity index 77%rename from web/app/components/plugins/marketplace/search-box/trigger/__tests__/marketplace.spec.tsxrename to web/app/components/plugins/plugin-tags-filter/__tests__/labeled-trigger.spec.tsxindex 083e6d753be..fce92d747fd 100644--- a/web/app/components/plugins/marketplace/search-box/trigger/__tests__/marketplace.spec.tsx+++ b/web/app/components/plugins/plugin-tags-filter/__tests__/labeled-trigger.spec.tsx@@ -1,10 +1,10 @@-import type { Tag } from '../../../../hooks'+import type { Tag } from '../../hooks'import { Popover } from '@langgenius/dify-ui/popover'import { render, screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useState } from 'react'import { describe, expect, it, vi } from 'vite-plus/test'-import MarketplaceTrigger from '../marketplace'+import LabeledTrigger from '../labeled-trigger'const tagsMap: Record<string, Tag> = {agent: { name: 'agent', label: 'Agent' },@@ -12,16 +12,11 @@ const tagsMap: Record<string, Tag> = {search: { name: 'search', label: 'Search' },}-describe('MarketplaceTrigger', () => {+describe('LabeledTrigger', () => {it('shows all-tags text when no tags are selected', () => {render(<Popover>- <MarketplaceTrigger- selectedTagsLength={0}- tags={[]}- tagsMap={tagsMap}- onTagsChange={vi.fn()}- />+ <LabeledTrigger tags={[]} tagsMap={tagsMap} onTagsChange={vi.fn()} /></Popover>,)@@ -34,8 +29,7 @@ describe('MarketplaceTrigger', () => {it('shows selected tag labels and overflow count', () => {render(<Popover>- <MarketplaceTrigger- selectedTagsLength={3}+ <LabeledTriggertags={['agent', 'rag', 'search']}tagsMap={tagsMap}onTagsChange={vi.fn()}@@ -54,12 +48,7 @@ describe('MarketplaceTrigger', () => {const [tags, setTags] = useState(['agent'])return (<Popover>- <MarketplaceTrigger- selectedTagsLength={tags.length}- tags={tags}- tagsMap={tagsMap}- onTagsChange={setTags}- />+ <LabeledTrigger tags={tags} tagsMap={tagsMap} onTagsChange={setTags} /></Popover>)}@@ -83,12 +72,7 @@ describe('MarketplaceTrigger', () => {render(<Popover>- <MarketplaceTrigger- selectedTagsLength={0}- tags={[]}- tagsMap={tagsMap}- onTagsChange={vi.fn()}- />+ <LabeledTrigger tags={[]} tagsMap={tagsMap} onTagsChange={vi.fn()} /></Popover>,)diff --git a/web/app/components/plugins/marketplace/search-box/trigger/tool-selector.tsx b/web/app/components/plugins/plugin-tags-filter/compact-trigger.tsxsimilarity index 90%rename from web/app/components/plugins/marketplace/search-box/trigger/tool-selector.tsxrename to web/app/components/plugins/plugin-tags-filter/compact-trigger.tsxindex 070058af986..498b4fa8506 100644--- a/web/app/components/plugins/marketplace/search-box/trigger/tool-selector.tsx+++ b/web/app/components/plugins/plugin-tags-filter/compact-trigger.tsx@@ -1,4 +1,4 @@-import type { Tag } from '../../../hooks'+import type { Tag } from '../hooks'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'@@ -6,20 +6,15 @@ import { PopoverTrigger } from '@langgenius/dify-ui/popover'import { memo, useEffect, useRef } from 'react'import { useTranslation } from '#i18n'-type ToolSelectorTriggerProps = {- selectedTagsLength: number+type CompactTriggerProps = {tags: string[]tagsMap: Record<string, Tag>onTagsChange: (tags: string[]) => void}-function ToolSelectorTrigger({- selectedTagsLength,- tags,- tagsMap,- onTagsChange,-}: ToolSelectorTriggerProps) {+function CompactTrigger({ tags, tagsMap, onTagsChange }: CompactTriggerProps) {const { t } = useTranslation(['pluginTags'])+ const selectedTagsLength = tags.lengthconst triggerRef = useRef<HTMLButtonElement>(null)const shouldRestoreFocusRef = useRef(false)const selectedTagLabels = tags.map((tag) => tagsMap[tag]?.label).filter(Boolean)@@ -35,7 +30,7 @@ function ToolSelectorTrigger({}, [selectedTagsLength])return (- <div className="relative mr-1 inline-flex h-7 max-w-32 shrink-0 items-center">+ <div className="relative inline-flex h-7 max-w-32 shrink-0 items-center"><PopoverTriggerrender={<Button@@ -100,4 +95,4 @@ function ToolSelectorTrigger({)}-export default memo(ToolSelectorTrigger)+export default memo(CompactTrigger)diff --git a/web/app/components/plugins/marketplace/search-box/tags-filter.tsx b/web/app/components/plugins/plugin-tags-filter/index.tsxsimilarity index 65%rename from web/app/components/plugins/marketplace/search-box/tags-filter.tsxrename to web/app/components/plugins/plugin-tags-filter/index.tsxindex 85b02bc8fa3..569aed801b0 100644--- a/web/app/components/plugins/marketplace/search-box/tags-filter.tsx+++ b/web/app/components/plugins/plugin-tags-filter/index.tsx@@ -7,52 +7,33 @@ import { Popover, PopoverContent } from '@langgenius/dify-ui/popover'import { useState } from 'react'import { useTranslation } from '#i18n'import { useTags } from '@/app/components/plugins/hooks'-import { markMarketplaceSiteFilter } from '@/utils/marketplace-site-track'-import MarketplaceTrigger from './trigger/marketplace'-import ToolSelectorTrigger from './trigger/tool-selector'+import CompactTrigger from './compact-trigger'+import LabeledTrigger from './labeled-trigger'-type TagsFilterProps = {- tags: string[]- onTagsChange: (tags: string[]) => void- usedInMarketplace?: boolean+type PluginTagsFilterProps = {+ value: string[]+ onValueChange: (tags: string[]) => void+ variant?: 'compact' | 'labeled'}-function TagsFilter({ tags, onTagsChange, usedInMarketplace = false }: TagsFilterProps) {+export function PluginTagsFilter({+ value,+ onValueChange,+ variant = 'compact',+}: PluginTagsFilterProps) {const { t } = useTranslation(['pluginTags'])const [searchText, setSearchText] = useState('')const { tags: options, tagsMap } = useTags()const filteredOptions = options.filter((option) =>option.label.toLowerCase().includes(searchText.toLowerCase()),)- const selectedTagsLength = tags.length- const handleTagsChange = (nextTags: string[]) => {- const addedTag = nextTags.find((tag) => !tags.includes(tag))- const removedTag = tags.find((tag) => !nextTags.includes(tag))- markMarketplaceSiteFilter({- filter_type: 'category',- selection_mode: 'multi',- filter_value: addedTag ?? removedTag ?? nextTags.at(-1) ?? '',- selected_values: nextTags,- })- onTagsChange(nextTags)- }return (<Popover>- {usedInMarketplace && (- <MarketplaceTrigger- selectedTagsLength={selectedTagsLength}- tags={tags}- tagsMap={tagsMap}- onTagsChange={handleTagsChange}- />+ {variant === 'labeled' && (+ <LabeledTrigger tags={value} tagsMap={tagsMap} onTagsChange={onValueChange} />)}- {!usedInMarketplace && (- <ToolSelectorTrigger- selectedTagsLength={selectedTagsLength}- tags={tags}- tagsMap={tagsMap}- onTagsChange={handleTagsChange}- />+ {variant === 'compact' && (+ <CompactTrigger tags={value} tagsMap={tagsMap} onTagsChange={onValueChange} />)}<PopoverContentplacement="bottom-start"@@ -84,8 +65,8 @@ function TagsFilter({ tags, onTagsChange, usedInMarketplace = false }: TagsFilte</div><CheckboxGrouparia-label={t(($) => $.allTags, { ns: 'pluginTags' })}- value={tags}- onValueChange={handleTagsChange}+ value={value}+ onValueChange={(nextTags) => onValueChange(nextTags)}className="max-h-112 overflow-y-auto p-1">{filteredOptions.map((option) => (@@ -103,5 +84,3 @@ function TagsFilter({ tags, onTagsChange, usedInMarketplace = false }: TagsFilte</Popover>)}--export default TagsFilterdiff --git a/web/app/components/plugins/marketplace/search-box/trigger/marketplace.tsx b/web/app/components/plugins/plugin-tags-filter/labeled-trigger.tsxsimilarity index 93%rename from web/app/components/plugins/marketplace/search-box/trigger/marketplace.tsxrename to web/app/components/plugins/plugin-tags-filter/labeled-trigger.tsxindex 3cc82adbaf4..b5f97ebf86e 100644--- a/web/app/components/plugins/marketplace/search-box/trigger/marketplace.tsx+++ b/web/app/components/plugins/plugin-tags-filter/labeled-trigger.tsx@@ -1,4 +1,4 @@-import type { Tag } from '../../../hooks'+import type { Tag } from '../hooks'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'@@ -6,20 +6,15 @@ import { PopoverTrigger } from '@langgenius/dify-ui/popover'import { memo, useEffect, useRef } from 'react'import { useTranslation } from '#i18n'-type MarketplaceTriggerProps = {- selectedTagsLength: number+type LabeledTriggerProps = {tags: string[]tagsMap: Record<string, Tag>onTagsChange: (tags: string[]) => void}-function MarketplaceTrigger({- selectedTagsLength,- tags,- tagsMap,- onTagsChange,-}: MarketplaceTriggerProps) {+function LabeledTrigger({ tags, tagsMap, onTagsChange }: LabeledTriggerProps) {const { t } = useTranslation(['pluginTags'])+ const selectedTagsLength = tags.lengthconst triggerRef = useRef<HTMLButtonElement>(null)const shouldRestoreFocusRef = useRef(false)const selectedTagLabels = tags.map((tag) => tagsMap[tag]?.label).filter(Boolean)@@ -108,4 +103,4 @@ function MarketplaceTrigger({)}-export default memo(MarketplaceTrigger)+export default memo(LabeledTrigger)diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsxindex d36315362e8..00ed78120ed 100644--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/__tests__/tool-picker.spec.tsx@@ -1,5 +1,6 @@import type { PluginDetail } from '@/app/components/plugins/types'import { fireEvent, render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { PluginCategoryEnum, PluginSource } from '@/app/components/plugins/types'import ToolPicker from '../tool-picker'@@ -19,34 +20,6 @@ vi.mock('@/app/components/base/loading-placeholder', () => ({LoadingPlaceholder: () => <div data-testid="loading">loading</div>,}))-vi.mock('@/app/components/plugins/marketplace/search-box', () => ({- default: ({- search,- tags,- onSearchChange,- onTagsChange,- placeholder,- }: {- search: string- tags: string[]- onSearchChange: (value: string) => void- onTagsChange: (value: string[]) => void- placeholder: string- }) => (- <div data-testid="search-box">- <div>{placeholder}</div>- <div data-testid="search-state">{search}</div>- <div data-testid="tags-state">{tags.join(',')}</div>- <button data-testid="set-query" onClick={() => onSearchChange('tool-rag')}>- set-query- </button>- <button data-testid="set-tags" onClick={() => onTagsChange(['rag'])}>- set-tags- </button>- </div>- ),-}))-vi.mock('../no-data-placeholder', () => ({default: ({ noPlugins }: { noPlugins?: boolean }) => (<div data-testid="no-data">{String(noPlugins)}</div>@@ -144,7 +117,8 @@ describe('ToolPicker', () => {expect(screen.getByTestId('no-data')).toHaveTextContent('true')})- it('filters by plugin type, tags, and query', () => {+ it('filters by plugin type, tags, and query', async () => {+ const user = userEvent.setup()mockInstalledPluginList.data = {plugins: [createPlugin('tool-search', PluginSource.marketplace, 'tool', ['search']),@@ -174,13 +148,16 @@ describe('ToolPicker', () => {fireEvent.click(screen.getByText('plugin.category.tools'))expect(screen.getAllByTestId('tool-item')).toHaveLength(2)- fireEvent.click(screen.getByTestId('set-tags'))+ await user.click(screen.getByRole('button', { name: 'pluginTags.allTags' }))+ await user.click(screen.getByRole('checkbox', { name: 'pluginTags.tags.rag' }))expect(screen.getAllByTestId('tool-item')).toHaveLength(1)expect(screen.getByText('tool-rag')).toBeInTheDocument()+ await user.keyboard('{Escape}')- fireEvent.click(screen.getByTestId('set-query'))+ const search = screen.getByRole('searchbox', { name: 'plugin.searchTools' })+ await user.type(search, 'tool-rag')expect(screen.getAllByTestId('tool-item')).toHaveLength(1)- expect(screen.getByTestId('search-state')).toHaveTextContent('tool-rag')+ expect(search).toHaveValue('tool-rag')})it('limits selectable integrations to the provided integration category', () => {diff --git a/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-picker.tsx b/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-picker.tsxindex d954cd9b8ed..707ed45838c 100644--- a/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-picker.tsx+++ b/web/app/components/plugins/reference-setting-modal/auto-update-setting/tool-picker.tsx@@ -8,7 +8,7 @@ import * as React from 'react'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import SearchBox from '@/app/components/plugins/marketplace/search-box'+import { PluginSearchInput } from '@/app/components/plugins/plugin-search-input'import { useInstalledPluginList } from '@/service/use-plugins'import { PLUGIN_TYPE_SEARCH_MAP } from '../../marketplace/constants'import { PluginSource } from '../../types'@@ -117,13 +117,12 @@ const ToolPicker: FC<Props> = ({<div className="relative min-h-20 w-108 max-w-[calc(100vw-32px)] overflow-hidden rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg backdrop-blur-xs"><div className="flex flex-col overflow-hidden rounded-t-lg border-b border-divider-subtle bg-background-section-burn"><div className="bg-components-panel-bg p-2">- <SearchBox- search={query}- onSearchChange={setQuery}+ <PluginSearchInput+ value={query}+ onValueChange={setQuery}tags={tags}onTagsChange={setTags}placeholder={t(($) => $.searchTools, { ns: 'plugin' })!}- inputClassName="w-full"/></div><div className="flex items-center justify-between bg-components-panel-bg px-3 pb-2">diff --git a/web/app/components/workflow/block-selector/tabs.tsx b/web/app/components/workflow/block-selector/tabs.tsxindex 4a207005796..309512e8d34 100644--- a/web/app/components/workflow/block-selector/tabs.tsx+++ b/web/app/components/workflow/block-selector/tabs.tsx@@ -7,7 +7,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooimport { useState } from 'react'import { useTranslation } from 'react-i18next'import { SearchInput } from '@/app/components/base/search-input'-import SearchBox from '@/app/components/plugins/marketplace/search-box'+import { PluginSearchInput } from '@/app/components/plugins/plugin-search-input'import AllStartBlocks from './all-start-blocks'import Blocks from './blocks'import DataSources from './data-sources'@@ -127,28 +127,26 @@ function BlockSelectorPanels({const filter = (() => {if (tab === TabType.Start) {return (- <SearchBox+ <PluginSearchInputref={inputRef}- search={searchText}- onSearchChange={(value) => setSearchText(tab, value)}+ value={searchText}+ onValueChange={(value) => setSearchText(tab, value)}tags={tags}onTagsChange={(value) => setTags(tab, value)}placeholder={t(($) => $['tabs.searchTrigger'], { ns: 'workflow' })}- inputClassName="grow"/>)}if (tab === TabType.Tools) {return (- <SearchBox+ <PluginSearchInputref={inputRef}- search={searchText}- onSearchChange={(value) => setSearchText(tab, value)}+ value={searchText}+ onValueChange={(value) => setSearchText(tab, value)}tags={tags}onTagsChange={(value) => setTags(tab, value)}placeholder={t(($) => $.searchTools, { ns: 'plugin' })!}- inputClassName="grow"/>)}diff --git a/web/app/components/workflow/block-selector/tool-picker.tsx b/web/app/components/workflow/block-selector/tool-picker.tsxindex 854f8f5c14a..2836cefa1ee 100644--- a/web/app/components/workflow/block-selector/tool-picker.tsx+++ b/web/app/components/workflow/block-selector/tool-picker.tsx@@ -5,13 +5,14 @@ import type { ToolDefaultValue, ToolValue } from './types'import type { CustomCollectionBackend } from '@/app/components/tools/types'import type { BlockEnum, OnSelectBlock } from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'+import { IconButton } from '@langgenius/dify-ui/icon-button'import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'import dynamic from 'next/dynamic'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import SearchBox from '@/app/components/plugins/marketplace/search-box'+import { PluginSearchInput } from '@/app/components/plugins/plugin-search-input'import EditCustomToolModal from '@/app/components/tools/edit-custom-collection-modal'import { useCanManageTools } from '@/app/components/tools/hooks/use-tool-permissions'import { toast } from '@/app/notifications'@@ -64,7 +65,7 @@ export function ToolPickerContent({selectedTools,panelClassName,}: ToolPickerContentProps) {- const { t } = useTranslation(['common', 'plugin'])+ const { t } = useTranslation(['common', 'plugin', 'tools'])const [searchText, setSearchText] = useState('')const [tags, setTags] = useState<string[]>([])const canManageTools = useCanManageTools()@@ -160,21 +161,30 @@ export function ToolPickerContent({panelClassName,)}>- <div className="p-2 pb-1">- <SearchBox- search={searchText}- onSearchChange={setSearchText}+ <div className="flex items-center gap-2 p-2 pb-1">+ <PluginSearchInput+ value={searchText}+ onValueChange={setSearchText}tags={tags}onTagsChange={setTags}placeholder={t(($) => $.searchTools, { ns: 'plugin' })!}- supportAddCustomTool={supportAddCustomTool && canManageTools}- onShowAddCustomCollectionModal={showEditCustomCollectionModal}// The picker replaces the focused menu item inside an already-open popover.// Focusing search keeps keyboard users in the same add-tool workflow.- /* oxlint-disable-next-line jsx-a11y/no-autofocus */+ /* oxlint-disable-next-line jsx-a11y/no-autofocus -- The picker replaces the focused menu item in an open popover. */autoFocus={focusSearchOnMount}- inputClassName="grow"+ className="flex-1"/>+ {supportAddCustomTool && canManageTools && (+ <IconButton+ variant="primary"+ size="md"+ aria-label={t(($) => $['addToolModal.custom.tip'], { ns: 'tools' })}+ className="shrink-0 rounded-full"+ onClick={showEditCustomCollectionModal}+ >+ <span className="i-ri-add-line size-4" aria-hidden />+ </IconButton>+ )}</div><ToolBrowserclassName="mt-1"diff --git a/web/app/components/workflow/hooks/use-serial-async-callback.ts b/web/app/components/workflow/hooks/use-serial-async-callback.tsindex 33aa824f912..b88d75e1f49 100644--- a/web/app/components/workflow/hooks/use-serial-async-callback.ts+++ b/web/app/components/workflow/hooks/use-serial-async-callback.ts@@ -1,5 +1,5 @@+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useCallback } from 'react'-import { useRefWithInit } from '@/hooks/use-ref-with-init'export const useSerialAsyncCallback = <Args extends any[], Result = void>(fn: (...args: Args) => Promise<Result> | Result,diff --git a/web/app/components/workflow/hooks/use-workflow-history.ts b/web/app/components/workflow/hooks/use-workflow-history.tsindex 011f4dfb0ee..16c23524c78 100644--- a/web/app/components/workflow/hooks/use-workflow-history.ts+++ b/web/app/components/workflow/hooks/use-workflow-history.ts@@ -1,9 +1,9 @@import type { WorkflowHistoryEventMeta } from '../store/workflow/history-slice'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { debounce } from 'es-toolkit/compat'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { useWorkflowHistoryStore } from '../workflow-history-store'/**diff --git a/web/app/components/workflow/nodes/agent-v2/panel.tsx b/web/app/components/workflow/nodes/agent-v2/panel.tsxindex 24d8d5733bd..d4ad1cf8243 100644--- a/web/app/components/workflow/nodes/agent-v2/panel.tsx+++ b/web/app/components/workflow/nodes/agent-v2/panel.tsx@@ -7,6 +7,7 @@ import type { AgentRosterNodeData } from '../../block-selector/types'import type { NodePanelProps } from '../../types'import type { AgentV2NodeType } from './types'import type { AgentOutputTypeOptionValue } from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useMutation } from '@tanstack/react-query'import { produce } from 'immer'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'@@ -19,7 +20,6 @@ import {} from '@/app/components/base/prompt-editor/plugins/agent-output-block/utils'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useStore } from '@/app/components/workflow/store'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { consoleQuery } from '@/service/console'import { FlowType } from '@/types/common'import { useNodeDataUpdate } from '../../hooks/use-node-data-update'diff --git a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/context.tsx b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/context.tsxindex df817a11852..fa7f6794871 100644--- a/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/context.tsx+++ b/web/app/components/workflow/nodes/llm/components/json-schema-config-modal/visual-editor/context.tsx@@ -1,7 +1,7 @@+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { noop } from 'es-toolkit/function'import { createContext, use } from 'react'import { useMitt } from '@/hooks/use-mitt'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { createVisualEditorStore } from './store'type VisualEditorStore = ReturnType<typeof createVisualEditorStore>diff --git a/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsxindex 28e5e04b630..883061e4391 100644--- a/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx+++ b/web/app/components/workflow/nodes/start-placeholder/__tests__/panel.spec.tsx@@ -22,10 +22,6 @@ vi.mock('reactflow', () => ({}),}))-vi.mock('@/app/components/plugins/marketplace/search-box', () => ({- default: () => <input aria-label="Search trigger" />,-}))-vi.mock('@/app/components/workflow/block-selector/all-start-blocks', () => ({default: ({ onSelect }: { onSelect: (type: BlockEnum) => void }) => (<button type="button" onClick={() => onSelect(BlockEnum.Start)}>diff --git a/web/app/components/workflow/nodes/start-placeholder/panel.tsx b/web/app/components/workflow/nodes/start-placeholder/panel.tsxindex 5825666b25f..e924fe15b25 100644--- a/web/app/components/workflow/nodes/start-placeholder/panel.tsx+++ b/web/app/components/workflow/nodes/start-placeholder/panel.tsx@@ -9,7 +9,7 @@ import * as React from 'react'import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'import { useStoreApi } from 'reactflow'-import SearchBox from '@/app/components/plugins/marketplace/search-box'+import { PluginSearchInput } from '@/app/components/plugins/plugin-search-input'import AllStartBlocks from '@/app/components/workflow/block-selector/all-start-blocks'import { useHooksStore } from '@/app/components/workflow/hooks-store'import { useStore as useWorkflowStore } from '@/app/components/workflow/store'@@ -134,13 +134,12 @@ const Panel: FC<NodePanelProps<StartPlaceholderNodeType>> = ({ id }) => {return (<div className="flex h-full min-h-0 flex-col"><div className="px-3 py-2">- <SearchBox- search={searchText}- onSearchChange={setSearchText}+ <PluginSearchInput+ value={searchText}+ onValueChange={setSearchText}tags={tags}onTagsChange={setTags}placeholder={t(($) => $['tabs.searchTrigger'], { ns: 'workflow' })}- inputClassName="grow"/></div><div className="min-h-0 flex-1 overflow-hidden">diff --git a/web/app/components/workflow/note-node/note-editor/context.tsx b/web/app/components/workflow/note-node/note-editor/context.tsxindex f2caeb631d0..68458bf58c7 100644--- a/web/app/components/workflow/note-node/note-editor/context.tsx+++ b/web/app/components/workflow/note-node/note-editor/context.tsx@@ -1,12 +1,12 @@'use client'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { LinkNode } from '@lexical/link'import { ListItemNode, ListNode } from '@lexical/list'import { LexicalComposer } from '@lexical/react/LexicalComposer'import { useLexicalComposerContext } from '@lexical/react/LexicalComposerContext'import { $getRoot } from 'lexical'import { createContext, memo, useEffect, useRef } from 'react'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { createNoteEditorStore } from './store'import theme from './theme'diff --git a/web/app/components/workflow/panel/env-panel/index.tsx b/web/app/components/workflow/panel/env-panel/index.tsxindex dc96245a305..f2ee348c3d1 100644--- a/web/app/components/workflow/panel/env-panel/index.tsx+++ b/web/app/components/workflow/panel/env-panel/index.tsx@@ -5,6 +5,7 @@ import type {LLMEnvironmentVariableValue,} from '@/app/components/workflow/types'import { cn } from '@langgenius/dify-ui/cn'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { RiCloseLine } from '@remixicon/react'import { cloneDeep } from 'es-toolkit/object'import { isEqual } from 'es-toolkit/predicate'@@ -24,7 +25,6 @@ import VariableTrigger from '@/app/components/workflow/panel/env-panel/variable-import { useStore, useWorkflowStore } from '@/app/components/workflow/store'import { BlockEnum } from '@/app/components/workflow/types'import { toast } from '@/app/notifications'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { Resolution } from '@/types/app'import {fetchModelParameterRulesForModel,diff --git a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.tsindex 638264278ba..b2fccfa44bf 100644--- a/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts+++ b/web/features/agent-v2/agent-detail/configure/use-agent-configure-sync.ts@@ -5,6 +5,7 @@ import type {AgentSoulConfig,} from '@dify/contracts/api/console/agent/types.gen'import type { AgentSoulConfigFormState } from '@/features/agent-v2/agent-composer/form-state'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { mutationOptions, useMutation, useQueryClient } from '@tanstack/react-query'import { debounce } from 'es-toolkit/compat'import isEqual from 'fast-deep-equal'@@ -26,7 +27,6 @@ import {isAgentComposerDirtyAtom,} from '@/features/agent-v2/agent-composer/store'import { agentComposerToolPresentationIdentitiesAtom } from '@/features/agent-v2/agent-composer/store-modules/tools'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { consoleQuery } from '@/service/console'import {getAgentToolPublishIssue,diff --git a/web/features/home/banner/banner.tsx b/web/features/home/banner/banner.tsxindex 32c1878eab4..aa2fc28873b 100644--- a/web/features/home/banner/banner.tsx+++ b/web/features/home/banner/banner.tsx@@ -5,6 +5,7 @@ import type {PointerEvent as ReactPointerEvent,} from 'react'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useSuspenseQuery } from '@tanstack/react-query'import { useEffect, useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -12,7 +13,6 @@ import { useLocale } from '#i18n'import { trackEvent } from '@/app/components/base/amplitude'import { Carousel, useCarousel } from '@/app/components/base/carousel'import { userProfileQueryOptions } from '@/features/account-profile/client'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { BannerItem } from './banner-item'import { IndicatorButton } from './indicator-button'diff --git a/web/features/new-rag/add-source-page.tsx b/web/features/new-rag/add-source-page.tsxindex be637d6bbdd..b68ec6af27a 100644--- a/web/features/new-rag/add-source-page.tsx+++ b/web/features/new-rag/add-source-page.tsx@@ -11,11 +11,11 @@ import type {} from './routes'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useInfiniteQuery, useQuery, useQueryClient } from '@tanstack/react-query'import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { useRouter } from '@/next/navigation'import { consoleClient, consoleQuery } from '@/service/console'import { registerPageLeaveGuard } from '@/utils/page-leave-guard'diff --git a/web/features/new-rag/auxiliary-task-read-guard.ts b/web/features/new-rag/auxiliary-task-read-guard.tsindex c3bdf74e915..23e6ae50e3c 100644--- a/web/features/new-rag/auxiliary-task-read-guard.ts+++ b/web/features/new-rag/auxiliary-task-read-guard.ts@@ -1,5 +1,5 @@+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useCallback, useEffect, useRef, useState } from 'react'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { taskVersionIsAfter } from './document-model'type RefetchDocuments = (options: { cancelRefetch: true }) => Promise<{ error: unknown }>diff --git a/web/features/new-rag/document-chunk-tree.tsx b/web/features/new-rag/document-chunk-tree.tsxindex 3e8404d8efa..cf936d5b2ba 100644--- a/web/features/new-rag/document-chunk-tree.tsx+++ b/web/features/new-rag/document-chunk-tree.tsx@@ -4,10 +4,10 @@ import type { DocumentChunkTree } from './document-detail-model'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'import { SpinnerIcon } from '@langgenius/dify-ui/spinner'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { defaultRangeExtractor, useVirtualizer } from '@tanstack/react-virtual'import { useEffect, useId, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { chunkTreeLabel, visibleDocumentChunkNodes } from './document-detail-model'const VIRTUALIZATION_THRESHOLD = 80diff --git a/web/features/new-rag/documents-page.tsx b/web/features/new-rag/documents-page.tsxindex 5326e90caa6..6ce1248b031 100644--- a/web/features/new-rag/documents-page.tsx+++ b/web/features/new-rag/documents-page.tsx@@ -7,6 +7,7 @@ import type {} from './services/processing-task-events'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { useAtomValue, useSetAtom } from 'jotai'import { debounce, parseAsString, parseAsStringLiteral, useQueryState } from 'nuqs'@@ -22,7 +23,6 @@ import {workspacePermissionKeysFetchingAtom,workspacePermissionKeysLoadingAtom,} from '@/context/permission-state'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { consoleClient, consoleQuery } from '@/service/console'import { DatasetACLPermission, hasPermission } from '@/utils/permission'import { useAuxiliaryTaskReadGuard } from './auxiliary-task-read-guard'diff --git a/web/features/new-rag/processing-tasks-drawer.tsx b/web/features/new-rag/processing-tasks-drawer.tsxindex ba41cc467b8..2b16c1835e2 100644--- a/web/features/new-rag/processing-tasks-drawer.tsx+++ b/web/features/new-rag/processing-tasks-drawer.tsx@@ -18,12 +18,12 @@ import {DrawerViewport,} from '@langgenius/dify-ui/drawer'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useMutation } from '@tanstack/react-query'import { useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { useFormatTimeFromNow } from '@/hooks/use-format-time-from-now'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { consoleQuery } from '@/service/console'import { taskCanRetry, taskIsActive, taskVersionIsAfter } from './document-model'diff --git a/web/features/new-rag/website-crawl-preview.tsx b/web/features/new-rag/website-crawl-preview.tsxindex d00b3d4309f..d0385af1e76 100644--- a/web/features/new-rag/website-crawl-preview.tsx+++ b/web/features/new-rag/website-crawl-preview.tsx@@ -18,9 +18,9 @@ import {} from '@langgenius/dify-ui/alert-dialog'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { useRouter } from '@/next/navigation'import { consoleClient } from '@/service/console'import { registerPageLeaveGuard } from '@/utils/page-leave-guard'diff --git a/web/features/skills/detail/builder-panel.tsx b/web/features/skills/detail/builder-panel.tsxindex 95c4fde817f..f528dc7e3d2 100644--- a/web/features/skills/detail/builder-panel.tsx+++ b/web/features/skills/detail/builder-panel.tsx@@ -8,6 +8,7 @@ import type { BuilderChatMessage, SkillBuilderAttachment, SkillBuilderModel } frimport type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'+import { useRefWithInit } from '@langgenius/dify-ui/use-ref-with-init'import { useQuery, useQueryClient } from '@tanstack/react-query'import { useEffect, useId, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -20,7 +21,6 @@ import { useDefaultModel } from '@/app/components/header/account-setting/model-pimport ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'import { ModelSelector } from '@/app/components/header/account-setting/model-provider-page/model-selector'import { toast } from '@/app/notifications'-import { useRefWithInit } from '@/hooks/use-ref-with-init'import { consoleQuery } from '@/service/console'import { sendSkillAssistMessage, uploadSkillFile } from '../client'import { SkillBuilderGridTexture } from './builder-grid-texture'diff --git a/web/hooks/use-ref-with-init/LICENSE b/web/hooks/use-ref-with-init/LICENSEdeleted file mode 100644index 510c55e0f0e..00000000000--- a/web/hooks/use-ref-with-init/LICENSE+++ /dev/null@@ -1,21 +0,0 @@-MIT License--Copyright (c) 2019 Material-UI SAS--Permission is hereby granted, free of charge, to any person obtaining a copy-of this software and associated documentation files (the "Software"), to deal-in the Software without restriction, including without limitation the rights-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell-copies of the Software, and to permit persons to whom the Software is-furnished to do so, subject to the following conditions:--The above copyright notice and this permission notice shall be included in all-copies or substantial portions of the Software.--THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE-SOFTWARE.diff --git a/web/hooks/use-ref-with-init/index.spec.ts b/web/hooks/use-ref-with-init/index.spec.tsdeleted file mode 100644index 11a67e1005c..00000000000--- a/web/hooks/use-ref-with-init/index.spec.ts+++ /dev/null@@ -1,66 +0,0 @@-import { renderHook } from '@testing-library/react'-import { StrictMode } from 'react'-import { describe, expect, expectTypeOf, it, vi } from 'vite-plus/test'-import { useRefWithInit } from './index'--describe('useRefWithInit', () => {- it('preserves the ref and initial value when the initializer and argument change', () => {- const init = vi.fn((value: number) => ({ value }))- const replacementInit = vi.fn((value: number) => ({ value }))- const { result, rerender } = renderHook(- ({ initializer, value }) => useRefWithInit(initializer, value),- { initialProps: { initializer: init, value: 1 } },- )- const ref = result.current- const initialValue = ref.current-- rerender({ initializer: replacementInit, value: 2 })-- expect(result.current).toBe(ref)- expect(result.current.current).toBe(initialValue)- expect(result.current.current).toEqual({ value: 1 })- expect(init).toHaveBeenCalledExactlyOnceWith(1)- expect(replacementInit).not.toHaveBeenCalled()- expectTypeOf(result.current.current).toEqualTypeOf<{ value: number }>()- })-- it.each([null, undefined])('accepts %s as an initialized value', (value) => {- const init = vi.fn(() => value)- const { result, rerender } = renderHook(() => useRefWithInit(init))-- rerender()-- expect(result.current.current).toBe(value)- expect(init).toHaveBeenCalledTimes(1)- })-- it('preserves explicit ref updates, including clearing the value', () => {- const init = vi.fn((): number | null => 1)- const { result, rerender } = renderHook(() => useRefWithInit(init))- expectTypeOf(result.current.current).toEqualTypeOf<number | null>()-- result.current.current = 2- rerender()- expect(result.current.current).toBe(2)-- result.current.current = null- rerender()- expect(result.current.current).toBeNull()- expect(init).toHaveBeenCalledTimes(1)- })-- it('keeps committed ref identity across rerenders in Strict Mode', () => {- const { result, rerender } = renderHook(() => useRefWithInit(() => new Map<string, number>()), {- wrapper: StrictMode,- })- const ref = result.current- const map = ref.current- map.set('count', 1)-- rerender()-- expect(result.current).toBe(ref)- expect(result.current.current).toBe(map)- expect(result.current.current.get('count')).toBe(1)- })-})diff --git a/web/hooks/use-ref-with-init/index.ts b/web/hooks/use-ref-with-init/index.tsdeleted file mode 100644index 38331d72aed..00000000000--- a/web/hooks/use-ref-with-init/index.ts+++ /dev/null@@ -1,26 +0,0 @@-/*!- * Adapted from Base UI (MIT). Copyright (c) 2019 Material-UI SAS.- * https://github.com/mui/base-ui/blob/50f90e8f8ff4cc77b624b6ad8550346e00b15445/packages/utils/src/useRefWithInit.ts- * See ./LICENSE for the full license.- */--'use client'-import * as React from 'react'--const UNINITIALIZED = {}--/**- * Lazily initializes a ref. Later changes to initArg do not reinitialize it.- * The initializer runs during render and must be safe to retry or discard.- */-export function useRefWithInit<T>(init: () => T): React.RefObject<T>-export function useRefWithInit<T, U>(init: (arg: U) => T, initArg: U): React.RefObject<T>-export function useRefWithInit(init: (arg?: unknown) => unknown, initArg?: unknown) {- const ref = React.useRef<unknown>(UNINITIALIZED)-- if (ref.current === UNINITIALIZED) {- ref.current = init(initArg)- }-- return ref-}