Skip to content

armgit / dify

Public Imported from GitHub
0

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.

fix(web): refresh model provider plugins after updates (#40002)

Jingyi15a5317bd3e2
diff --git a/web/__mocks__/provider-context.ts b/web/__mocks__/provider-context.ts
index a8847ecb8a1..6265352feee 100644
--- a/web/__mocks__/provider-context.ts
+++ b/web/__mocks__/provider-context.ts
@@ -7,7 +7,7 @@ import { defaultPlan } from '@/app/components/billing/config'
// Avoid being mocked in tests
export const baseProviderContextValue: ProviderContextState = {
modelProviders: [],
- refreshModelProviders: noop,
+ refreshModelProviders: async () => {},
isLoadingModelProviders: false,
textGenerationModelList: [],
isAPIKeySet: true,
@@ -45,7 +45,7 @@ export const createMockProviderContextValue = (
return {
...merged,
- refreshModelProviders: merged.refreshModelProviders ?? noop,
+ refreshModelProviders: merged.refreshModelProviders ?? (async () => {}),
onPlanInfoChanged: merged.onPlanInfoChanged ?? noop,
refreshLicenseLimit: merged.refreshLicenseLimit ?? noop,
}
diff --git a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
index 2f2537bd06e..fe87c4071cd 100644
--- a/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
+++ b/web/app/components/app/overview/apikey-info-panel/__tests__/test-utils.tsx
@@ -39,7 +39,7 @@ const mockUseProviderContext = actualUseProviderContext as MockedFunction<
// Default mock data
const defaultProviderContext = {
modelProviders: [],
- refreshModelProviders: noop,
+ refreshModelProviders: async () => {},
isLoadingModelProviders: false,
textGenerationModelList: [],
isAPIKeySet: false,
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/agent-model-trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/agent-model-trigger.spec.tsx
index 11acfc8514c..0c3c773451f 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/agent-model-trigger.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/agent-model-trigger.spec.tsx
@@ -2,6 +2,7 @@ import type { MouseEvent } from 'react'
import type { ModelProvider } from '../../declarations'
import { fireEvent, render, screen } from '@testing-library/react'
import { vi } from 'vitest'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import {
CurrentSystemQuotaTypeEnum,
CustomConfigurationStatusEnum,
@@ -123,7 +124,7 @@ describe('AgentModelTrigger', () => {
expect(updateModelList).toHaveBeenCalledWith(ModelTypeEnum.textGeneration)
expect(updateModelList).toHaveBeenCalledWith(ModelTypeEnum.tts)
expect(updateModelProviders).toHaveBeenCalledTimes(1)
- expect(invalidateInstalledPluginList).toHaveBeenCalledTimes(1)
+ expect(invalidateInstalledPluginList).toHaveBeenCalledWith(PluginCategoryEnum.model)
})
it('should show configuration action when provider requires setup', () => {
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/status-indicators.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/status-indicators.spec.tsx
index e044b2972ff..30e3e07da7f 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/status-indicators.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/status-indicators.spec.tsx
@@ -1,13 +1,20 @@
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { vi } from 'vitest'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { withSelectorKey } from '@/test/i18n-mock'
import StatusIndicators from '../status-indicators'
let installedPlugins = [{ name: 'demo-plugin', plugin_unique_identifier: '[email protected]' }]
+const { mockUseInstalledPluginList } = vi.hoisted(() => ({
+ mockUseInstalledPluginList: vi.fn(),
+}))
vi.mock('@/service/use-plugins', () => ({
- useInstalledPluginList: () => ({ data: { plugins: installedPlugins } }),
+ useInstalledPluginList: (...args: unknown[]) => {
+ mockUseInstalledPluginList(...args)
+ return { data: { plugins: installedPlugins } }
+ },
}))
vi.mock('@/app/components/workflow/nodes/_base/components/switch-plugin-version', () => ({
@@ -24,6 +31,23 @@ describe('StatusIndicators', () => {
installedPlugins = [{ name: 'demo-plugin', plugin_unique_identifier: '[email protected]' }]
})
+ it('reads the model-specific installed plugin list', () => {
+ render(
+ <StatusIndicators
+ needsConfiguration={false}
+ modelProvider={true}
+ inModelList={false}
+ disabled={true}
+ pluginInfo={{ name: 'demo-plugin' }}
+ t={t}
+ />,
+ )
+
+ expect(mockUseInstalledPluginList).toHaveBeenCalledWith(false, 100, {
+ category: PluginCategoryEnum.model,
+ })
+ })
+
const getPopoverTrigger = (name: string) => {
const trigger = screen.getByRole('button', { name })
expect(trigger).toBeInTheDocument()
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx
index e0d82c78efe..afae0d1e623 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx
@@ -5,6 +5,7 @@ import { cn } from '@langgenius/dify-ui/cn'
import { useMemo, useState } from 'react'
import { useTranslation } from 'react-i18next'
import Loading from '@/app/components/base/loading'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'
import { useProviderContext } from '@/context/provider-context'
import {
@@ -111,7 +112,7 @@ const AgentModelTrigger: FC<AgentModelTriggerProps> = ({
if (scope?.includes(type)) updateModelList(type)
})
updateModelProviders()
- invalidateInstalledPluginList()
+ invalidateInstalledPluginList(PluginCategoryEnum.model)
setInstalled(true)
}}
/>
diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/status-indicators.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/status-indicators.tsx
index cb5971b6f71..81c584064ee 100644
--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/status-indicators.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/status-indicators.tsx
@@ -2,6 +2,7 @@ import type { SelectorParam } from 'i18next'
import type { ReactNode } from 'react'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { RiErrorWarningFill } from '@remixicon/react'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { SwitchPluginVersion } from '@/app/components/workflow/nodes/_base/components/switch-plugin-version'
import Link from '@/next/link'
import { useInstalledPluginList } from '@/service/use-plugins'
@@ -53,7 +54,9 @@ const StatusIndicators = ({
pluginInfo,
t,
}: StatusIndicatorsProps) => {
- const { data: pluginList } = useInstalledPluginList()
+ const { data: pluginList } = useInstalledPluginList(false, 100, {
+ category: PluginCategoryEnum.model,
+ })
const renderTooltipContent = (
title: string,
description?: string,
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx
index 2fce814e4f7..f7a17b9611c 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx
@@ -1,7 +1,9 @@
import type { ReactElement } from 'react'
import type { ModelProvider } from '../../declarations'
+import type { PluginDetail } from '@/app/components/plugins/types'
import { QueryClient } from '@tanstack/react-query'
import { act, fireEvent, screen, waitFor } from '@testing-library/react'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { createQueryClientWrapper } from '@/test/console/query-client'
import { seedSystemFeatures } from '@/test/console/query-data'
import { render } from '@/test/console/render'
@@ -16,6 +18,12 @@ let mockWorkspacePermissionKeys: string[] = [
'credential.create',
'credential.manage',
]
+const { mockInvalidateInstalledPluginList, mockProviderCardActions, mockRefreshModelProviders } =
+ vi.hoisted(() => ({
+ mockInvalidateInstalledPluginList: vi.fn(),
+ mockProviderCardActions: vi.fn(),
+ mockRefreshModelProviders: vi.fn(),
+ }))
const mockFetchModelProviderModels = vi.fn()
const mockQueryOptions = vi.fn(
({ input, ...options }: { input: { params: { provider: string } }; enabled?: boolean }) => ({
@@ -70,6 +78,15 @@ vi.mock('@/context/permission-state', async () => {
}))
})
+vi.mock('@/context/provider-context', () => ({
+ useProviderContextSelector: (selector: (state: object) => unknown) =>
+ selector({ refreshModelProviders: mockRefreshModelProviders }),
+}))
+
+vi.mock('@/service/use-plugins', () => ({
+ useInvalidateInstalledPluginList: () => mockInvalidateInstalledPluginList,
+}))
+
// Mock internal components to simplify testing of the index file
vi.mock('../credential-panel', () => ({
default: () => <div data-testid="credential-panel" />,
@@ -102,6 +119,13 @@ vi.mock('../../model-badge', () => ({
default: ({ children }: { children: string }) => <div data-testid="model-badge">{children}</div>,
}))
+vi.mock('../provider-card-actions', () => ({
+ default: (props: { onUpdate?: () => Promise<void> }) => {
+ mockProviderCardActions(props)
+ return <div data-testid="provider-card-actions" />
+ },
+}))
+
vi.mock('@/app/components/header/account-setting/model-provider-page/model-auth', () => ({
AddCustomModel: () => <div data-testid="add-custom-model" />,
ManageCustomModelCredentials: () => <div data-testid="manage-custom-model" />,
@@ -188,6 +212,55 @@ describe('ProviderAddedCard', () => {
expect(screen.getByTestId('provider-icon')).toBeInTheDocument()
})
+ it('refreshes provider data and installed plugin details after an update', async () => {
+ let resolveProviderRefresh: (() => void) | undefined
+ let resolveInstalledPluginRefresh: (() => void) | undefined
+ mockRefreshModelProviders.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveProviderRefresh = resolve
+ }),
+ )
+ mockInvalidateInstalledPluginList.mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveInstalledPluginRefresh = resolve
+ }),
+ )
+
+ renderWithQueryClient(
+ <ProviderAddedCard
+ provider={mockProvider}
+ pluginDetail={
+ {
+ plugin_id: 'provider-plugin',
+ plugin_unique_identifier: '[email protected]',
+ declaration: {
+ author: 'langgenius',
+ description: { en_US: 'Provider plugin' },
+ },
+ } as PluginDetail
+ }
+ />,
+ )
+
+ const onUpdate = mockProviderCardActions.mock.calls[0]?.[0].onUpdate as () => Promise<void>
+ let isRefreshComplete = false
+ const refreshPromise = onUpdate().then(() => {
+ isRefreshComplete = true
+ })
+
+ expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith(PluginCategoryEnum.model)
+ expect(mockRefreshModelProviders).toHaveBeenCalledOnce()
+ expect(mockInvalidateInstalledPluginList).toHaveBeenCalledTimes(1)
+
+ resolveProviderRefresh?.()
+ await Promise.resolve()
+ expect(isRefreshComplete).toBe(false)
+
+ resolveInstalledPluginRefresh?.()
+ await refreshPromise
+ expect(isRefreshComplete).toBe(true)
+ })
+
it('should open, refresh and collapse model list', async () => {
mockFetchModelProviderModels.mockResolvedValue(modelProviderModelsResponse)
renderWithQueryClient(<ProviderAddedCard provider={mockProvider} />)
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx
index 3d17ea12902..95d9e4bcc24 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx
@@ -11,12 +11,14 @@ import {
AddCustomModel,
ManageCustomModelCredentials,
} from '@/app/components/header/account-setting/model-provider-page/model-auth'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { workspacePermissionKeysAtom } from '@/context/permission-state'
import { useProviderContextSelector } from '@/context/provider-context'
import { systemFeaturesQueryOptions } from '@/features/system-features/client'
import { useCredentialPermissions } from '@/hooks/use-credential-permissions'
import { renderI18nObject } from '@/i18n-config'
import { consoleQuery } from '@/service/client'
+import { useInvalidateInstalledPluginList } from '@/service/use-plugins'
import { hasPermission } from '@/utils/permission'
import { useModelProviderListExpanded, useSetModelProviderListExpanded } from '../atoms'
import { ConfigurationMethodEnum } from '../declarations'
@@ -51,6 +53,7 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({
})
const language = useLanguage()
const refreshModelProviders = useProviderContextSelector((state) => state.refreshModelProviders)
+ const invalidateInstalledPluginList = useInvalidateInstalledPluginList()
const currentProviderName = provider.provider
const expanded = useModelProviderListExpanded(currentProviderName)
const setExpanded = useSetModelProviderListExpanded(currentProviderName)
@@ -98,6 +101,13 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({
[currentProviderName, expanded, refetchModelList, setExpanded],
)
+ const refreshPluginData = useCallback(async () => {
+ await Promise.all([
+ refreshModelProviders(),
+ invalidateInstalledPluginList(PluginCategoryEnum.model),
+ ])
+ }, [invalidateInstalledPluginList, refreshModelProviders])
+
const handleOpenModelList = useCallback(() => {
if (loading) return
@@ -149,7 +159,7 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({
{providerLabel}
</div>
{pluginDetail && (
- <ProviderCardActions detail={pluginDetail} onUpdate={refreshModelProviders} />
+ <ProviderCardActions detail={pluginDetail} onUpdate={refreshPluginData} />
)}
</div>
<div className="mt-0.5 flex h-4 min-w-0 items-center gap-2 system-xs-regular text-text-tertiary">
@@ -244,7 +254,7 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({
<div className="mb-2 flex items-center gap-1">
<ProviderIcon provider={provider} />
{pluginDetail && (
- <ProviderCardActions detail={pluginDetail} onUpdate={refreshModelProviders} />
+ <ProviderCardActions detail={pluginDetail} onUpdate={refreshPluginData} />
)}
</div>
<div className="flex gap-0.5">
diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx
index e3ff3abaac1..60aea8819f1 100644
--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx
+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx
@@ -21,7 +21,7 @@ import { getMarketplaceUrl } from '@/utils/var'
type Props = Readonly<{
detail: PluginDetail
- onUpdate?: () => void
+ onUpdate?: () => void | Promise<void>
}>
const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {
diff --git a/web/app/components/integrations/tool-provider-list.tsx b/web/app/components/integrations/tool-provider-list.tsx
index 81369906549..9e6d7886835 100644
--- a/web/app/components/integrations/tool-provider-list.tsx
+++ b/web/app/components/integrations/tool-provider-list.tsx
@@ -19,6 +19,7 @@ import { useTags } from '@/app/components/plugins/hooks'
import Empty from '@/app/components/plugins/marketplace/empty'
import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'
import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import {
toolsContentInsetClassNames,
toolsUnifiedContentFrameClassName,
@@ -272,7 +273,9 @@ const ProviderList = ({ category, contentInset = 'default', layout }: ProviderLi
)}
<PluginDetailPanel
detail={currentPluginDetail}
- onUpdate={() => invalidateInstalledPluginList()}
+ onUpdate={() => {
+ invalidateInstalledPluginList(PluginCategoryEnum.tool)
+ }}
onHide={() => setCurrentProviderId(undefined)}
canDeletePlugin={canDeletePlugin}
canUpdatePlugin={canUpdatePlugin}
diff --git a/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts b/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts
index 7e61ad44379..3d4a1f15dd7 100644
--- a/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts
+++ b/web/app/components/plugins/install-plugin/hooks/__tests__/use-refresh-plugin-list.spec.ts
@@ -96,6 +96,7 @@ describe('useRefreshPluginList', () => {
result.current.refreshPluginList({ category: PluginCategoryEnum.tool } as never)
+ expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith(PluginCategoryEnum.tool)
expect(mockInvalidateAllToolProviders).toHaveBeenCalledTimes(1)
expect(mockInvalidateAllBuiltInTools).toHaveBeenCalledTimes(1)
expect(mockInvalidateRAGRecommendedPlugins).toHaveBeenCalledWith('tool')
@@ -106,6 +107,7 @@ describe('useRefreshPluginList', () => {
result.current.refreshPluginList({ category: PluginCategoryEnum.model } as never)
+ expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith(PluginCategoryEnum.model)
expect(mockRefreshModelProviders).toHaveBeenCalledTimes(1)
expect(mockRefetchLLMModelList).toHaveBeenCalledTimes(1)
expect(mockRefetchEmbeddingModelList).toHaveBeenCalledTimes(1)
@@ -150,7 +152,7 @@ describe('useRefreshPluginList', () => {
result.current.refreshPluginList(undefined, true)
- expect(mockInvalidateInstalledPluginList).toHaveBeenCalledTimes(1)
+ expect(mockInvalidateInstalledPluginList).toHaveBeenCalledWith()
expect(mockInvalidateAllToolProviders).toHaveBeenCalledTimes(1)
expect(mockInvalidateAllBuiltInTools).toHaveBeenCalledTimes(1)
expect(mockInvalidateRAGRecommendedPlugins).toHaveBeenCalledWith('tool')
diff --git a/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx b/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx
index 049427b2c90..a8fa7d76cc4 100644
--- a/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx
+++ b/web/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list.tsx
@@ -21,7 +21,7 @@ import { useInvalidateAllTriggerPlugins } from '@/service/use-triggers'
import { PluginCategoryEnum } from '../../types'
type PluginCategoryPayload = {
- category: PluginCategoryEnum | string
+ category: PluginCategoryEnum
}
const SYSTEM_MODEL_TYPES = [
@@ -60,7 +60,8 @@ const useRefreshPluginList = () => {
refreshAllType?: boolean,
) => {
// installed list
- invalidateInstalledPluginList()
+ if (refreshAllType || !manifest) invalidateInstalledPluginList()
+ else invalidateInstalledPluginList(manifest.category)
invalidateCheckInstalled()
// tool page, tool select
diff --git a/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
index b13b8985d47..805644b18df 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/__tests__/index.spec.tsx
@@ -616,6 +616,42 @@ describe('InstallFromGitHub', () => {
})
})
+ it('waits for an async onSuccess callback before showing installation success', async () => {
+ let resolveSuccess: (() => void) | undefined
+ const onSuccess = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveSuccess = resolve
+ }),
+ )
+ render(
+ <InstallFromGitHub
+ onClose={vi.fn()}
+ onSuccess={onSuccess}
+ updatePayload={createUpdatePayload()}
+ />,
+ )
+
+ fireEvent.click(screen.getByTestId('trigger-upload-btn'))
+
+ await waitFor(() => {
+ expect(screen.getByTestId('loaded-step')).toBeInTheDocument()
+ })
+
+ fireEvent.click(screen.getByTestId('install-success-btn'))
+
+ await waitFor(() => {
+ expect(onSuccess).toHaveBeenCalledTimes(1)
+ })
+ expect(screen.queryByTestId('installed-step')).not.toBeInTheDocument()
+
+ resolveSuccess?.()
+
+ await waitFor(() => {
+ expect(screen.getByTestId('installed-step')).toBeInTheDocument()
+ })
+ })
+
it('should call refreshPluginList when installation completes without notRefresh flag', async () => {
render(<InstallFromGitHub {...defaultProps} updatePayload={createUpdatePayload()} />)
diff --git a/web/app/components/plugins/install-plugin/install-from-github/index.tsx b/web/app/components/plugins/install-plugin/install-from-github/index.tsx
index 8ff6f3a12b3..55cc15b96d9 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/index.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/index.tsx
@@ -32,7 +32,7 @@ type InstallFromGitHubProps = {
updatePayload?: UpdateFromGitHubPayload
installContextCategory?: PluginCategoryEnum
onClose: () => void
- onSuccess: () => void
+ onSuccess: () => void | Promise<void>
}
const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({
@@ -138,11 +138,11 @@ const InstallFromGitHub: React.FC<InstallFromGitHubProps> = ({
}, [])
const handleInstalled = useCallback(
- (notRefresh?: boolean) => {
- setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installed }))
+ async (notRefresh?: boolean) => {
if (!notRefresh) refreshPluginList(manifest)
+ await onSuccess()
+ setState((prevState) => ({ ...prevState, step: InstallStepFromGitHub.installed }))
setIsInstalling(false)
- onSuccess()
},
[manifest, onSuccess, refreshPluginList, setIsInstalling],
)
diff --git a/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/loaded.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/loaded.spec.tsx
index 4f58e55f9e6..118b807cfc0 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/loaded.spec.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/steps/__tests__/loaded.spec.tsx
@@ -482,6 +482,9 @@ describe('Loaded', () => {
await waitFor(() => {
expect(screen.getByText('plugin.installModal.installing')).toBeInTheDocument()
})
+ expect(
+ screen.getByRole('button', { name: /plugin.installModal.installing/i }),
+ ).toHaveAttribute('aria-disabled', 'true')
resolveInstall!({ all_installed: true, task_id: 'task-1' })
})
diff --git a/web/app/components/plugins/install-plugin/install-from-github/steps/loaded.tsx b/web/app/components/plugins/install-plugin/install-from-github/steps/loaded.tsx
index a7a61e65ae0..f640fe09c89 100644
--- a/web/app/components/plugins/install-plugin/install-from-github/steps/loaded.tsx
+++ b/web/app/components/plugins/install-plugin/install-from-github/steps/loaded.tsx
@@ -2,7 +2,6 @@
import type { Plugin, PluginDeclaration, UpdateFromGitHubPayload } from '../../../types'
import { Button } from '@langgenius/dify-ui/button'
-import { RiLoader2Line } from '@remixicon/react'
import * as React from 'react'
import { useEffect } from 'react'
import { useTranslation } from 'react-i18next'
@@ -24,7 +23,7 @@ type LoadedProps = {
selectedPackage: string
onBack: () => void
onStartToInstall?: () => void
- onInstalled: (notRefresh?: boolean) => void
+ onInstalled: (notRefresh?: boolean) => void | Promise<void>
onFailed: (message?: string) => void
}
@@ -112,7 +111,7 @@ const Loaded: React.FC<LoadedProps> = ({
}
}
if (isInstalled) {
- onInstalled()
+ await onInstalled()
return
}
@@ -124,7 +123,7 @@ const Loaded: React.FC<LoadedProps> = ({
onFailed(error)
return
}
- onInstalled(true)
+ await onInstalled(true)
} catch (e) {
if (typeof e === 'string') {
onFailed(e)
@@ -164,11 +163,11 @@ const Loaded: React.FC<LoadedProps> = ({
)}
<Button
variant="primary"
- className="flex min-w-18"
+ className="min-w-18"
onClick={handleInstall}
- disabled={isInstalling || isLoading}
+ disabled={isLoading}
+ loading={isInstalling}
>
- {isInstalling && <RiLoader2Line className="size-4 animate-spin-slow" />}
<span>
{t(($) => $[`${i18nPrefix}.${isInstalling ? 'installing' : 'install'}`], {
ns: 'plugin',
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts
index fb9b996db41..202a0756e29 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts
@@ -1,6 +1,6 @@
import type { PluginDetail } from '../../../../types'
import type { ModalStates, VersionTarget } from '../use-detail-header-state'
-import { act, renderHook } from '@testing-library/react'
+import { act, renderHook, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import * as amplitude from '@/app/components/base/amplitude'
import { PluginSource } from '../../../../types'
@@ -183,8 +183,15 @@ describe('usePluginOperations', () => {
expect(modalStates.showUpdateModal).toHaveBeenCalled()
})
- it('should call onUpdate and hide modal on successful marketplace update', () => {
+ it('waits for the updated plugin list before hiding the update modal', async () => {
const detail = createPluginDetail({ source: PluginSource.marketplace })
+ let resolveUpdate: (() => void) | undefined
+ mockOnUpdate = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveUpdate = resolve
+ }),
+ )
const { result } = renderHook(() =>
usePluginOperations({
detail,
@@ -196,12 +203,19 @@ describe('usePluginOperations', () => {
)
act(() => {
- result.current.handleUpdatedFromMarketplace()
+ void result.current.handleUpdatedFromMarketplace()
})
expect(mockInvalidateCheckInstalled).toHaveBeenCalled()
expect(mockOnUpdate).toHaveBeenCalled()
- expect(modalStates.hideUpdateModal).toHaveBeenCalled()
+ expect(mockRefreshPluginList).not.toHaveBeenCalled()
+ expect(modalStates.hideUpdateModal).not.toHaveBeenCalled()
+
+ resolveUpdate?.()
+
+ await waitFor(() => {
+ expect(modalStates.hideUpdateModal).toHaveBeenCalled()
+ })
})
})
@@ -273,11 +287,18 @@ describe('usePluginOperations', () => {
expect(mockSetShowUpdatePluginModal).toHaveBeenCalled()
})
- it('should invalidate checkInstalled when GitHub update save callback fires', async () => {
+ it('waits for the update callback when GitHub update save callback fires', async () => {
const detail = createPluginDetail({
source: PluginSource.github,
meta: { repo: 'owner/repo', version: 'v1.0.0', package: 'pkg' },
})
+ let resolveUpdate: (() => void) | undefined
+ mockOnUpdate = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveUpdate = resolve
+ }),
+ )
const { result } = renderHook(() =>
usePluginOperations({
detail,
@@ -293,10 +314,21 @@ describe('usePluginOperations', () => {
})
const firstCall = mockSetShowUpdatePluginModal.mock.calls.at(0)?.[0]
- firstCall?.onSaveCallback()
+ const updatePromise = Promise.resolve(firstCall?.onSaveCallback?.())
expect(mockInvalidateCheckInstalled).toHaveBeenCalled()
expect(mockOnUpdate).toHaveBeenCalled()
+
+ let didFinish = false
+ void updatePromise.then(() => {
+ didFinish = true
+ })
+ await Promise.resolve()
+ expect(didFinish).toBe(false)
+
+ resolveUpdate?.()
+ await updatePromise
+ expect(didFinish).toBe(true)
})
it('should not show modal when no releases found', async () => {
diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts
index e6315975fde..30005bdb255 100644
--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts
+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-plugin-operations.ts
@@ -23,12 +23,12 @@ type UsePluginOperationsParams = {
setIsDowngrade: (downgrade: boolean) => void
}
isFromMarketplace: boolean
- onUpdate?: (isDelete?: boolean) => void
+ onUpdate?: (isDelete?: boolean) => void | Promise<void>
}
type UsePluginOperationsReturn = {
handleUpdate: (isDowngrade?: boolean) => Promise<void>
- handleUpdatedFromMarketplace: () => void
+ handleUpdatedFromMarketplace: () => Promise<void>
handleDelete: () => Promise<void>
}
@@ -49,9 +49,9 @@ export const usePluginOperations = ({
const { id, meta, plugin_id } = detail
const { author, category, name } = detail.declaration || detail
const handlePluginUpdated = useCallback(
- (isDelete?: boolean) => {
+ async (isDelete?: boolean) => {
invalidateCheckInstalled()
- onUpdate?.(isDelete)
+ await onUpdate?.(isDelete)
},
[invalidateCheckInstalled, onUpdate],
)
@@ -81,9 +81,7 @@ export const usePluginOperations = ({
if (needUpdate) {
setShowUpdatePluginModal({
- onSaveCallback: () => {
- handlePluginUpdated()
- },
+ onSaveCallback: () => handlePluginUpdated(),
payload: {
type: PluginSource.github,
category,
@@ -114,8 +112,8 @@ export const usePluginOperations = ({
],
)
- const handleUpdatedFromMarketplace = useCallback(() => {
- handlePluginUpdated()
+ const handleUpdatedFromMarketplace = useCallback(async () => {
+ await handlePluginUpdated()
modalStates.hideUpdateModal()
}, [handlePluginUpdated, modalStates])
diff --git a/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx b/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx
index 980d97f70af..ba438525fae 100644
--- a/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx
+++ b/web/app/components/plugins/plugin-detail-panel/endpoint-list.tsx
@@ -49,7 +49,7 @@ const EndpointListContent = ({ declaration, detail }: EndpointListContentProps)
const { mutate: createEndpoint } = useCreateEndpoint({
onSuccess: async () => {
await invalidateEndpointList(detail.plugin_id)
- invalidateInstalledPluginList()
+ invalidateInstalledPluginList(detail.declaration.category)
hideEndpointModal()
},
onError: () => {
@@ -129,7 +129,7 @@ const EndpointListContent = ({ declaration, detail }: EndpointListContentProps)
data={item}
handleChange={() => {
invalidateEndpointList(detail.plugin_id)
- invalidateInstalledPluginList()
+ invalidateInstalledPluginList(detail.declaration.category)
}}
pluginDetail={detail}
/>
diff --git a/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts b/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts
index 90627db55fa..418cf633cd0 100644
--- a/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts
+++ b/web/app/components/plugins/plugin-detail-panel/tool-selector/hooks/use-tool-selector.ts
@@ -4,6 +4,7 @@ import type { ToolParameter } from '@/app/components/tools/types'
import type { ToolDefaultValue, ToolValue } from '@/app/components/workflow/block-selector/types'
import type { ResourceVarInputs } from '@/app/components/workflow/nodes/_base/types'
import { useCallback, useMemo, useState } from 'react'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { CollectionType } from '@/app/components/tools/types'
import {
generateFormValue,
@@ -245,7 +246,7 @@ export function useToolSelector({ value, onSelect, onSelectMultiple }: UseToolSe
console.error('Failed to invalidate built-in tools cache', error)
}
try {
- await invalidateInstalledPluginList()
+ await invalidateInstalledPluginList(PluginCategoryEnum.tool)
} catch (error) {
console.error('Failed to invalidate installed plugin list cache', error)
}
diff --git a/web/app/components/plugins/plugin-item/action.tsx b/web/app/components/plugins/plugin-item/action.tsx
index 68e0410ce86..49153d36d91 100644
--- a/web/app/components/plugins/plugin-item/action.tsx
+++ b/web/app/components/plugins/plugin-item/action.tsx
@@ -68,7 +68,7 @@ const Action: FC<Props> = ({
if (needUpdate) {
setShowUpdatePluginModal({
onSaveCallback: () => {
- invalidateInstalledPluginList()
+ invalidateInstalledPluginList(category)
},
payload: {
type: PluginSource.github,
@@ -96,7 +96,7 @@ const Action: FC<Props> = ({
const res = await uninstallPlugin(installationId)
if (res.success) {
hideDeleteConfirm()
- invalidateInstalledPluginList()
+ invalidateInstalledPluginList(category)
onDelete()
}
} catch (error) {
@@ -108,6 +108,7 @@ const Action: FC<Props> = ({
hideDeleteConfirm,
hideDeleting,
installationId,
+ category,
invalidateInstalledPluginList,
onDelete,
showDeleting,
diff --git a/web/app/components/plugins/plugin-page/plugins-panel.tsx b/web/app/components/plugins/plugin-page/plugins-panel.tsx
index b43aae56b5c..da4ddcfaae3 100644
--- a/web/app/components/plugins/plugin-page/plugins-panel.tsx
+++ b/web/app/components/plugins/plugin-page/plugins-panel.tsx
@@ -294,7 +294,9 @@ const PluginsPanel = ({
)}
<PluginDetailPanel
detail={currentPluginDetail}
- onUpdate={() => invalidateInstalledPluginList()}
+ onUpdate={() => {
+ invalidateInstalledPluginList(fixedCategory)
+ }}
onHide={handleHide}
canDeletePlugin={canDeletePlugin}
canUpdatePlugin={canUpdatePlugin}
diff --git a/web/app/components/plugins/types.ts b/web/app/components/plugins/types.ts
index 2d301c56b28..68c380f6c0a 100644
--- a/web/app/components/plugins/types.ts
+++ b/web/app/components/plugins/types.ts
@@ -310,7 +310,7 @@ export type UpdatePluginPayload = {
export type UpdatePluginModalType = UpdatePluginPayload & {
onCancel: () => void
- onSave: () => void
+ onSave: () => void | Promise<void>
}
export enum InstallStepFromGitHub {
diff --git a/web/app/components/plugins/update-plugin/from-github.tsx b/web/app/components/plugins/update-plugin/from-github.tsx
index 9806a80959d..e6f00cdfa8c 100644
--- a/web/app/components/plugins/update-plugin/from-github.tsx
+++ b/web/app/components/plugins/update-plugin/from-github.tsx
@@ -6,7 +6,7 @@ import InstallFromGitHub from '../install-plugin/install-from-github'
type Props = Readonly<{
payload: UpdateFromGitHubPayload
- onSave: () => void
+ onSave: () => void | Promise<void>
onCancel: () => void
}>
diff --git a/web/app/components/plugins/update-plugin/from-market-place.tsx b/web/app/components/plugins/update-plugin/from-market-place.tsx
index 698b8afc9b5..90835ac9d26 100644
--- a/web/app/components/plugins/update-plugin/from-market-place.tsx
+++ b/web/app/components/plugins/update-plugin/from-market-place.tsx
@@ -22,7 +22,7 @@ const i18nPrefix = 'upgrade'
type Props = Readonly<{
payload: UpdateFromMarketPlacePayload
pluginId?: string
- onSave: () => void
+ onSave: () => void | Promise<void>
onCancel: () => void
isShowDowngradeWarningModal?: boolean
}>
@@ -101,7 +101,7 @@ const UpdatePluginModal = ({
const { all_installed: isInstalled, task_id: taskId } = response
if (isInstalled) {
- onSave()
+ await onSave()
return
}
handleInstallTaskStart(response)
@@ -114,7 +114,7 @@ const UpdatePluginModal = ({
setUploadStep(UploadStep.notStarted)
return
}
- onSave()
+ await onSave()
} catch {
setUploadStep(UploadStep.notStarted)
}
diff --git a/web/context/modal-context-provider.tsx b/web/context/modal-context-provider.tsx
index 4413694c6bb..12fa72940b6 100644
--- a/web/context/modal-context-provider.tsx
+++ b/web/context/modal-context-provider.tsx
@@ -10,6 +10,7 @@ import type { ExternalDataTool } from '@/models/common'
import type { ModerationConfig, PromptVariable } from '@/models/debug'
import { useAtomValue } from 'jotai'
import { useCallback, useState } from 'react'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { useProviderContext } from '@/context/provider-context'
import { currentWorkspaceIdAtom } from '@/context/workspace-state'
import { usePricingModal } from '@/hooks/use-query-params'
@@ -288,8 +289,15 @@ export const ModalContextProvider = ({ children }: ModalContextProviderProps) =>
showUpdatePluginModal.onCancelCallback?.()
}}
onSave={() => {
- setShowUpdatePluginModal(null)
- showUpdatePluginModal.onSaveCallback?.()
+ if (showUpdatePluginModal.payload.category !== PluginCategoryEnum.model) {
+ setShowUpdatePluginModal(null)
+ showUpdatePluginModal.onSaveCallback?.()
+ return
+ }
+
+ return Promise.resolve(showUpdatePluginModal.onSaveCallback?.()).then(() => {
+ setShowUpdatePluginModal(null)
+ })
}}
/>
)}
diff --git a/web/context/modal-context.test.tsx b/web/context/modal-context.test.tsx
index a5cfa87d35e..5fedde87cac 100644
--- a/web/context/modal-context.test.tsx
+++ b/web/context/modal-context.test.tsx
@@ -3,6 +3,7 @@ import userEvent from '@testing-library/user-event'
import * as React from 'react'
import { defaultPlan } from '@/app/components/billing/config'
import { Plan } from '@/app/components/billing/type'
+import { PluginCategoryEnum, PluginSource } from '@/app/components/plugins/types'
import { useModalContextSelector } from '@/context/modal-context'
import { ModalContextProvider } from '@/context/modal-context-provider'
import { createConsoleQueryWrapper } from '@/test/console/query-data'
@@ -20,6 +21,14 @@ vi.mock('@/app/components/billing/pricing', () => ({
default: () => <div>billing.plansCommon.mostPopular</div>,
}))
+vi.mock('@/app/components/plugins/update-plugin', () => ({
+ default: ({ onSave }: { onSave: () => void | Promise<void> }) => (
+ <button data-testid="save-plugin-update" onClick={onSave}>
+ Save plugin update
+ </button>
+ ),
+}))
+
const mockUseProviderContext = vi.fn()
vi.mock('@/context/provider-context', () => ({
useProviderContext: () => mockUseProviderContext(),
@@ -67,6 +76,43 @@ const ModalBlockingState = () => {
return <output>{hasBlockingModalOpen ? 'blocked' : 'clear'}</output>
}
+const UpdatePluginTrigger = ({
+ onSave,
+ category = PluginCategoryEnum.model,
+}: {
+ onSave: () => void | Promise<void>
+ category?: PluginCategoryEnum
+}) => {
+ const setShowUpdatePluginModal = useModalContextSelector(
+ (state) => state.setShowUpdatePluginModal,
+ )
+
+ return (
+ <button
+ onClick={() =>
+ setShowUpdatePluginModal({
+ onSaveCallback: onSave,
+ payload: {
+ type: PluginSource.github,
+ category,
+ github: {
+ originalPackageInfo: {
+ repo: 'owner/repo',
+ version: '1.0.0',
+ package: 'plugin.difypkg',
+ releases: [],
+ },
+ },
+ },
+ })
+ }
+ >
+ Open plugin update
+ </button>
+ )
+}
+
const renderProvider = (children: React.ReactNode = <ModalBlockingState />) => {
const { wrapper: QueryWrapper } = createConsoleQueryWrapper({
systemFeatures: { deployment_edition: 'CLOUD' },
@@ -223,3 +269,57 @@ describe('ModalContextProvider trigger events limit modal', () => {
expect(screen.getByText('blocked')).toBeInTheDocument()
})
})
+
+describe('ModalContextProvider plugin update modal', () => {
+ beforeEach(() => {
+ mockConsoleStateReader.mockReset()
+ mockUseProviderContext.mockReset()
+ mockConsoleStateReader.mockReturnValue({
+ currentWorkspace: {
+ id: 'workspace-1',
+ },
+ })
+ mockUseProviderContext.mockReturnValue({
+ plan: createPlan(),
+ isFetchedPlan: false,
+ })
+ })
+
+ it('keeps a model plugin update open until its refresh callback finishes', async () => {
+ let resolveSave: (() => void) | undefined
+ const onSave = vi.fn(
+ () =>
+ new Promise<void>((resolve) => {
+ resolveSave = resolve
+ }),
+ )
+ const user = userEvent.setup()
+
+ renderProvider(<UpdatePluginTrigger onSave={onSave} />)
+
+ await user.click(screen.getByRole('button', { name: 'Open plugin update' }))
+ await user.click(screen.getByTestId('save-plugin-update'))
+
+ expect(onSave).toHaveBeenCalledTimes(1)
+ expect(screen.getByTestId('save-plugin-update')).toBeInTheDocument()
+
+ resolveSave?.()
+
+ await waitFor(() => {
+ expect(screen.queryByTestId('save-plugin-update')).not.toBeInTheDocument()
+ })
+ })
+
+ it('closes a non-model plugin update immediately after saving', async () => {
+ const onSave = vi.fn()
+ const user = userEvent.setup()
+
+ renderProvider(<UpdatePluginTrigger onSave={onSave} category={PluginCategoryEnum.tool} />)
+
+ await user.click(screen.getByRole('button', { name: 'Open plugin update' }))
+ await user.click(screen.getByTestId('save-plugin-update'))
+
+ expect(onSave).toHaveBeenCalledTimes(1)
+ expect(screen.queryByTestId('save-plugin-update')).not.toBeInTheDocument()
+ })
+})
diff --git a/web/context/modal-context.ts b/web/context/modal-context.ts
index a99dfad1987..df1e60243d4 100644
--- a/web/context/modal-context.ts
+++ b/web/context/modal-context.ts
@@ -21,7 +21,7 @@ import { createContext, useContext, useContextSelector } from 'use-context-selec
export type ModalState<T> = {
payload: T
onCancelCallback?: () => void
- onSaveCallback?: (newPayload?: T, formValues?: Record<string, unknown>) => void
+ onSaveCallback?: (newPayload?: T, formValues?: Record<string, unknown>) => void | Promise<void>
onRemoveCallback?: (newPayload?: T, formValues?: Record<string, unknown>) => void
onEditCallback?: (newPayload: T) => void
onValidateBeforeSaveCallback?: (newPayload: T) => boolean
diff --git a/web/context/provider-context-provider.tsx b/web/context/provider-context-provider.tsx
index c4dff304d57..3bf9c5bb57a 100644
--- a/web/context/provider-context-provider.tsx
+++ b/web/context/provider-context-provider.tsx
@@ -95,9 +95,8 @@ export const ProviderContextProvider = ({ children }: ProviderContextProviderPro
] = useState(false)
const [humanInputEmailDeliveryEnabled, setHumanInputEmailDeliveryEnabled] = useState(false)
- const refreshModelProviders = () => {
+ const refreshModelProviders = () =>
queryClient.invalidateQueries({ queryKey: ['common', 'model-providers'] })
- }
const fetchPlan = async () => {
try {
diff --git a/web/context/provider-context.ts b/web/context/provider-context.ts
index 4c6d22ee147..987aabba409 100644
--- a/web/context/provider-context.ts
+++ b/web/context/provider-context.ts
@@ -12,7 +12,7 @@ import { defaultPlan } from '@/app/components/billing/config'
export type ProviderContextState = {
modelProviders: ModelProvider[]
isLoadingModelProviders: boolean
- refreshModelProviders: () => void
+ refreshModelProviders: () => Promise<void>
textGenerationModelList: Model[]
isAPIKeySet: boolean
plan: {
@@ -50,7 +50,7 @@ export type ProviderContextState = {
export const baseProviderContextValue: ProviderContextState = {
modelProviders: [],
isLoadingModelProviders: false,
- refreshModelProviders: noop,
+ refreshModelProviders: async () => {},
textGenerationModelList: [],
isAPIKeySet: true,
plan: defaultPlan,
diff --git a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
index ad1a9b3cd2f..27f97479eda 100644
--- a/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
+++ b/web/features/agent-v2/agent-detail/configure/components/orchestrate/tools/index.tsx
@@ -16,6 +16,7 @@ import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/pop
import { useAtomValue, useSetAtom } from 'jotai'
import { memo, useCallback, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
+import { PluginCategoryEnum } from '@/app/components/plugins/types'
import { parseToolProviderType } from '@/app/components/tools/provider-type'
import { CollectionType } from '@/app/components/tools/types'
import { ToolPickerContent } from '@/app/components/workflow/block-selector/tool-picker'
@@ -517,7 +518,10 @@ export function AgentTools() {
[setProviderToolCredential],
)
const handlePluginInstalled = useCallback(() => {
- void Promise.allSettled([invalidateAllBuiltInTools(), invalidateInstalledPluginList()])
+ void Promise.allSettled([
+ invalidateAllBuiltInTools(),
+ invalidateInstalledPluginList(PluginCategoryEnum.tool),
+ ])
}, [invalidateAllBuiltInTools, invalidateInstalledPluginList])
const visibleTools = useMemo(
() => (ENABLE_AGENT_CLI_TOOLS ? tools : tools.filter((tool) => tool.kind !== 'cli')),
diff --git a/web/service/__tests__/use-plugins.spec.tsx b/web/service/__tests__/use-plugins.spec.tsx
index ccae20709c3..ac2713557f7 100644
--- a/web/service/__tests__/use-plugins.spec.tsx
+++ b/web/service/__tests__/use-plugins.spec.tsx
@@ -20,6 +20,7 @@ import {
normalizeInstalledPluginDetail,
useInstalledPluginList,
useInstallOrUpdate,
+ useInvalidateInstalledPluginList,
useMutationPluginAutoUpgradeSettings,
useMutationPluginPermissionSettings,
usePluginAutoUpgradeSettings,
@@ -58,10 +59,6 @@ vi.mock('@/context/permission-state', async () => {
}))
})
-vi.mock('../use-tools', () => ({
- useInvalidateAllBuiltInTools: () => vi.fn(),
-}))
-
const createQueryClient = () =>
new QueryClient({
defaultOptions: {
@@ -671,6 +668,61 @@ describe('useInstalledPluginList', () => {
})
})
+describe('useInvalidateInstalledPluginList', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ })
+
+ it('only invalidates the requested category list', async () => {
+ const queryClient = createQueryClient()
+ const allPluginsKey = ['plugins', 'installedPluginList']
+ const modelPluginsKey = [...allPluginsKey, PluginCategoryEnum.model]
+ const toolPluginsKey = [...allPluginsKey, PluginCategoryEnum.tool]
+ const builtInToolsKey = ['tools', 'builtIn']
+
+ queryClient.setQueryData(allPluginsKey, { plugins: [] })
+ queryClient.setQueryData(modelPluginsKey, { plugins: [] })
+ queryClient.setQueryData(toolPluginsKey, { plugins: [] })
+ queryClient.setQueryData(builtInToolsKey, [])
+
+ const { result } = renderHook(() => useInvalidateInstalledPluginList(), {
+ wrapper: createWrapper(queryClient),
+ })
+
+ await act(async () => {
+ await result.current(PluginCategoryEnum.model)
+ })
+
+ expect(queryClient.getQueryState(modelPluginsKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(allPluginsKey)?.isInvalidated).toBe(false)
+ expect(queryClient.getQueryState(toolPluginsKey)?.isInvalidated).toBe(false)
+ expect(queryClient.getQueryState(builtInToolsKey)?.isInvalidated).toBe(false)
+ })
+
+ it('invalidates built-in tools when invalidating the tool category list', async () => {
+ const queryClient = createQueryClient()
+ const modelPluginsKey = ['plugins', 'installedPluginList', PluginCategoryEnum.model]
+ const toolPluginsKey = ['plugins', 'installedPluginList', PluginCategoryEnum.tool]
+ const builtInToolsKey = ['tools', 'builtIn']
+
+ queryClient.setQueryData(modelPluginsKey, { plugins: [] })
+ queryClient.setQueryData(toolPluginsKey, { plugins: [] })
+ queryClient.setQueryData(builtInToolsKey, [])
+
+ const { result } = renderHook(() => useInvalidateInstalledPluginList(), {
+ wrapper: createWrapper(queryClient),
+ })
+
+ await act(async () => {
+ await result.current(PluginCategoryEnum.tool)
+ })
+
+ expect(queryClient.getQueryState(toolPluginsKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(builtInToolsKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueryState(modelPluginsKey)?.isInvalidated).toBe(false)
+ })
+})
+
describe('usePluginTaskList', () => {
beforeEach(() => {
vi.clearAllMocks()
diff --git a/web/service/use-plugins.ts b/web/service/use-plugins.ts
index 25fe6c6d4d9..d5a23babb8d 100644
--- a/web/service/use-plugins.ts
+++ b/web/service/use-plugins.ts
@@ -675,11 +675,23 @@ export const useInstalledPluginList = (
export const useInvalidateInstalledPluginList = () => {
const queryClient = useQueryClient()
const invalidateAllBuiltInTools = useInvalidateAllBuiltInTools()
- return () => {
- queryClient.invalidateQueries({
- queryKey: useInstalledPluginListKey,
- })
- invalidateAllBuiltInTools()
+ return (category?: PluginCategoryEnum) => {
+ if (category) {
+ const invalidateCategoryPluginList = queryClient.invalidateQueries({
+ queryKey: [...useInstalledPluginListKey, category],
+ exact: true,
+ })
+
+ if (category === PluginCategoryEnum.tool)
+ return Promise.all([invalidateCategoryPluginList, invalidateAllBuiltInTools()])
+
+ return invalidateCategoryPluginList
+ }
+
+ return Promise.all([
+ queryClient.invalidateQueries({ queryKey: useInstalledPluginListKey }),
+ invalidateAllBuiltInTools(),
+ ])
}
}
@@ -1286,7 +1298,7 @@ export const useFetchPluginsInMarketPlaceByInfo = (infos: MarketplacePluginInfoR
})
}
-export const usePluginTaskList = (category?: PluginCategoryEnum | string) => {
+export const usePluginTaskList = (category?: PluginCategoryEnum) => {
const initializedRef = useRef(false)
const queryClient = useQueryClient()
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)