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
fix(plugins): align provider overlays and background update feedback (#44284)
yyh47b6712a3789
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 5a1a7896ad2..61939d0ce07 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -3274,7 +3274,7 @@},"web/service/use-plugins.ts": {"@tanstack/query/prefer-query-options": {- "count": 11+ "count": 10},"dify/require-disable-directive-description": {"count": 1diff --git a/packages/contracts/marketplace.ts b/packages/contracts/marketplace.tsindex 881af8e72ec..2900b44bd30 100644--- a/packages/contracts/marketplace.ts+++ b/packages/contracts/marketplace.ts@@ -472,6 +472,30 @@ const templateSearchContract = base).output(type<TemplateSearchResponse>())+export type PluginVersionsResponse = {+ data: {+ versions: Array<{+ plugin_org: string+ plugin_name: string+ version: string+ file_name: string+ checksum: string+ created_at: string+ unique_identifier: string+ }>+ }+}++const pluginVersionsContract = base+ .route({ path: '/plugins/{organization}/{pluginName}/versions', method: 'GET' })+ .input(+ type<{+ params: { organization: string; pluginName: string }+ query: { page: number; page_size: number }+ }>(),+ )+ .output(type<PluginVersionsResponse>())+const downloadPluginContract = base.route({path: '/plugins/{organization}/{pluginName}/{version}/download',@@ -568,6 +592,7 @@ export const marketplaceRouterContract = {templateDetail: templateDetailContract,templateSearch: templateSearchContract,downloadPlugin: downloadPluginContract,+ pluginVersions: pluginVersionsContract,creatorDetail: creatorDetailContract,organizationDetail: organizationDetailContract,publisherPlugins: publisherPluginsContract,diff --git a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsxindex ab03f9de5fd..dc682a87fa6 100644--- a/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/__tests__/index.spec.tsx@@ -53,6 +53,7 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.uninstall.post': api.uninstall,'auth.plugin.datasource.list.get': api.sources,'workspaces.current.plugin.readme.get': api.readme,'workspaces.current.plugin.byCategory.list.get': api.installed,@@ -60,7 +61,6 @@ vi.mock('@/service/console', async (importOriginal) => {'workspaces.current.plugin.list.installations.ids.post': async () => ({ plugins: [] }),}),consoleClient: withConsoleClientResponses(actual.consoleClient, {- 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.plugin.permission.fetch.get': async () => ({install_permission: 'everyone',debug_permission: 'everyone',diff --git a/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx b/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsxindex 8abe697121f..dd6d6b6e870 100644--- a/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx+++ b/web/app/components/header/account-setting/data-source-page-new/plugin-actions.tsx@@ -1,8 +1,18 @@'use client'+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'import type { PluginDetail } from '@/app/components/plugins/types'import { Button } from '@langgenius/dify-ui/button'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuGroupLabel,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { skipToken, useQuery } from '@tanstack/react-query'import { memo, useId } from 'react'import { useTranslation } from 'react-i18next'import { useLocale } from '#i18n'@@ -16,9 +26,11 @@ import { OperationDropdown } from '@/app/components/plugins/plugin-detail-panel/import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'import { useReadmePanelStore } from '@/app/components/plugins/readme-panel/store'import { PluginSource } from '@/app/components/plugins/types'-import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'import { useRenderI18nObject } from '@/hooks/use-i18n'import useTheme from '@/hooks/use-theme'+import useTimestamp from '@/hooks/use-timestamp'+import { marketplaceQuery } from '@/service/marketplace'+import { isEarlierThanVersion } from '@/utils/semver'import { getMarketplaceUrl } from '@/utils/var'type Props = {@@ -26,8 +38,6 @@ type Props = {onUpdate?: (isDelete?: boolean) => void}-const usePluginDetailHeader = useDetailHeaderState-const getDetailUrl = (detail: PluginDetail, locale: string, theme: string) => {const { source, meta } = detailconst { author, name } = detail.declaration || detail@@ -41,46 +51,66 @@ const getDetailUrl = (detail: PluginDetail, locale: string, theme: string) => {}const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {- const { t } = useTranslation(['common', 'plugin'])+ const { t } = useTranslation(['common', 'plugin', 'appLog'])+ const versionMenuLabelId = useId()+ const { formatDate } = useTimestamp()+ const dateFormat = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]!const { theme } = useTheme()const locale = useLocale()const renderI18nObject = useRenderI18nObject()const readmeTriggerId = useId()const openReadmePanel = useReadmePanelStore((s) => s.openReadmePanel)const { canDeletePlugin, canUpdatePlugin } = usePluginSettingsAccess()- const detailHeaderState = usePluginDetailHeader(detail)+ const detailHeaderState = useDetailHeaderState(detail)const {modalStates,versionPicker,hasNewVersion,isAutoUpgradeEnabled,+ autoUpgradeSettings,isFromGitHub,isFromMarketplace,} = detailHeaderState- const { handleUpdate, handleUpdatedFromMarketplace, handleDelete } = usePluginOperations({- detail,- modalStates,- versionPicker,- isFromMarketplace,- canDeletePlugin,- canUpdatePlugin,- onUpdate,- })+ const { handleUpdate, handleUpdatedFromMarketplace, handleDelete, deleting } =+ usePluginOperations({+ detail,+ modalStates,+ canDeletePlugin,+ canUpdatePlugin,+ onUpdate,+ })const displayVersion = isFromGitHub ? (detail.meta?.version ?? detail.version) : detail.versionconst pluginLabel = renderI18nObject(detail.declaration.label) || detail.name- const handleVersionSelect = (state: {- version: string- unique_identifier: string- isDowngrade?: boolean- }) => {- versionPicker.setTargetVersion(state)- handleUpdate(state.isDowngrade)+ const [organization, pluginName] = detail.plugin_id.split('/')+ const versionsQuery = useQuery(+ marketplaceQuery.pluginVersions.queryOptions({+ input:+ organization && pluginName+ ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }+ : skipToken,+ enabled: versionPicker.isShow && canUpdatePlugin && isFromMarketplace,+ retry: false,+ }),+ )+ const loadingVersions =+ versionPicker.isShow && (versionsQuery.isPending || autoUpgradeSettings.isPending)++ const handleVersionSelect = (item: PluginVersionsResponse['data']['versions'][number]) => {+ const isDowngrade = isEarlierThanVersion(item.version, detail.version)+ versionPicker.setTargetVersion({+ ...item,+ plugin: detail,+ warnAboutAutoUpdate: isDowngrade && isAutoUpgradeEnabled,+ })+ handleUpdate()}const handleTriggerLatestUpdate = () => {if (isFromMarketplace) {+ if (!detail.latest_version || !detail.latest_unique_identifier) returnversionPicker.setTargetVersion({+ plugin: detail,version: detail.latest_version,unique_identifier: detail.latest_unique_identifier,})@@ -96,35 +126,77 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {return (<div className="flex shrink-0 items-center gap-1">- {!!displayVersion && (- <PluginVersionPicker- disabled={!canUpdatePlugin || !isFromMarketplace}- isShow={versionPicker.isShow}- onShowChange={versionPicker.setIsShow}- pluginID={detail.plugin_id}- currentVersion={detail.version}- triggerAccessibleName={`${t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })} ${pluginLabel} ${displayVersion}`}- onSelect={handleVersionSelect}- trigger={() => (- <Badge- className="h-5 px-1.5"- text={- <>- <div>{displayVersion}</div>- {canUpdatePlugin && isFromMarketplace && (- <span- aria-hidden- className="ml-1 i-ri-arrow-left-right-line h-3 w-3 shrink-0 text-text-tertiary"- />+ <DropdownMenu+ open={+ !!displayVersion &&+ versionPicker.isShow &&+ canUpdatePlugin &&+ isFromMarketplace &&+ !loadingVersions+ }+ onOpenChange={versionPicker.setIsShow}+ >+ {!!displayVersion && (+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="small"+ disabled={!canUpdatePlugin || !isFromMarketplace}+ loading={loadingVersions}+ aria-label={`${t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })} ${pluginLabel} ${displayVersion}`}+ className="relative h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.5 system-xs-medium text-text-tertiary"+ >+ {hasNewVersion && (+ <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-xs border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm" />+ )}+ <span>{displayVersion}</span>+ {canUpdatePlugin && isFromMarketplace && !loadingVersions && (+ <span aria-hidden className="i-ri-arrow-left-right-line size-3" />+ )}+ </Button>+ }+ />+ )}+ <DropdownMenuContent+ className="max-h-[min(16rem,var(--available-height))]"+ placement="bottom-start"+ aria-labelledby={versionMenuLabelId}+ >+ <DropdownMenuGroup>+ <DropdownMenuGroupLabel id={versionMenuLabelId}>+ {t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}+ </DropdownMenuGroupLabel>+ {versionsQuery.data && autoUpgradeSettings.data ? (+ versionsQuery.data.data.versions.map((item) => (+ <DropdownMenuItem+ key={item.unique_identifier}+ disabled={detail.version === item.version}+ onClick={() => handleVersionSelect(item)}+ >+ <span>{item.version}</span>+ {detail.version === item.version && (+ <Badge className="shrink-0" variant="dimm" text="CURRENT" />)}- </>- }- hasRedCornerMark={hasNewVersion}- uppercase={false}- />- )}- />- )}+ <span className="ms-auto text-text-tertiary">+ {formatDate(item.created_at, dateFormat)}+ </span>+ </DropdownMenuItem>+ ))+ ) : (+ <DropdownMenuItem+ closeOnClick={false}+ onClick={() => {+ if (versionsQuery.isError) void versionsQuery.refetch()+ if (autoUpgradeSettings.isError) void autoUpgradeSettings.refetch()+ }}+ >+ {t(($) => $['operation.retry'], { ns: 'common' })}+ </DropdownMenuItem>+ )}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>{canUpdatePlugin && (hasNewVersion || isFromGitHub) && (<Tooltip><TooltipTrigger@@ -165,10 +237,9 @@ const DataSourcePluginActions = ({ detail, onUpdate }: Props) => {detail={detail}modalStates={modalStates}targetVersion={versionPicker.targetVersion}- isDowngrade={versionPicker.isDowngrade}- isAutoUpgradeEnabled={isAutoUpgradeEnabled}onUpdatedFromMarketplace={handleUpdatedFromMarketplace}onDelete={handleDelete}+ deleting={deleting}/></div>)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.tsxindex 3afd1dda016..ba56841210e 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@@ -33,16 +33,26 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.modelProviders.byProvider.models.get': api.models,'workspaces.current.modelProviders.get': api.providers,}),consoleClient: withConsoleClientResponses(actual.consoleClient, {'workspaces.current.modelProviders.byProvider.models.disable.patch': api.disable,- 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.plugin.permission.fetch.get': async () => ({install_permission: 'everyone',debug_permission: 'everyone',}),+ 'workspaces.current.plugin.autoUpgrade.fetch.get': async () => ({+ category: 'model',+ auto_upgrade: {+ strategy_setting: 'disabled',+ upgrade_mode: 'all',+ upgrade_time_of_day: 0,+ include_plugins: [],+ exclude_plugins: [],+ },+ }),}),}})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsxindex 06fdd43f1ea..9bca80d5175 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/provider-card-actions.spec.tsx@@ -1,6 +1,6 @@+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'import type { ComponentProps, ReactElement } from 'react'import type { ModelProviderPluginSummary } from '../../index'-import type { VersionListResponse } from '@/app/components/plugins/types'import type { consoleClient } from '@/service/console'import { zPostWorkspacesCurrentPluginListInstallationsIdsResponse } from '@dify/contracts/api/console/workspaces/zod.gen'import { act, screen, waitFor, within } from '@testing-library/react'@@ -23,8 +23,9 @@ const api = vi.hoisted(() => ({detail: vi.fn<typeof consoleClient.workspaces.current.plugin.list.installations.ids.post>(),uninstall: vi.fn<typeof consoleClient.workspaces.current.plugin.uninstall.post>(),upgrade: vi.fn<typeof consoleClient.workspaces.current.plugin.upgrade.marketplace.post>(),- versions: vi.fn<() => Promise<{ data: VersionListResponse }>>(),+ versions: vi.fn<() => Promise<PluginVersionsResponse>>(),releases: vi.fn<typeof fetch>(),+ autoUpgrade: vi.fn<typeof consoleClient.workspaces.current.plugin.autoUpgrade.fetch.get>(),}))vi.mock('@/service/console', async (importOriginal) => {const actual = await importOriginal<typeof import('@/service/console')>()@@ -33,7 +34,9 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.upgrade.marketplace.post': api.upgrade,'workspaces.current.plugin.list.installations.ids.post': api.detail,+ 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.models.modelTypes.byModelType.get': async () => ({ data: [] }),'workspaces.current.modelProviders.summary.get': async () => ({ data: [], plugins: {} }),}),@@ -45,23 +48,24 @@ vi.mock('@/service/console', async (importOriginal) => {install_permission: 'everyone',debug_permission: 'everyone',}),- 'workspaces.current.plugin.autoUpgrade.fetch.get': async () => ({- category: 'model',- auto_upgrade: {- strategy_setting: 'disabled',- upgrade_mode: 'all',- upgrade_time_of_day: 0,- include_plugins: [],- exclude_plugins: [],- },- }),+ 'workspaces.current.plugin.autoUpgrade.fetch.get': api.autoUpgrade,}),}})-vi.mock('@/service/base', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/base')>()),- getMarketplace: api.versions,-}))+vi.mock('@/service/marketplace', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/marketplace')>()+ const { createTanstackQueryUtils } = await import('@orpc/tanstack-query')+ return {+ ...actual,+ marketplaceQuery: createTanstackQueryUtils(+ {+ ...actual.marketplaceClient,+ pluginVersions: api.versions,+ },+ { path: ['marketplace'] },+ ),+ }+})const identifier = (version: string) => `langgenius/plugin-entity:${version}@test`const installed = zPostWorkspacesCurrentPluginListInstallationsIdsResponse.parse({@@ -124,6 +128,16 @@ const openActions = async (user: ReturnType<typeof userEvent.setup>) => {)}beforeEach(() => {+ api.autoUpgrade.mockReset().mockResolvedValue({+ category: 'model',+ auto_upgrade: {+ strategy_setting: 'disabled',+ upgrade_mode: 'all',+ upgrade_time_of_day: 0,+ include_plugins: [],+ exclude_plugins: [],+ },+ })api.detail.mockReset().mockResolvedValue({ plugins: [installed] })api.uninstall.mockReset().mockResolvedValue({ success: true })api.upgrade.mockReset().mockResolvedValue({ all_installed: true, task_id: '' })@@ -152,6 +166,53 @@ afterEach(() => {act(() => toast.dismiss())})+it('loads independent version prerequisites together and keeps the trigger focused while loading', async () => {+ const details = createDeferred<Awaited<ReturnType<typeof api.detail>>>()+ const versions = createDeferred<PluginVersionsResponse>()+ const versionResponse = await api.versions()+ api.versions.mockClear().mockReturnValueOnce(versions.promise)+ api.detail.mockReturnValueOnce(details.promise)+ const { user } = setup()+ const trigger = await screen.findByRole('button', { name: '1.0.0' })+ expect(api.detail).not.toHaveBeenCalled()+ expect(api.versions).not.toHaveBeenCalled()++ await user.click(trigger)+ await waitFor(() => {+ expect(api.detail).toHaveBeenCalledOnce()+ expect(api.versions).toHaveBeenCalledOnce()+ })+ expect(trigger).toHaveFocus()+ expect(trigger).toHaveAttribute('aria-disabled', 'true')+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ await user.click(trigger)+ expect(api.detail).toHaveBeenCalledOnce()+ await act(async () => details.resolve({ plugins: [installed] }))+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ await act(async () => versions.resolve(versionResponse))+ expect(+ await screen.findByRole('menu', { name: 'plugin.detailPanel.switchVersion' }),+ ).toBeInTheDocument()+ expect(trigger).not.toHaveAttribute('aria-disabled', 'true')+ await user.keyboard('{Escape}')+ await waitFor(() => expect(screen.queryByRole('menu')).not.toBeInTheDocument())+ expect(trigger).toHaveFocus()+ await user.click(trigger)+ expect(await screen.findByRole('menu')).toBeInTheDocument()+ expect(api.detail).toHaveBeenCalledOnce()+ expect(api.versions).toHaveBeenCalledOnce()+})++it('allows retrying a failed version query without reloading successful installation details', async () => {+ api.versions.mockRejectedValueOnce(new Error('marketplace unavailable'))+ const { user } = setup()+ await user.click(await screen.findByRole('button', { name: '1.0.0' }))+ await user.click(await screen.findByRole('menuitem', { name: 'common.operation.retry' }))+ expect(await screen.findByRole('menuitem', { name: /^2\.0\.0/ })).toBeInTheDocument()+ expect(api.versions).toHaveBeenCalledTimes(2)+ expect(api.detail).toHaveBeenCalledOnce()+})+it('loads GitHub package details only when the user opens plugin information', async () => {api.detail.mockResolvedValue({ plugins: [github] })const { user } = setup({@@ -205,7 +266,7 @@ it.each(['2.0.0', '0.5.0'])(})await user.click(await screen.findByRole('button', { name: '1.0.0' }))await user.click(- await screen.findByRole('button', { name: new RegExp(`^${next.replaceAll('.', '\\.')}`) }),+ await screen.findByRole('menuitem', { name: new RegExp(`^${next.replaceAll('.', '\\.')}`) }),)const dialog = await screen.findByRole('dialog', { name: 'plugin.upgrade.title' })await user.click(within(dialog).getByRole('button', { name: 'plugin.upgrade.upgrade' }))@@ -242,7 +303,7 @@ it('keeps the loaded plugin and confirmation usable when refreshing the summary.mockResolvedValue(undefined)const { user } = setup({ summary: summary(), providerLabel: 'Provider Plugin', onUpdate })await user.click(await screen.findByRole('button', { name: '1.0.0' }))- await user.click(await screen.findByRole('button', { name: /^2\.0\.0/ }))+ await user.click(await screen.findByRole('menuitem', { name: /^2\.0\.0/ }))const dialog = await screen.findByRole('dialog', { name: 'plugin.upgrade.title' })await user.click(within(dialog).getByRole('button', { name: 'plugin.upgrade.upgrade' }))await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())@@ -291,6 +352,8 @@ it('keeps a failed removal retryable without loading plugin details and refreshe},})expect(onUpdate).not.toHaveBeenCalled()+ await user.keyboard('{Escape}')+ expect(dialog).toBeInTheDocument()await act(async () => removal.resolve({ success: false }))expect(dialog).toBeInTheDocument()for (const key of relatedKeys) expect(queryClient.getQueryState(key)?.isInvalidated).toBe(false)@@ -381,3 +444,66 @@ it.each(['marketplace', 'github'] as const)(expect(api.uninstall).not.toHaveBeenCalled()},)++it('waits for the auto-upgrade policy before offering a downgrade', async () => {+ const policy = createDeferred<Awaited<ReturnType<typeof api.autoUpgrade>>>()+ api.autoUpgrade.mockReturnValueOnce(policy.promise)+ const { user } = setup()+ const trigger = await screen.findByRole('button', { name: '1.0.0' })+ await user.click(trigger)+ await waitFor(() => expect(api.versions).toHaveBeenCalledOnce())+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ expect(trigger).toHaveAttribute('aria-disabled', 'true')+ await act(async () =>+ policy.resolve({+ category: 'model',+ auto_upgrade: {+ strategy_setting: 'latest',+ upgrade_mode: 'all',+ upgrade_time_of_day: 0,+ include_plugins: [],+ exclude_plugins: [],+ },+ }),+ )+ await user.click(await screen.findByRole('menuitem', { name: /^0\.5\.0/ }))+ expect(+ await screen.findByRole('alertdialog', {+ name: 'plugin.autoUpdate.pluginDowngradeWarning.title',+ }),+ ).toBeInTheDocument()+ expect(api.upgrade).not.toHaveBeenCalled()+})++it('blocks confirmation if delete permission is revoked while the dialog is open', async () => {+ const { user, queryClient } = setup()+ await openActions(user)+ await user.click(screen.getByRole('menuitem', { name: 'plugin.detailPanel.operation.remove' }))+ const dialog = await screen.findByRole('alertdialog')+ await act(async () => seedWorkspacePermissionsQuery(queryClient, []))+ const confirm = within(dialog).getByRole('button', { name: 'common.operation.confirm' })+ await waitFor(() => expect(confirm).toBeDisabled())+ await user.click(confirm)+ expect(api.uninstall).not.toHaveBeenCalled()+})++it('keeps a later confirmation open when a dismissed update completes', async () => {+ const firstUpgrade = createDeferred<Awaited<ReturnType<typeof api.upgrade>>>()+ api.upgrade.mockReturnValueOnce(firstUpgrade.promise)+ const onUpdate = vi.fn()+ const { user } = setup({ summary: summary(), providerLabel: 'Provider Plugin', onUpdate })+ await user.click(await screen.findByRole('button', { name: '1.0.0' }))+ await user.click(await screen.findByRole('menuitem', { name: /^2\.0\.0/ }))+ const firstDialog = await screen.findByRole('dialog', { name: 'plugin.upgrade.title' })+ await user.click(within(firstDialog).getByRole('button', { name: 'plugin.upgrade.upgrade' }))+ await user.click(within(firstDialog).getByRole('button', { name: 'common.operation.close' }))+ await waitFor(() => expect(firstDialog).not.toBeInTheDocument())+ await user.click(screen.getByRole('button', { name: '1.0.0' }))+ await user.click(await screen.findByRole('menuitem', { name: /^0\.5\.0/ }))+ const nextDialog = await screen.findByRole('dialog', { name: 'plugin.upgrade.title' })+ await act(async () => firstUpgrade.resolve({ all_installed: true, task_id: '' }))+ await waitFor(() => expect(onUpdate).toHaveBeenCalledOnce())+ expect(nextDialog).toBeInTheDocument()+ expect(within(nextDialog).getByText('1.0.0 -> 0.5.0')).toBeInTheDocument()+ expect(within(nextDialog).getByRole('button', { name: 'plugin.upgrade.upgrade' })).toBeEnabled()+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/index.spec.tsxindex 4a21e7e7c28..f8a3f198123 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/__tests__/index.spec.tsx@@ -1,13 +1,14 @@import type { ModelProviderSummaryResponse } from '@dify/contracts/api/console/workspaces/types.gen'-import type { ModelProvider } from '../../../declarations'import type { CredentialPanelState } from '../../use-credential-panel-state'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { modelProviderDetailsQueryOptions } from '@/app/components/header/account-setting/model-provider-page/utils'-import { createProviderResponseFixture } from '@/test/console/model-provider'+import {+ createProviderResponseFixture,+ createProviderSummaryFixture,+} from '@/test/console/model-provider'import { renderWithConsoleQuery } from '@/test/console/query-data'import { createDeferred } from '@/test/deferred'-import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../../declarations'import ModelAuthDropdown from '../index'const render = (ui: React.ReactElement) => renderWithConsoleQuery(ui)@@ -23,18 +24,6 @@ vi.mock('../../../model-auth/hooks', () => ({}),}))-const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider =>- ({- ...createProviderResponseFixture({ provider: 'test' }),- custom_configuration: {- status: CustomConfigurationStatusEnum.active,- available_credentials: [],- },- system_configuration: { enabled: true, current_quota_type: 'trial', quota_configurations: [] },- preferred_provider_type: PreferredProviderTypeEnum.system,- ...overrides,- }) as unknown as ModelProvider-const createState = (overrides: Partial<CredentialPanelState> = {}): CredentialPanelState => ({variant: 'credits-active',priority: 'credits',@@ -89,7 +78,11 @@ describe('ModelAuthDropdown', () => {await user.click(screen.getByRole('button', { name: /addApiKey/i }))- expect(await screen.findByRole('status')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /addApiKey/i })).toHaveAttribute(+ 'aria-disabled',+ 'true',+ )+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()// The console client loads its contract segment before the first request starts.await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1))await act(async () => {@@ -114,86 +107,45 @@ describe('ModelAuthDropdown', () => {expect(fetchMock).toHaveBeenCalledTimes(2)})- it('should open popover on button click and show dropdown content', async () => {- const user = userEvent.setup()- render(- <ModelAuthDropdown- provider={createProvider({- custom_configuration: {- status: CustomConfigurationStatusEnum.active,- available_credentials: [{ credential_id: 'c1', credential_name: 'Key 1' }],- current_credential_id: 'c1',- current_credential_name: 'Key 1',- },- })}- state={createState({ hasCredentials: true, variant: 'api-active' })}- isChangingPriority={false}- onChangePriority={onChangePriority}- />,- )-- await user.click(screen.getByRole('button', { name: /config/i }))-- await waitFor(() => {- expect(screen.getByText('Key 1')).toBeInTheDocument()- })- expect(screen.getByRole('dialog', { name: /config/i })).toBeInTheDocument()- })-- it('should load provider detail on first click and reuse it on reopen', async () => {+ it('shares the provider detail response across cards without opening a loading popup', async () => {const user = userEvent.setup()- const fullProvider = createProviderResponseFixture({- provider: 'test',- custom_configuration: {- available_credentials: [{ credential_id: 'c1', credential_name: 'Key 1' }],- current_credential_id: 'c1',- current_credential_name: 'Key 1',- },- })- const providerSummary = {- provider: 'test',- is_configured: true,- custom_configuration: {- available_credentials: [{ credential_id: 'c1', credential_name: 'Key 1' }],- current_credential_id: 'c1',- current_credential_name: 'Key 1',- current_credential_usable: true,- },- } as unknown as ModelProviderSummaryResponse+ const request = createDeferred<Response>()+ const fetchMock = vi.mocked(globalThis.fetch).mockReturnValueOnce(request.promise)render(- <ModelAuthDropdown- provider={providerSummary}- state={createState({ hasCredentials: true, variant: 'api-active' })}- isChangingPriority={false}- onChangePriority={onChangePriority}- />,+ <>+ {['openai', 'tongyi'].map((provider) => (+ <ModelAuthDropdown+ key={provider}+ provider={createProviderSummaryFixture({ provider })}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />+ ))}+ </>,)- const fetchMock = vi.mocked(globalThis.fetch)- fetchMock.mockResolvedValueOnce(- new Response(JSON.stringify({ data: [fullProvider] }), {- status: 200,- headers: { 'Content-Type': 'application/json' },- }),+ const triggers = screen.getAllByRole('button', { name: /addApiKey/i })+ await user.click(triggers[0]!)+ expect(triggers[0]).toHaveFocus()+ expect(triggers[0]).toHaveAttribute('aria-disabled', 'true')+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await waitFor(() => expect(fetchMock).toHaveBeenCalledOnce())+ await act(async () =>+ request.resolve(+ Response.json({+ data: ['openai', 'tongyi'].map((provider) =>+ createProviderResponseFixture({ provider }),+ ),+ }),+ ),)- const trigger = screen.getByRole('button', { name: /config/i })-- await user.click(trigger)-- await waitFor(() => {- expect(screen.getByText('Key 1')).toBeInTheDocument()- })- expect(fetchMock).toHaveBeenCalledTimes(1)-- await user.click(trigger)- await waitFor(() => {- expect(screen.queryByText('Key 1')).not.toBeInTheDocument()- })- await user.click(trigger)-- await waitFor(() => {- expect(screen.getByText('Key 1')).toBeInTheDocument()- })- expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(await screen.findByRole('dialog')).toBeInTheDocument()+ await user.keyboard('{Escape}')+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(triggers[0]).toHaveFocus()+ await user.click(triggers[1]!)+ expect(await screen.findByRole('dialog')).toBeInTheDocument()+ expect(fetchMock).toHaveBeenCalledOnce()})it('should render updated provider detail from the query cache', async () => {diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.tsxindex 5e42c04f625..3437a8cd0f6 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.tsx@@ -3,9 +3,10 @@ import type { ModelProvider, PreferredProviderTypeEnum } from '../../declarationimport type { CredentialPanelState } from '../use-credential-panel-state'import { Button } from '@langgenius/dify-ui/button'import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from '@langgenius/dify-ui/popover'-import { memo, useCallback, useState } from 'react'+import { useQuery } from '@tanstack/react-query'+import { memo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { useLazyModelProviderDetail } from '../../hooks'+import { modelProviderDetailsQueryOptions } from '../../utils'import { getButtonConfig } from './button-config'import DropdownContent from './dropdown-content'@@ -23,42 +24,22 @@ function ModelAuthDropdown({onChangePriority,}: ModelAuthDropdownProps) {const { t } = useTranslation(['common', 'modelProvider'])- const [open, setOpen] = useState(false)- const [isProviderDetailError, setIsProviderDetailError] = useState(false)+ const [requestedOpen, setRequestedOpen] = useState(false)const isFullProvider = !('is_configured' in provider) || 'provider_credential_schema' in provider- const { providerDetail, loadProviderDetail, isProviderDetailEnabled, isLoadingProviderDetail } =- useLazyModelProviderDetail(provider.provider)- const currentProvider = isFullProvider ? provider : providerDetail-- const handleClose = useCallback(() => {- setOpen(false)- setIsProviderDetailError(false)- }, [])-+ const detailQuery = useQuery({+ ...modelProviderDetailsQueryOptions(),+ enabled: requestedOpen && !isFullProvider,+ retry: false,+ })+ const currentProvider = isFullProvider+ ? provider+ : detailQuery.data?.data.find((item) => item.provider === provider.provider)+ const loading = requestedOpen && !isFullProvider && detailQuery.isLoading+ const open = requestedOpen && (isFullProvider || !detailQuery.isPending)const buttonConfig = getButtonConfig(state.variant, state.hasCredentials, t)- const loadDetail = useCallback(async () => {- setIsProviderDetailError(false)- const detail = await loadProviderDetail()- if (!detail) setIsProviderDetailError(true)- }, [loadProviderDetail])-- const handleOpenChange = (nextOpen: boolean) => {- if (!nextOpen) {- handleClose()- return- }-- setOpen(true)-- if (- !isFullProvider &&- !(currentProvider && isProviderDetailEnabled && !isLoadingProviderDetail)- )- void loadDetail()- }return (- <Popover open={open} onOpenChange={handleOpenChange}>+ <Popover open={open} onOpenChange={setRequestedOpen}><PopoverTriggerrender={<Button@@ -66,7 +47,7 @@ function ModelAuthDropdown({size="small"variant={buttonConfig.variant}title={buttonConfig.text}- loading={isLoadingProviderDetail}+ loading={loading}><span className="i-ri-equalizer-2-line size-3.5 shrink-0" /><span className="min-w-0 truncate">{buttonConfig.text}</span>@@ -81,31 +62,17 @@ function ModelAuthDropdown({state={state}isChangingPriority={isChangingPriority}onChangePriority={onChangePriority}- onClose={handleClose}+ onClose={() => setRequestedOpen(false)}/>- ) : isProviderDetailError ? (+ ) : (<div className="flex w-80 flex-col items-start gap-3 p-4" role="alert"><span className="system-sm-medium text-text-primary">{t(($) => $['api.actionFailed'], { ns: 'common' })}</span>- <Button size="small" variant="secondary" onClick={() => void loadDetail()}>+ <Button size="small" variant="secondary" onClick={() => void detailQuery.refetch()}>{t(($) => $['operation.retry'], { ns: 'common' })}</Button></div>- ) : (- <div- className="flex w-80 items-center justify-center gap-2 p-4"- role="status"- aria-busy="true"- >- <span- aria-hidden- className="i-ri-loader-2-line size-4 animate-spin text-text-tertiary motion-reduce:animate-none"- />- <span className="system-sm-regular text-text-secondary">- {t(($) => $.loading, { ns: 'common' })}- </span>- </div>)}</PopoverContent></Popover>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.tsxindex aff4589d8f5..576fb539187 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@@ -1,4 +1,4 @@-import type { FC } from 'react'+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'import type { ModelProviderPluginSummary } from '../index'import type { PluginDetail } from '@/app/components/plugins/types'import {@@ -12,31 +12,37 @@ import {AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuGroupLabel,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { useQueryClient } from '@tanstack/react-query'-import { useBoolean } from 'ahooks'-import { useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { skipToken, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'+import { useId, useState } from 'react'import { useTranslation } from 'react-i18next'import { useLocale } from '#i18n'import Badge from '@/app/components/base/badge'-import { HeaderModals } from '@/app/components/plugins/plugin-detail-panel/detail-header/components'-import {- useDetailHeaderState,- usePluginOperations,-} from '@/app/components/plugins/plugin-detail-panel/detail-header/hooks'import { OperationDropdown } from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'+import PluginInfoContent from '@/app/components/plugins/plugin-page/plugin-info'import { usePluginSettingsAccess } from '@/app/components/plugins/plugin-page/use-reference-setting'-import { PluginSource } from '@/app/components/plugins/types'-import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'+import { PluginCategoryEnum, PluginSource } from '@/app/components/plugins/types'+import { checkGitHubPluginUpdate } from '@/app/components/plugins/update-plugin/check-github-update'+import MarketplaceUpdateDialog from '@/app/components/plugins/update-plugin/from-market-place'+import { useModalContext } from '@/context/modal-context'+import { systemFeaturesQueryOptions } from '@/features/system-features/client'import useTheme from '@/hooks/use-theme'+import useTimestamp from '@/hooks/use-timestamp'import { consoleQuery } from '@/service/console'-import { uninstallPlugin } from '@/service/plugins'-import { normalizeInstalledPluginDetail } from '@/service/use-plugins'+import { marketplaceQuery } from '@/service/marketplace'+import { normalizeInstalledPluginDetail, usePluginAutoUpgradeSettings } from '@/service/use-plugins'+import { isEarlierThanVersion } from '@/utils/semver'import { getMarketplaceUrl } from '@/utils/var'-type DetailAction = 'version' | 'latest' | 'info' | 'check'-type Props =| Readonly<{summary: ModelProviderPluginSummary@@ -58,10 +64,97 @@ const pluginSourceMap: Record<ModelProviderPluginSummary['source'], PluginSourceremote: PluginSource.debugging,}-const ProviderCardActions: FC<Props> = (props) => {+type UpdateSession = {+ detail: PluginDetail+ target: Pick<+ PluginVersionsResponse['data']['versions'][number],+ 'version' | 'unique_identifier'+ > & { warnAboutAutoUpdate: boolean }+}++function ProviderCardActions(props: Props) {+ const { t } = useTranslation(['appDebug', 'common', 'plugin', 'appLog'])+ const versionMenuLabelId = useId()+ const { formatDate } = useTimestamp()+ const dateFormat = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]!const queryClient = useQueryClient()+ const { canDeletePlugin, canUpdatePlugin } = usePluginSettingsAccess()+ const { setShowUpdatePluginModal } = useModalContext()+ const locale = useLocale()+ const { theme } = useTheme()const { onUpdate } = props- const handlePluginChanged = useCallback(async () => {+ const pluginID = props.detail ? props.detail.plugin_id : props.summary.plugin_id+ const source = props.detail ? props.detail.source : pluginSourceMap[props.summary.source]+ const version = props.detail?.version ?? props.summary?.version+ const latestVersion = props.detail?.latest_version ?? props.summary?.latestVersion+ const latestIdentifier =+ props.detail?.latest_unique_identifier ?? props.summary?.latestUniqueIdentifier+ const isFromMarketplace = source === PluginSource.marketplace+ const isFromGitHub = source === PluginSource.github+ const canChangeVersion = canUpdatePlugin && isFromMarketplace+ const hasNewVersion = isFromMarketplace && !!latestVersion && latestVersion !== version+ const category = props.detail?.declaration.category ?? PluginCategoryEnum.model+ const autoUpgradeSettings = usePluginAutoUpgradeSettings(category)+ const { data: enableMarketplace } = useQuery({+ ...systemFeaturesQueryOptions(),+ select: (value) => value.enable_marketplace,+ })+ const policy = autoUpgradeSettings.data?.auto_upgrade+ const autoUpgradeEnabled =+ enableMarketplace &&+ policy &&+ policy.strategy_setting !== 'disabled' &&+ (policy.upgrade_mode === 'all' ||+ (policy.upgrade_mode === 'partial' && policy.include_plugins.includes(pluginID)) ||+ (policy.upgrade_mode === 'exclude' && !policy.exclude_plugins.includes(pluginID)))+ const [organization, pluginName] = pluginID.split('/')+ const [versionMenuRequested, setVersionMenuRequested] = useState(false)+ const [info, setInfo] = useState<PluginDetail>()+ const [infoOpen, setInfoOpen] = useState(false)+ const [update, setUpdate] = useState<UpdateSession>()+ const [updateOpen, setUpdateOpen] = useState(false)+ const [showDeleteConfirm, setShowDeleteConfirm] = useState(false)+ const detailQuery = useQuery(+ consoleQuery.workspaces.current.plugin.list.installations.ids.post.queryOptions({+ input: { body: { plugin_ids: [pluginID] } },+ enabled: versionMenuRequested && canChangeVersion && !props.detail,+ retry: false,+ select: (response) =>+ response.plugins[0] ? normalizeInstalledPluginDetail(response.plugins[0]) : undefined,+ }),+ )+ const versionsQuery = useQuery(+ marketplaceQuery.pluginVersions.queryOptions({+ input:+ organization && pluginName+ ? {+ params: { organization, pluginName },+ query: { page: 1, page_size: 100 },+ }+ : skipToken,+ enabled: versionMenuRequested && canChangeVersion,+ retry: false,+ }),+ )+ const detail = props.detail ?? detailQuery.data+ const loadingVersions =+ versionMenuRequested &&+ canChangeVersion &&+ (versionsQuery.isPending ||+ (!props.detail && detailQuery.isPending) ||+ autoUpgradeSettings.isPending)+ const versionMenuOpen = versionMenuRequested && canChangeVersion && !loadingVersions+ const detailUrl =+ isFromMarketplace && organization && pluginName+ ? getMarketplaceUrl(+ `/plugins/${props.detail?.declaration.author ?? organization}/${props.detail?.declaration.name ?? pluginName}`,+ { language: locale, theme },+ )+ : isFromGitHub && detail?.meta?.repo+ ? `https://github.com/${detail.meta.repo}`+ : ''++ const handlePluginChanged = async () => {await Promise.all([queryClient.invalidateQueries({queryKey: consoleQuery.workspaces.current.modelProviders.summary.get.key(),@@ -82,140 +175,142 @@ const ProviderCardActions: FC<Props> = (props) => {queryClient.invalidateQueries({ queryKey: ['marketplaceCollectionPlugins'] }),])await onUpdate?.()- }, [onUpdate, queryClient])+ }- if (props.detail) {- return (- <LoadedProviderCardActions- detail={props.detail}- onInitialActionHandled={() => {}}- onUpdate={handlePluginChanged}- />+ const loadDetail = async () => {+ if (props.detail) return props.detail+ const response = await queryClient.query(+ consoleQuery.workspaces.current.plugin.list.installations.ids.post.queryOptions({+ input: { body: { plugin_ids: [pluginID] } },+ }),)+ return response.plugins[0] ? normalizeInstalledPluginDetail(response.plugins[0]) : undefined}- return <SummaryProviderCardActions {...props} onUpdate={handlePluginChanged} />-}--type SummaryProps = Extract<Props, { summary: ModelProviderPluginSummary }>--function SummaryProviderCardActions({ summary, providerLabel, onUpdate }: SummaryProps) {- const { t } = useTranslation(['appDebug', 'common', 'plugin'])- const queryClient = useQueryClient()- const { canDeletePlugin, canUpdatePlugin } = usePluginSettingsAccess()- const [detail, setDetail] = useState<PluginDetail>()- const [detailAction, setDetailAction] = useState<DetailAction>()- const [loadingAction, setLoadingAction] = useState<DetailAction>()- const [showDeleteConfirm, { setTrue: openDeleteConfirm, setFalse: closeDeleteConfirm }] =- useBoolean(false)- const [deleting, { setTrue: startDeleting, setFalse: finishDeleting }] = useBoolean(false)- const source = pluginSourceMap[summary.source]- const isFromMarketplace = source === PluginSource.marketplace- const isFromGitHub = source === PluginSource.github- const canChangeVersion = canUpdatePlugin && isFromMarketplace- const hasNewVersion =- isFromMarketplace && !!summary.latestVersion && summary.latestVersion !== summary.version- const [author, name] = summary.plugin_id.split('/')- const detailUrl =- isFromMarketplace && author && name ? getMarketplaceUrl(`/plugins/${author}/${name}`) : ''-- const loadDetail = async (action: DetailAction) => {- setLoadingAction(action)+ const handleInfo = async () => {try {- const response = await queryClient.query(- consoleQuery.workspaces.current.plugin.list.installations.ids.post.queryOptions({- input: { body: { plugin_ids: [summary.plugin_id] } },- }),- )- const nextDetail = response.plugins[0]- if (!nextDetail) return- const normalizedDetail = normalizeInstalledPluginDetail(nextDetail)- const detailWithLatestVersion =- isFromMarketplace && summary.latestVersion && summary.latestUniqueIdentifier- ? {- ...normalizedDetail,- latest_version: summary.latestVersion,- latest_unique_identifier: summary.latestUniqueIdentifier,- }- : normalizedDetail- setDetail(detailWithLatestVersion)- setDetailAction(action)- } catch {- } finally {- setLoadingAction(undefined)- }+ const loaded = await loadDetail()+ if (loaded) {+ setInfo(loaded)+ setInfoOpen(true)+ }+ } catch {}}-- const handleDelete = async () => {- startDeleting()+ const handleUpdate = async () => {+ if (!canUpdatePlugin) returntry {- const response = await uninstallPlugin(summary.installation_id)- if (!response.success) return- closeDeleteConfirm()- await onUpdate?.()- } finally {- finishDeleting()- }- }-- const handleLoadedDetailUpdated = useCallback(async () => {- await onUpdate?.()- setDetail(undefined)- }, [onUpdate])-- if (detail) {- return (- <LoadedProviderCardActions- detail={detail}- initialAction={detailAction}- onInitialActionHandled={() => setDetailAction(undefined)}- onUpdate={handleLoadedDetailUpdated}- />- )+ const loaded = await loadDetail()+ if (!loaded) return+ if (isFromGitHub) {+ await checkGitHubPluginUpdate(loaded, setShowUpdatePluginModal, handlePluginChanged)+ } else if (latestVersion && latestIdentifier) {+ setUpdate({+ detail: loaded,+ target: {+ version: latestVersion,+ unique_identifier: latestIdentifier,+ warnAboutAutoUpdate: false,+ },+ })+ setUpdateOpen(true)+ }+ } catch {}}+ const remove = useMutation(+ consoleQuery.workspaces.current.plugin.uninstall.post.mutationOptions({+ onSuccess: async (response) => {+ if (!response.success) return+ await handlePluginChanged()+ setShowDeleteConfirm(false)+ },+ }),+ )return (<>- {!!summary.version && (- <>- {canChangeVersion ? (- <button- type="button"- className="rounded-md border-0 bg-transparent p-0 focus-visible:ring-2 focus-visible:ring-state-accent-solid focus-visible:outline-hidden"- aria-label={summary.version}- disabled={loadingAction === 'version'}- onClick={() => loadDetail('version')}- >- <Badge- className="cursor-pointer hover:bg-state-base-hover"- uppercase={false}- text={- <>- <span>{summary.version}</span>- <span className="ml-1 i-ri-arrow-left-right-line size-3" />- </>- }- hasRedCornerMark={hasNewVersion}- />- </button>- ) : (- <Badge- uppercase={false}- text={<span>{summary.version}</span>}- hasRedCornerMark={hasNewVersion}- />- )}- {source === PluginSource.debugging && (- <Badge- className="border-state-warning-active bg-state-warning-hover text-text-warning"- size="xs"- uppercase={false}- text={t(($) => $['operation.debugConfig'], { ns: 'appDebug' })}+ <DropdownMenu open={!!version && versionMenuOpen} onOpenChange={setVersionMenuRequested}>+ {!!version &&+ (canChangeVersion ? (+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="small"+ loading={loadingVersions}+ className="relative h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.25 system-xs-medium text-text-tertiary"+ >+ {hasNewVersion && (+ <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-xs border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm" />+ )}+ <span>{version}</span>+ {!loadingVersions && (+ <span aria-hidden className="i-ri-arrow-left-right-line size-3" />+ )}+ </Button>+ }/>- )}- </>+ ) : (+ <Badge uppercase={false} text={version} hasRedCornerMark={hasNewVersion} />+ ))}+ <DropdownMenuContent+ className="max-h-[min(16rem,var(--available-height))]"+ placement="bottom-start"+ aria-labelledby={versionMenuLabelId}+ >+ <DropdownMenuGroup>+ <DropdownMenuGroupLabel id={versionMenuLabelId}>+ {t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}+ </DropdownMenuGroupLabel>+ {version && versionsQuery.data && detail && autoUpgradeSettings.data ? (+ versionsQuery.data.data.versions.map((item) => (+ <DropdownMenuItem+ key={item.unique_identifier}+ disabled={version === item.version}+ onClick={() => {+ setUpdate({+ detail,+ target: {+ version: item.version,+ unique_identifier: item.unique_identifier,+ warnAboutAutoUpdate:+ !!autoUpgradeEnabled && isEarlierThanVersion(item.version, version),+ },+ })+ setUpdateOpen(true)+ }}+ >+ <span>{item.version}</span>+ {version === item.version && (+ <Badge className="shrink-0" variant="dimm" text="CURRENT" />+ )}+ <span className="ms-auto text-text-tertiary">+ {formatDate(item.created_at, dateFormat)}+ </span>+ </DropdownMenuItem>+ ))+ ) : (+ <DropdownMenuItem+ closeOnClick={false}+ onClick={() => {+ if (versionsQuery.isError) void versionsQuery.refetch()+ if (autoUpgradeSettings.isError) void autoUpgradeSettings.refetch()+ if (!detail) void detailQuery.refetch()+ }}+ >+ {t(($) => $['operation.retry'], { ns: 'common' })}+ </DropdownMenuItem>+ )}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>+ {source === PluginSource.debugging && (+ <Badge+ className="border-state-warning-active bg-state-warning-hover text-text-warning"+ size="xs"+ uppercase={false}+ text={t(($) => $['operation.debugConfig'], { ns: 'appDebug' })}+ />)}-{canUpdatePlugin && (hasNewVersion || isFromGitHub) && (<Tooltip><TooltipTrigger@@ -224,9 +319,9 @@ function SummaryProviderCardActions({ summary, providerLabel, onUpdate }: Summar<Buttonvariant="secondary-accent"size="small"- className="h-5!"- loading={loadingAction === 'latest'}- onClick={() => loadDetail('latest')}+ className="h-5"+ loading={detailQuery.isFetching && !versionMenuRequested}+ onClick={handleUpdate}>{t(($) => $['detailPanel.operation.update'], { ns: 'plugin' })}</Button>@@ -237,23 +332,22 @@ function SummaryProviderCardActions({ summary, providerLabel, onUpdate }: Summar</TooltipContent></Tooltip>)}-<OperationDropdownsource={source}- onInfo={() => loadDetail('info')}- onCheckVersion={() => loadDetail('check')}- onRemove={openDeleteConfirm}+ onInfo={handleInfo}+ onCheckVersion={handleUpdate}+ onRemove={() => setShowDeleteConfirm(true)}detailUrl={detailUrl}placement="bottom-start"destructiveRemoveshowCheckVersion={canUpdatePlugin}showRemove={canDeletePlugin}/>-<AlertDialogopen={showDeleteConfirm}- onOpenChange={(open) => {- if (!open) closeDeleteConfirm()+ onOpenChange={(open, details) => {+ if (!open && remove.isPending) details.cancel()+ else setShowDeleteConfirm(open)}}><AlertDialogContent backdropProps={{ forceRender: true }}>@@ -261,188 +355,66 @@ function SummaryProviderCardActions({ summary, providerLabel, onUpdate }: Summar<AlertDialogTitle>{t(($) => $['action.delete'], { ns: 'plugin' })}</AlertDialogTitle><AlertDialogDescription>{t(($) => $['action.deleteContentLeft'], { ns: 'plugin' })}- <span className="system-md-semibold text-text-secondary">{providerLabel}</span>+ <span className="system-md-semibold text-text-secondary">+ {props.providerLabel ?? props.detail?.declaration.label[locale]}+ </span>{t(($) => $['action.deleteContentRight'], { ns: 'plugin' })}</AlertDialogDescription></AlertDialogHeader><AlertDialogFooter>- <AlertDialogCancelButton disabled={deleting}>+ <AlertDialogCancelButton disabled={remove.isPending}>{t(($) => $['operation.cancel'], { ns: 'common' })}</AlertDialogCancelButton>- <AlertDialogConfirmButton loading={deleting} onClick={handleDelete}>+ <AlertDialogConfirmButton+ loading={remove.isPending}+ disabled={!canDeletePlugin}+ onClick={() =>+ remove.mutate({+ body: {+ plugin_installation_id: props.detail+ ? props.detail.id+ : props.summary.installation_id,+ preserve_credentials: false,+ },+ })+ }+ >{t(($) => $['operation.confirm'], { ns: 'common' })}</AlertDialogConfirmButton></AlertDialogFooter></AlertDialogContent></AlertDialog>- </>- )-}--type LoadedProps = Readonly<{- detail: PluginDetail- initialAction?: DetailAction- onInitialActionHandled: () => void- onUpdate?: () => void | Promise<void>-}>--function LoadedProviderCardActions({- detail,- initialAction,- onInitialActionHandled,- onUpdate,-}: LoadedProps) {- const { t } = useTranslation(['appDebug', 'plugin'])- const { theme } = useTheme()- const locale = useLocale()- const { canDeletePlugin, canUpdatePlugin } = usePluginSettingsAccess()- const { source, version, latest_version, latest_unique_identifier, meta } = detail- const author = detail.declaration?.author ?? ''- const name = detail.declaration?.name ?? detail.name- const isDebuggingPlugin = source === PluginSource.debugging- const {- modalStates,- versionPicker,- hasNewVersion,- isAutoUpgradeEnabled,- isFromMarketplace,- isFromGitHub,- } = useDetailHeaderState(detail)- const { handleUpdate, handleUpdatedFromMarketplace, handleDelete } = usePluginOperations({- detail,- modalStates,- versionPicker,- isFromMarketplace,- canDeletePlugin,- canUpdatePlugin,- onUpdate,- })-- const handleVersionSelect = (state: {- version: string- unique_identifier: string- isDowngrade?: boolean- }) => {- versionPicker.setTargetVersion(state)- handleUpdate(state.isDowngrade)- }-- const handleTriggerLatestUpdate = useCallback(() => {- if (isFromMarketplace) {- if (!latest_unique_identifier) return- versionPicker.setTargetVersion({- version: latest_version,- unique_identifier: latest_unique_identifier,- })- }- handleUpdate()- }, [handleUpdate, isFromMarketplace, latest_unique_identifier, latest_version, versionPicker])-- const pendingInitialActionRef = useRef(initialAction)- useEffect(() => {- const pendingAction = pendingInitialActionRef.current- if (!pendingAction) return- pendingInitialActionRef.current = undefined- if (pendingAction === 'version') versionPicker.setIsShow(true)- if (pendingAction === 'latest') handleTriggerLatestUpdate()- if (pendingAction === 'info') modalStates.showPluginInfo()- if (pendingAction === 'check') handleUpdate()- onInitialActionHandled()- }, [handleTriggerLatestUpdate, handleUpdate, modalStates, onInitialActionHandled, versionPicker])-- const detailUrl = useMemo(() => {- if (source === PluginSource.github) return meta?.repo ? `https://github.com/${meta.repo}` : ''- if (source === PluginSource.marketplace)- return getMarketplaceUrl(`/plugins/${author}/${name}`, { language: locale, theme })- return ''- }, [source, meta?.repo, author, name, locale, theme])-- return (- <>- {!!version && (- <>- <PluginVersionPicker- disabled={!isFromMarketplace || !canUpdatePlugin}- isShow={versionPicker.isShow}- onShowChange={versionPicker.setIsShow}- pluginID={detail.plugin_id}- currentVersion={version}- onSelect={handleVersionSelect}- sideOffset={4}- alignOffset={0}- trigger={() => (- <Badge- className={cn(- canUpdatePlugin &&- isFromMarketplace &&- 'cursor-pointer hover:bg-state-base-hover',- )}- uppercase={false}- text={- <>- <span>{version}</span>- {canUpdatePlugin && isFromMarketplace && (- <span className="ml-1 i-ri-arrow-left-right-line size-3" />- )}- </>- }- hasRedCornerMark={hasNewVersion}- />- )}- />- {isDebuggingPlugin && (- <Badge- className="border-state-warning-active bg-state-warning-hover text-text-warning"- size="xs"- uppercase={false}- text={t(($) => $['operation.debugConfig'], { ns: 'appDebug' })}+ <Dialog open={infoOpen} onOpenChange={setInfoOpen}>+ <DialogContent className="w-120">+ {info && (+ <PluginInfoContent+ repository={info.meta?.repo}+ release={info.version}+ packageName={info.meta?.package}/>)}- </>- )}-- {canUpdatePlugin && (hasNewVersion || isFromGitHub) && (- <Tooltip>- <TooltipTrigger- delay={300}- render={- <Button- variant="secondary-accent"- size="small"- className="h-5!"- onClick={handleTriggerLatestUpdate}- >- {t(($) => $['detailPanel.operation.update'], { ns: 'plugin' })}- </Button>- }- />- <TooltipContent>- {t(($) => $['detailPanel.operation.updateTooltip'], { ns: 'plugin' })}- </TooltipContent>- </Tooltip>+ </DialogContent>+ </Dialog>+ {update && (+ <MarketplaceUpdateDialog+ open={updateOpen}+ onClose={() => setUpdateOpen(false)}+ pluginId={update.detail.plugin_id}+ payload={{+ category: update.detail.declaration.category,+ originalPackageInfo: {+ id: update.detail.plugin_unique_identifier,+ payload: update.detail.declaration,+ },+ targetPackageInfo: {+ id: update.target.unique_identifier,+ version: update.target.version,+ },+ }}+ warnAboutAutoUpdate={update.target.warnAboutAutoUpdate}+ onRefresh={handlePluginChanged}+ />)}-- <OperationDropdown- source={source}- onInfo={modalStates.showPluginInfo}- onCheckVersion={() => handleUpdate()}- onRemove={modalStates.showDeleteConfirm}- detailUrl={detailUrl}- placement="bottom-start"- destructiveRemove- showCheckVersion={canUpdatePlugin}- showRemove={canDeletePlugin}- />-- <HeaderModals- detail={detail}- modalStates={modalStates}- targetVersion={versionPicker.targetVersion}- isDowngrade={versionPicker.isDowngrade}- isAutoUpgradeEnabled={isAutoUpgradeEnabled}- onUpdatedFromMarketplace={handleUpdatedFromMarketplace}- onDelete={handleDelete}- /></>)}diff --git a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsxindex 9720badd1ed..a967d00d482 100644--- a/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx+++ b/web/app/components/integrations/__tests__/tool-provider-list.spec.tsx@@ -68,6 +68,7 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.toolProviders.get': api.providers,'workspaces.current.plugin.list.installations.ids.post': api.installed,'workspaces.current.toolProvider.builtin.byProvider.tools.get': api.builtinTools,@@ -83,7 +84,6 @@ vi.mock('@/service/console', async (importOriginal) => {consoleClient: withConsoleClientResponses(actual.consoleClient, {'workspaces.current.toolProvider.builtin.byProvider.tools.get': api.builtinTools,'workspaces.current.toolProvider.api.add.post': api.createCustom,- 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.plugin.tasks.get': async () => ({ tasks: [] }),'workspaces.current.toolProvider.api.schema.post': api.parseSchema,'workspaces.current.plugin.permission.fetch.get': async () => ({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.tsindex 546930323b4..02207bf2101 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@@ -41,6 +41,14 @@ const providerKeys = [current.modelProviders.summary.get.key(),consoleQuery.workspaces.current.modelProviders.get.key(),]+const pluginVersionKeys = [+ current.plugin.list.installations.ids.post.queryKey({+ input: { body: { plugin_ids: ['langgenius/test'] } },+ }),+ current.plugin.list.latestVersions.post.queryKey({+ input: { body: { plugin_ids: ['langgenius/test'] } },+ }),+]const datasourceKey = consoleQuery.rag.pipelines.datasourcePlugins.get.queryKey()const dataSourceAuthKey = consoleQuery.auth.plugin.datasource.list.get.queryKey()const toolKeys = [@@ -68,7 +76,7 @@ describe('plugin installation refresh', () => {client = new QueryClient({defaultOptions: { queries: { retry: false, staleTime: Infinity } },})- for (const key of [...strategyKeys, ...providerKeys, unrelatedKey])+ for (const key of [...strategyKeys, ...providerKeys, ...pluginVersionKeys, unrelatedKey])client.setQueryData(key, { cached: true })client.setQueryData(datasourceKey, [])client.setQueryData(dataSourceAuthKey, { result: [] })@@ -88,6 +96,7 @@ describe('plugin installation refresh', () => {const { result } = renderHook(useRefreshPluginList, { wrapper })act(() => result.current.refreshPluginList({ category: PluginCategoryEnum.agent }))+ for (const key of pluginVersionKeys) expect(client.getQueryState(key)?.isInvalidated).toBe(true)expect(mocks.installed).toHaveBeenCalledWith(PluginCategoryEnum.agent)expect(mocks.checkInstalled).toHaveBeenCalledOnce()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.tsxindex e8ae6fecbe3..c2ab8dcd4ab 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@@ -63,6 +63,12 @@ const useRefreshPluginList = () => {if (refreshAllType || !manifest) invalidateInstalledPluginList()else invalidateInstalledPluginList(manifest.category)invalidateCheckInstalled()+ queryClient.invalidateQueries({+ queryKey: consoleQuery.workspaces.current.plugin.list.installations.ids.post.key(),+ })+ queryClient.invalidateQueries({+ queryKey: consoleQuery.workspaces.current.plugin.list.latestVersions.post.key(),+ })// tool page, tool selectif ((manifest && PluginCategoryEnum.tool.includes(manifest.category)) || refreshAllType) {diff --git a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx b/web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsxsimilarity index 65%rename from web/app/components/plugins/update-plugin/__tests__/index.spec.tsxrename to web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsxindex e51d864433d..c3d2c0b0411 100644--- a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx+++ b/web/app/components/plugins/install-plugin/install-from-github/__tests__/update.spec.tsx@@ -1,21 +1,18 @@-import type { UpdateFromGitHubPayload, UpdateFromMarketPlacePayload } from '../../types'-import { screen, waitFor } from '@testing-library/react'+import type { UpdateFromGitHubPayload } from '../../../types'+import { screen } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'-import { PluginCategoryEnum, PluginSource } from '../../types'-import UpdatePlugin from '../index'+import InstallFromGitHub from '../index'-const { uploadGitHub, updateFromGitHub, updateFromMarketPlace } = vi.hoisted(() => ({+const { uploadGitHub, updateFromGitHub } = vi.hoisted(() => ({uploadGitHub: vi.fn(),updateFromGitHub: vi.fn(),- updateFromMarketPlace: vi.fn(),}))vi.mock('@/service/plugins', async (importOriginal) => ({...(await importOriginal<typeof import('@/service/plugins')>()),uploadGitHub,updateFromGitHub,- updateFromMarketPlace,}))vi.mock('@/service/console', async (importOriginal) => {const actual = await importOriginal<typeof import('@/service/console')>()@@ -28,7 +25,7 @@ vi.mock('@/service/console', async (importOriginal) => {}})// Model/tool catalog refresh is covered by its own hook tests.-vi.mock('../../install-plugin/hooks/use-refresh-plugin-list', () => ({+vi.mock('../../hooks/use-refresh-plugin-list', () => ({default: () => ({ refreshPluginList: vi.fn() }),}))@@ -64,12 +61,6 @@ const github: UpdateFromGitHubPayload = {],},}-const marketPlace: UpdateFromMarketPlacePayload = {- category: PluginCategoryEnum.tool,- originalPackageInfo: { id: 'marketplace-original-id', payload: createPluginDeclarationFixture() },- targetPackageInfo: { id: 'marketplace-target-id', version: '2.0.0' },-}-beforeEach(() => vi.resetAllMocks())it('updates a GitHub plugin using the selected release and the existing installation identifier', async () => {@@ -81,15 +72,7 @@ it('updates a GitHub plugin using the selected release and the existing installaupdateFromGitHub.mockResolvedValueOnce({ all_installed: true, task_id: '' })const onSave = vi.fn()const onCancel = vi.fn()- render(- <UpdatePlugin- type={PluginSource.github}- category={PluginCategoryEnum.tool}- github={github}- onSave={onSave}- onCancel={onCancel}- />,- )+ render(<InstallFromGitHub updatePayload={github} onSuccess={onSave} onClose={onCancel} />)await user.click(screen.getByRole('combobox', { name: 'plugin.installFromGitHub.selectVersion' }))expect(await screen.findByRole('option', { name: /v1\.0\.0.*INSTALLED/ })).toBeInTheDocument()@@ -115,28 +98,4 @@ it('updates a GitHub plugin using the selected release and the existing installa)expect(onSave).toHaveBeenCalledOnce()expect(onCancel).not.toHaveBeenCalled()- expect(updateFromMarketPlace).not.toHaveBeenCalled()-})--it('routes a marketplace update to its package identifiers and completion callback', async () => {- const user = userEvent.setup()- updateFromMarketPlace.mockResolvedValueOnce({ all_installed: true, task_id: '' })- const onSave = vi.fn()- render(- <UpdatePlugin- type={PluginSource.marketplace}- category={PluginCategoryEnum.tool}- marketPlace={marketPlace}- onSave={onSave}- onCancel={vi.fn()}- />,- )- expect(screen.getByText('1.0.0 -> 2.0.0')).toBeInTheDocument()- await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))- await waitFor(() => expect(onSave).toHaveBeenCalledOnce())- expect(updateFromMarketPlace).toHaveBeenCalledExactlyOnceWith({- original_plugin_unique_identifier: 'marketplace-original-id',- new_plugin_unique_identifier: 'marketplace-target-id',- })- expect(updateFromGitHub).not.toHaveBeenCalled()})diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/index.spec.tsxindex dc4dd7b3325..dda729dbc3b 100644--- a/web/app/components/plugins/plugin-detail-panel/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/index.spec.tsx@@ -1,6 +1,7 @@import type { ComponentProps, ReactElement } from 'react'import type { Credential } from '@/app/components/plugins/plugin-auth/types'import type { PluginDeclaration, PluginDetail } from '@/app/components/plugins/types'+import type { consoleClient } from '@/service/console'import {zToolApiEntity,zTriggerProviderApiEntity,@@ -18,8 +19,8 @@ import { createNuqsTestRenderer } from '@/test/nuqs-testing'import PluginDetailPanel from '../index'const api = vi.hoisted(() => ({- uninstall: vi.fn<typeof import('@/service/plugins').uninstallPlugin>(),- upgrade: vi.fn<typeof import('@/service/plugins').updateFromMarketPlace>(),+ uninstall: vi.fn<typeof consoleClient.workspaces.current.plugin.uninstall.post>(),+ upgrade: vi.fn<typeof consoleClient.workspaces.current.plugin.upgrade.marketplace.post>(),tools:vi.fn<typeof import('@/service/console').consoleClient.workspaces.current.toolProvider.builtin.byProvider.tools.get@@ -42,11 +43,6 @@ const api = vi.hoisted(() => ({}>>(),}))-vi.mock('@/service/plugins', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/plugins')>()),- uninstallPlugin: api.uninstall,- updateFromMarketPlace: api.upgrade,-}))vi.mock('@/service/base', async (importOriginal) => ({...(await importOriginal<typeof import('@/service/base')>()),get: api.credentials,@@ -58,10 +54,12 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.uninstall.post': api.uninstall,'workspaces.current.toolProviders.get': api.providers,'workspaces.current.toolProvider.builtin.byProvider.tools.get': api.tools,}),consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'workspaces.current.plugin.upgrade.marketplace.post': api.upgrade,'workspaces.current.toolProvider.builtin.byProvider.tools.get': api.tools,'workspaces.current.triggerProvider.byProvider.info.get': api.trigger,'workspaces.current.triggerProvider.byProvider.subscriptions.list.get': api.subscriptions,@@ -270,8 +268,10 @@ it('upgrades through the confirmation dialog and refreshes its consumer withoutawait user.click(within(dialog).getByRole('button', { name: 'plugin.upgrade.upgrade' }))expect(onUpdate).not.toHaveBeenCalled()expect(api.upgrade).toHaveBeenCalledWith({- original_plugin_unique_identifier: 'test-plugin-uid',- new_plugin_unique_identifier: 'new-plugin-uid',+ body: {+ original_plugin_unique_identifier: 'test-plugin-uid',+ new_plugin_unique_identifier: 'new-plugin-uid',+ },})await act(async () => pending.resolve({ all_installed: true, task_id: '' }))await waitFor(() => expect(dialog).not.toBeInTheDocument())@@ -306,7 +306,9 @@ it('requires confirmation before uninstalling, disables cancellation while pendiawait act(async () => pending.resolve({ success: true }))await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()- expect(api.uninstall).toHaveBeenCalledExactlyOnceWith('test-plugin-id')+ expect(api.uninstall).toHaveBeenCalledExactlyOnceWith({+ body: { plugin_installation_id: 'test-plugin-id', preserve_credentials: false },+ })expect(onUpdate).toHaveBeenCalledOnce()})diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsxindex 2b4379293b8..9a82c8a652f 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/__tests__/index.spec.tsx@@ -1,5 +1,5 @@+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'import type { ComponentProps, ReactElement } from 'react'-import type { VersionListResponse } from '@/app/components/plugins/types'import type { consoleClient } from '@/service/console'import {zPluginDecodeResponse,@@ -21,7 +21,8 @@ import DetailHeader from '../index'const api = vi.hoisted(() => ({releases: vi.fn<typeof fetch>(),- versions: vi.fn<() => Promise<{ data: VersionListResponse }>>(),+ uninstall: vi.fn<typeof consoleClient.workspaces.current.plugin.uninstall.post>(),+ versions: vi.fn<() => Promise<PluginVersionsResponse>>(),autoUpgrade: vi.fn<typeof consoleClient.workspaces.current.plugin.autoUpgrade.fetch.get>(),upload: vi.fn<typeof consoleClient.workspaces.current.plugin.upload.github.post>(),upgrade: vi.fn<typeof consoleClient.workspaces.current.plugin.upgrade.github.post>(),@@ -36,6 +37,8 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.uninstall.post': api.uninstall,+ 'workspaces.current.plugin.upgrade.marketplace.post': api.marketplaceUpgrade,'workspaces.current.models.modelTypes.byModelType.get': api.models,'workspaces.current.modelProviders.summary.get': async () => ({ data: [], plugins: {} }),'workspaces.current.plugin.list.installations.ids.post': async () => ({ plugins: [] }),@@ -54,10 +57,20 @@ vi.mock('@/service/console', async (importOriginal) => {}})-vi.mock('@/service/base', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/base')>()),- getMarketplace: api.versions,-}))+vi.mock('@/service/marketplace', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/marketplace')>()+ const { createTanstackQueryUtils } = await import('@orpc/tanstack-query')+ return {+ ...actual,+ marketplaceQuery: createTanstackQueryUtils(+ {+ ...actual.marketplaceClient,+ pluginVersions: api.versions,+ },+ { path: ['marketplace'] },+ ),+ }+})const autoUpgrade = {strategy_setting: 'disabled',@@ -120,6 +133,7 @@ beforeEach(() => {return Response.json({ releases })})vi.stubGlobal('fetch', api.releases)+ api.uninstall.mockReset().mockResolvedValue({ success: true })api.upload.mockReset().mockResolvedValue(uploadedPackage)api.upgrade.mockReset().mockResolvedValue({ all_installed: true, task_id: '' })api.marketplaceUpgrade.mockReset().mockResolvedValue({ all_installed: true, task_id: '' })@@ -259,8 +273,8 @@ it.each(['marketplace' in options ? options.marketplace : true,)await user.click(screen.getByRole('button', { name: '1.0.0' }))- await user.click(await screen.findByRole('button', { name: /^0\.5\.0/ }))- const dialog = await screen.findByRole('dialog', {+ await user.click(await screen.findByRole('menuitem', { name: /^0\.5\.0/ }))+ const dialog = await screen.findByRole(warning ? 'alertdialog' : 'dialog', {name: warning ? 'plugin.autoUpdate.pluginDowngradeWarning.title' : 'plugin.upgrade.title',})if (warning)@@ -295,14 +309,14 @@ it('uses the newly selected target after cancelling a downgrade', async () => {})const { user } = setup({ detail: { ...detail, source: PluginSource.marketplace } })await user.click(screen.getByRole('button', { name: '1.0.0' }))- await user.click(await screen.findByRole('button', { name: /^0\.5\.0/ }))- const downgrade = await screen.findByRole('dialog', {+ await user.click(await screen.findByRole('menuitem', { name: /^0\.5\.0/ }))+ const downgrade = await screen.findByRole('alertdialog', {name: 'plugin.autoUpdate.pluginDowngradeWarning.title',})await user.click(within(downgrade).getByRole('button', { name: 'app.newApp.Cancel' }))await waitFor(() => expect(downgrade).not.toBeInTheDocument())await user.click(screen.getByRole('button', { name: '1.0.0' }))- await user.click(await screen.findByRole('button', { name: /^2\.0\.0/ }))+ await user.click(await screen.findByRole('menuitem', { name: /^2\.0\.0/ }))const upgrade = await screen.findByRole('dialog', { name: 'plugin.upgrade.title' })expect(within(upgrade).queryByRole('button', {@@ -350,3 +364,52 @@ it('opens GitHub repository and package information from the real action menu',screen.getByRole('button', { name: 'plugin.detailPanel.operation.moreActions' }),).toBeEnabled()})++it('waits for the automatic update policy before exposing version actions', async () => {+ const policy = createDeferred<Awaited<ReturnType<typeof api.autoUpgrade>>>()+ api.autoUpgrade.mockReturnValueOnce(policy.promise)+ const { user } = setup({ detail: { ...detail, source: PluginSource.marketplace } })+ const trigger = await screen.findByRole('button', { name: '1.0.0' })+ await user.click(trigger)+ await waitFor(() => expect(api.versions).toHaveBeenCalledOnce())+ expect(screen.queryByRole('menu')).not.toBeInTheDocument()+ await act(async () =>+ policy.resolve({+ category: 'model',+ auto_upgrade: {+ ...autoUpgrade,+ include_plugins: [],+ exclude_plugins: [],+ strategy_setting: 'latest',+ },+ }),+ )+ await user.click(await screen.findByRole('menuitem', { name: /^0\.5\.0/ }))+ expect(+ await screen.findByRole('alertdialog', {+ name: 'plugin.autoUpdate.pluginDowngradeWarning.title',+ }),+ ).toHaveAccessibleDescription('plugin.autoUpdate.pluginDowngradeWarning.description')+})++it('restores the removal confirmation after a failed request and permits retry', async () => {+ const removal = createDeferred<Awaited<ReturnType<typeof api.uninstall>>>()+ api.uninstall.mockReturnValueOnce(removal.promise)+ const { user, onUpdate } = setup()+ await user.click(screen.getByRole('button', { name: 'plugin.detailPanel.operation.moreActions' }))+ await user.click(+ await screen.findByRole('menuitem', { name: 'plugin.detailPanel.operation.remove' }),+ )+ const dialog = await screen.findByRole('alertdialog', { name: 'plugin.action.delete' })+ const confirm = within(dialog).getByRole('button', { name: 'common.operation.confirm' })+ await user.click(confirm)+ await user.keyboard('{Escape}')+ expect(dialog).toBeInTheDocument()+ await act(async () => removal.reject(new Error('Removal failed')))+ await waitFor(() => expect(confirm).not.toHaveAttribute('aria-disabled'))+ expect(onUpdate).not.toHaveBeenCalled()+ await user.click(confirm)+ await waitFor(() => expect(onUpdate).toHaveBeenCalledExactlyOnceWith(true))+ await waitFor(() => expect(dialog).not.toBeInTheDocument())+ expect(api.uninstall).toHaveBeenCalledTimes(2)+})diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/components/header-modals.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/components/header-modals.tsxindex bc2541b10d7..27b1d54173b 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/components/header-modals.tsx+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/components/header-modals.tsx@@ -13,32 +13,31 @@ import {AlertDialogHeader,AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { useTranslation } from 'react-i18next'-import PluginInfo from '@/app/components/plugins/plugin-page/plugin-info'-import UpdateFromMarketplace from '@/app/components/plugins/update-plugin/from-market-place'+import PluginInfoContent from '@/app/components/plugins/plugin-page/plugin-info'+import MarketplaceUpdateDialog from '@/app/components/plugins/update-plugin/from-market-place'import { useGetLanguage } from '@/context/i18n'-import { PluginCategoryEnum, PluginSource } from '../../../types'+import { PluginSource } from '../../../types'const i18nPrefix = 'action'type HeaderModalsProps = {detail: PluginDetailmodalStates: ModalStates- targetVersion: VersionTarget- isDowngrade: boolean- isAutoUpgradeEnabled: boolean- onUpdatedFromMarketplace: () => void+ targetVersion: VersionTarget | undefined+ onUpdatedFromMarketplace: () => void | Promise<void>onDelete: () => void+ deleting: boolean}const HeaderModals: FC<HeaderModalsProps> = ({detail,modalStates,targetVersion,- isDowngrade,- isAutoUpgradeEnabled,onUpdatedFromMarketplace,onDelete,+ deleting,}) => {const { t } = useTranslation(['common', 'plugin'])const locale = useGetLanguage()@@ -54,24 +53,30 @@ const HeaderModals: FC<HeaderModalsProps> = ({hidePluginInfo,isShowDeleteConfirm,hideDeleteConfirm,- deleting,} = modalStatesreturn (<>- {isShowPluginInfo && (- <PluginInfo- repository={isFromGitHub ? meta?.repo : ''}- release={version}- packageName={meta?.package || ''}- onHide={hidePluginInfo}- />- )}+ <Dialog+ open={isShowPluginInfo}+ onOpenChange={(open) => {+ if (!open) hidePluginInfo()+ }}+ >+ <DialogContent className="w-120">+ <PluginInfoContent+ repository={isFromGitHub ? meta?.repo : ''}+ release={version}+ packageName={meta?.package || ''}+ />+ </DialogContent>+ </Dialog><AlertDialogopen={isShowDeleteConfirm}- onOpenChange={(open) => {- if (!open) hideDeleteConfirm()+ onOpenChange={(open, details) => {+ if (!open && deleting) details.cancel()+ else if (!open) hideDeleteConfirm()}}><AlertDialogContent backdropProps={{ forceRender: true }}>@@ -96,23 +101,24 @@ const HeaderModals: FC<HeaderModalsProps> = ({</AlertDialogContent></AlertDialog>- {isShowUpdateModal && (- <UpdateFromMarketplace- pluginId={detail.plugin_id}+ {targetVersion && (+ <MarketplaceUpdateDialog+ open={isShowUpdateModal}+ pluginId={targetVersion.plugin.plugin_id}payload={{- category: detail.declaration?.category ?? PluginCategoryEnum.tool,+ category: targetVersion.plugin.declaration.category,originalPackageInfo: {- id: detail.plugin_unique_identifier,- payload: detail.declaration ?? undefined,+ id: targetVersion.plugin.plugin_unique_identifier,+ payload: targetVersion.plugin.declaration,},targetPackageInfo: {- id: targetVersion.unique_identifier || '',- version: targetVersion.version || '',+ id: targetVersion.unique_identifier,+ version: targetVersion.version,},}}- onCancel={hideUpdateModal}- onSave={onUpdatedFromMarketplace}- isShowDowngradeWarningModal={isDowngrade && isAutoUpgradeEnabled}+ onRefresh={onUpdatedFromMarketplace}+ onClose={hideUpdateModal}+ warnAboutAutoUpdate={!!targetVersion.warnAboutAutoUpdate}/>)}</>diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.tsindex 8b23ec2492d..f3e7f4d14ca 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/use-detail-header-state.ts@@ -3,16 +3,17 @@import type { PluginDetail } from '../../../types'import { useSuspenseQuery } from '@tanstack/react-query'import { useBoolean } from 'ahooks'-import { useCallback, useMemo, useState } from 'react'+import { useMemo, useState } from 'react'import { systemFeaturesQueryOptions } from '@/features/system-features/client'-import useReferenceSetting from '../../../plugin-page/use-reference-setting'+import { usePluginAutoUpgradeSettings } from '@/service/use-plugins'import { AUTO_UPDATE_MODE } from '../../../reference-setting-modal/auto-update-setting/types'import { PluginCategoryEnum, PluginSource } from '../../../types'export type VersionTarget = {- version: string | undefined- unique_identifier: string | undefined- isDowngrade?: boolean+ plugin: PluginDetail+ version: string+ unique_identifier: string+ warnAboutAutoUpdate?: boolean}export type ModalStates = {@@ -25,18 +26,13 @@ export type ModalStates = {isShowDeleteConfirm: booleanshowDeleteConfirm: () => voidhideDeleteConfirm: () => void- deleting: boolean- showDeleting: () => void- hideDeleting: () => void}type VersionPickerState = {isShow: booleansetIsShow: (show: boolean) => void- targetVersion: VersionTarget+ targetVersion: VersionTarget | undefinedsetTargetVersion: (version: VersionTarget) => void- isDowngrade: boolean- setIsDowngrade: (downgrade: boolean) => void}type UseDetailHeaderStateReturn = {@@ -44,6 +40,7 @@ type UseDetailHeaderStateReturn = {versionPicker: VersionPickerStatehasNewVersion: booleanisAutoUpgradeEnabled: boolean+ autoUpgradeSettings: ReturnType<typeof usePluginAutoUpgradeSettings>isFromGitHub: booleanisFromMarketplace: boolean}@@ -54,18 +51,14 @@ export const useDetailHeaderState = (detail: PluginDetail): UseDetailHeaderStateselect: (s) => s.enable_marketplace,})const category = detail.declaration?.category ?? PluginCategoryEnum.tool- const { referenceSetting } = useReferenceSetting(category)+ const autoUpgradeSettings = usePluginAutoUpgradeSettings(category)- const { source, version, latest_version, latest_unique_identifier, plugin_id } = detail+ const { source, version, latest_version, plugin_id } = detailconst isFromGitHub = source === PluginSource.githubconst isFromMarketplace = source === PluginSource.marketplaceconst [isShow, setIsShow] = useState(false)- const [targetVersion, setTargetVersion] = useState<VersionTarget>({- version: latest_version,- unique_identifier: latest_unique_identifier,- })- const [isDowngrade, setIsDowngrade] = useState(false)+ const [targetVersion, setTargetVersion] = useState<VersionTarget>()const [isShowUpdateModal, { setTrue: showUpdateModal, setFalse: hideUpdateModal }] =useBoolean(false)@@ -73,14 +66,13 @@ export const useDetailHeaderState = (detail: PluginDetail): UseDetailHeaderStateuseBoolean(false)const [isShowDeleteConfirm, { setTrue: showDeleteConfirm, setFalse: hideDeleteConfirm }] =useBoolean(false)- const [deleting, { setTrue: showDeleting, setFalse: hideDeleting }] = useBoolean(false)const hasNewVersion = useMemo(() => {if (isFromMarketplace) return !!latest_version && latest_version !== versionreturn false}, [isFromMarketplace, latest_version, version])- const { auto_upgrade: autoUpgradeInfo } = referenceSetting || {}+ const { auto_upgrade: autoUpgradeInfo } = autoUpgradeSettings.data || {}const isAutoUpgradeEnabled = useMemo(() => {if (!enable_marketplace || !autoUpgradeInfo || !isFromMarketplace) return false@@ -99,11 +91,6 @@ export const useDetailHeaderState = (detail: PluginDetail): UseDetailHeaderStatereturn false}, [autoUpgradeInfo, plugin_id, isFromMarketplace, enable_marketplace])- const handleSetTargetVersion = useCallback((version: VersionTarget) => {- setTargetVersion(version)- if (version.isDowngrade !== undefined) setIsDowngrade(version.isDowngrade)- }, [])-return {modalStates: {isShowUpdateModal,@@ -115,20 +102,16 @@ export const useDetailHeaderState = (detail: PluginDetail): UseDetailHeaderStateisShowDeleteConfirm,showDeleteConfirm,hideDeleteConfirm,- deleting,- showDeleting,- hideDeleting,},versionPicker: {isShow,setIsShow,targetVersion,- setTargetVersion: handleSetTargetVersion,- isDowngrade,- setIsDowngrade,+ setTargetVersion,},hasNewVersion,isAutoUpgradeEnabled,+ autoUpgradeSettings,isFromGitHub,isFromMarketplace,}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.tsindex 63d121db479..e85be3a3ee1 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@@ -1,34 +1,30 @@'use client'import type { PluginDetail } from '../../../types'-import type { ModalStates, VersionTarget } from './use-detail-header-state'+import type { ModalStates } from './use-detail-header-state'+import { useMutation } from '@tanstack/react-query'import { useCallback } from 'react'import { trackEvent } from '@/app/components/base/amplitude'import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'-import { toast } from '@/app/notifications'import { useModalContext } from '@/context/modal-context'-import { uninstallPlugin } from '@/service/plugins'+import { consoleQuery } from '@/service/console'import { useInvalidateCheckInstalled } from '@/service/use-plugins'-import { checkForUpdates, fetchReleases } from '../../../install-plugin/hooks'import { PluginSource } from '../../../types'+import { checkGitHubPluginUpdate } from '../../../update-plugin/check-github-update'type UsePluginOperationsParams = {canDeletePlugin?: booleancanUpdatePlugin?: booleandetail: PluginDetailmodalStates: ModalStates- versionPicker: {- setTargetVersion: (version: VersionTarget) => void- setIsDowngrade: (downgrade: boolean) => void- }- isFromMarketplace: booleanonUpdate?: (isDelete?: boolean) => void | Promise<void>}type UsePluginOperationsReturn = {- handleUpdate: (isDowngrade?: boolean) => Promise<void>+ handleUpdate: () => Promise<void>handleUpdatedFromMarketplace: () => Promise<void>- handleDelete: () => Promise<void>+ handleDelete: () => void+ deleting: boolean}export const usePluginOperations = ({@@ -36,16 +32,15 @@ export const usePluginOperations = ({canUpdatePlugin = true,detail,modalStates,- versionPicker,- isFromMarketplace,onUpdate,}: UsePluginOperationsParams): UsePluginOperationsReturn => {const { setShowUpdatePluginModal } = useModalContext()const { refreshPluginList } = useRefreshPluginList()const invalidateCheckInstalled = useInvalidateCheckInstalled()- const { id, meta, plugin_id } = detail- const { author, category, name } = detail.declaration || detail+ const isFromMarketplace = detail.source === PluginSource.marketplace+ const { id, plugin_id } = detail+ const { category, name } = detail.declaration || detailconst handlePluginUpdated = useCallback(async (isDelete?: boolean) => {invalidateCheckInstalled()@@ -54,95 +49,44 @@ export const usePluginOperations = ({[invalidateCheckInstalled, onUpdate],)- const handleUpdate = useCallback(- async (isDowngrade?: boolean) => {- if (!canUpdatePlugin) return-- if (isFromMarketplace) {- versionPicker.setIsDowngrade(!!isDowngrade)- modalStates.showUpdateModal()- return- }-- if (!meta?.repo || !meta?.version || !meta?.package) {- toast.error('Missing plugin metadata for GitHub update')- return- }-- const owner = meta.repo.split('/')[0] || author- const repo = meta.repo.split('/')[1] || name- const fetchedReleases = await fetchReleases(owner, repo)- if (fetchedReleases.length === 0) return-- const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta.version)- toast(toastProps.message, { type: toastProps.type })-- if (needUpdate) {- setShowUpdatePluginModal({- onSaveCallback: () => handlePluginUpdated(),- payload: {- type: PluginSource.github,- category,- github: {- originalPackageInfo: {- id: detail.plugin_unique_identifier,- repo: meta.repo,- version: meta.version,- package: meta.package,- releases: fetchedReleases,- },- },- },- })- }- },- [- canUpdatePlugin,- isFromMarketplace,- meta,- author,- name,- setShowUpdatePluginModal,- detail,- handlePluginUpdated,- modalStates,- versionPicker,- ],- )-- const handleUpdatedFromMarketplace = useCallback(async () => {- await handlePluginUpdated()- modalStates.hideUpdateModal()- }, [handlePluginUpdated, modalStates])-- const handleDelete = useCallback(async () => {- if (!canDeletePlugin) return-- modalStates.showDeleting()- const res = await uninstallPlugin(id)- modalStates.hideDeleting()-- if (res.success) {- modalStates.hideDeleteConfirm()- handlePluginUpdated(true)- refreshPluginList({ category })+ const handleUpdate = useCallback(async () => {+ if (!canUpdatePlugin) return- trackEvent('plugin_uninstalled', { plugin_id, plugin_name: name })+ if (isFromMarketplace) {+ modalStates.showUpdateModal()+ return}++ await checkGitHubPluginUpdate(detail, setShowUpdatePluginModal, handlePluginUpdated)}, [- canDeletePlugin,- id,- category,- plugin_id,- name,- modalStates,+ canUpdatePlugin,+ isFromMarketplace,+ setShowUpdatePluginModal,+ detail,handlePluginUpdated,- refreshPluginList,+ modalStates,])+ const remove = useMutation(+ consoleQuery.workspaces.current.plugin.uninstall.post.mutationOptions({+ onSuccess: async (response) => {+ if (!response.success) return+ await handlePluginUpdated(true)+ refreshPluginList({ category })+ trackEvent('plugin_uninstalled', { plugin_id, plugin_name: name })+ modalStates.hideDeleteConfirm()+ },+ }),+ )+ const handleDelete = () => {+ if (!canDeletePlugin) return+ remove.mutate({ body: { plugin_installation_id: id, preserve_credentials: false } })+ }+return {handleUpdate,- handleUpdatedFromMarketplace,+ handleUpdatedFromMarketplace: handlePluginUpdated,handleDelete,+ deleting: remove.isPending,}}diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsxindex a95283c041a..21c8fb0f7c5 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/index.tsx@@ -1,12 +1,21 @@'use client'+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'import type { PluginDetail } from '../../types'import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuGroupLabel,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'import { IconButton } from '@langgenius/dify-ui/icon-button'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'-import { useQuery } from '@tanstack/react-query'-import { useCallback, useMemo } from 'react'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useCallback, useId, useMemo } from 'react'import { useTranslation } from 'react-i18next'import { useLocale } from '#i18n'import Badge from '@/app/components/base/badge'@@ -14,13 +23,15 @@ import { AuthCategory, PluginAuth } from '@/app/components/plugins/plugin-auth'import { OperationDropdown } from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'import { BUILTIN_TOOLS_ARRAY } from '@/app/components/plugins/readme-panel/constants'import { useReadmePanelStore } from '@/app/components/plugins/readme-panel/store'-import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'import { selectToolCollections } from '@/app/components/tools/utils/query-select'import { API_PREFIX } from '@/config'import { useGetLanguage } from '@/context/i18n'import { userProfileQueryOptions } from '@/features/account-profile/client'import useTheme from '@/hooks/use-theme'+import useTimestamp from '@/hooks/use-timestamp'import { consoleQuery } from '@/service/console'+import { marketplaceQuery } from '@/service/marketplace'+import { isEarlierThanVersion } from '@/utils/semver'import { getMarketplaceUrl } from '@/utils/var'import Verified from '../../base/badges/verified'import DeprecationNotice from '../../base/deprecation-notice'@@ -85,7 +96,10 @@ const DetailHeader = ({onHide,onUpdate,}: Props) => {- const { t } = useTranslation(['common', 'plugin'])+ const { t } = useTranslation(['common', 'plugin', 'appLog'])+ const versionMenuLabelId = useId()+ const { formatDate } = useTimestamp()+ const dateFormat = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]!const openReadmePanel = useReadmePanelStore((s) => s.openReadmePanel)const { data: timezone } = useQuery({...userProfileQueryOptions(),@@ -101,8 +115,6 @@ const DetailHeader = ({source,tenant_id,version,- latest_version,- latest_unique_identifier,meta,plugin_id,status,@@ -118,19 +130,33 @@ const DetailHeader = ({versionPicker,hasNewVersion,isAutoUpgradeEnabled,+ autoUpgradeSettings,isFromGitHub,isFromMarketplace,} = useDetailHeaderState(detail)- const { handleUpdate, handleUpdatedFromMarketplace, handleDelete } = usePluginOperations({- detail,- modalStates,- versionPicker,- isFromMarketplace,- canDeletePlugin,- canUpdatePlugin,- onUpdate,- })+ const { handleUpdate, handleUpdatedFromMarketplace, handleDelete, deleting } =+ usePluginOperations({+ detail,+ modalStates,+ canDeletePlugin,+ canUpdatePlugin,+ onUpdate,+ })++ const [organization, pluginName] = plugin_id.split('/')+ const versionsQuery = useQuery(+ marketplaceQuery.pluginVersions.queryOptions({+ input:+ organization && pluginName+ ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }+ : skipToken,+ enabled: versionPicker.isShow && canUpdatePlugin && isFromMarketplace && !isReadmeView,+ retry: false,+ }),+ )+ const loadingVersions =+ versionPicker.isShow && (versionsQuery.isPending || autoUpgradeSettings.isPending)const isTool = category === PluginCategoryEnum.toolconst providerBriefInfo = tool?.identity@@ -158,20 +184,23 @@ const DetailHeader = ({})}, [detail, openReadmePanel])- const handleVersionSelect = (state: {- version: string- unique_identifier: string- isDowngrade?: boolean- }) => {- versionPicker.setTargetVersion(state)- handleUpdate(state.isDowngrade)+ const handleVersionSelect = (item: PluginVersionsResponse['data']['versions'][number]) => {+ const isDowngrade = isEarlierThanVersion(item.version, detail.version)+ versionPicker.setTargetVersion({+ ...item,+ plugin: detail,+ warnAboutAutoUpdate: isDowngrade && isAutoUpgradeEnabled,+ })+ handleUpdate()}const handleTriggerLatestUpdate = () => {if (isFromMarketplace) {+ if (!detail.latest_version || !detail.latest_unique_identifier) returnversionPicker.setTargetVersion({- version: latest_version,- unique_identifier: latest_unique_identifier,+ plugin: detail,+ version: detail.latest_version,+ unique_identifier: detail.latest_unique_identifier,})}handleUpdate()@@ -208,39 +237,80 @@ const DetailHeader = ({)}{/* Version Picker */}- {!!version && (- <PluginVersionPicker- disabled={!canUpdatePlugin || !isFromMarketplace || isReadmeView}- isShow={versionPicker.isShow}- onShowChange={versionPicker.setIsShow}- pluginID={plugin_id}- currentVersion={version}- onSelect={handleVersionSelect}- trigger={(open) => (- <Badge- className={cn(- 'mx-1',- open && 'bg-state-base-hover',- (open || (canUpdatePlugin && isFromMarketplace)) &&- 'hover:bg-state-base-hover',- )}- uppercase={false}- text={- <>- <div>{isFromGitHub ? (meta?.version ?? version ?? '') : version}</div>- {canUpdatePlugin && isFromMarketplace && !isReadmeView && (- <span- aria-hidden- className="ml-1 i-ri-arrow-left-right-line size-3 text-text-tertiary"- />+ <DropdownMenu+ open={+ !!version &&+ versionPicker.isShow &&+ canUpdatePlugin &&+ isFromMarketplace &&+ !isReadmeView &&+ !loadingVersions+ }+ onOpenChange={versionPicker.setIsShow}+ >+ {!!version && (+ <DropdownMenuTrigger+ render={+ <Button+ variant="ghost"+ size="small"+ disabled={!canUpdatePlugin || !isFromMarketplace || isReadmeView}+ loading={loadingVersions}+ className="relative mx-1 h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.25 system-xs-medium text-text-tertiary"+ >+ {hasNewVersion && (+ <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-xs border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm" />+ )}+ <span>{isFromGitHub ? (meta?.version ?? version) : version}</span>+ {canUpdatePlugin &&+ isFromMarketplace &&+ !isReadmeView &&+ !loadingVersions && (+ <span aria-hidden className="i-ri-arrow-left-right-line size-3" />)}- </>- }- hasRedCornerMark={hasNewVersion}- />- )}- />- )}+ </Button>+ }+ />+ )}+ <DropdownMenuContent+ className="max-h-[min(16rem,var(--available-height))]"+ placement="bottom-start"+ aria-labelledby={versionMenuLabelId}+ >+ <DropdownMenuGroup>+ <DropdownMenuGroupLabel id={versionMenuLabelId}>+ {t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}+ </DropdownMenuGroupLabel>+ {versionsQuery.data && autoUpgradeSettings.data ? (+ versionsQuery.data.data.versions.map((item) => (+ <DropdownMenuItem+ key={item.unique_identifier}+ disabled={version === item.version}+ onClick={() => handleVersionSelect(item)}+ >+ <span>{item.version}</span>+ {version === item.version && (+ <Badge className="shrink-0" variant="dimm" text="CURRENT" />+ )}+ <span className="ms-auto text-text-tertiary">+ {formatDate(item.created_at, dateFormat)}+ </span>+ </DropdownMenuItem>+ ))+ ) : (+ <DropdownMenuItem+ closeOnClick={false}+ onClick={() => {+ if (versionsQuery.isError) void versionsQuery.refetch()+ if (autoUpgradeSettings.isError) void autoUpgradeSettings.refetch()+ }}+ >+ {t(($) => $['operation.retry'], { ns: 'common' })}+ </DropdownMenuItem>+ )}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu>{/* Auto Update Badge */}{isAutoUpgradeEnabled && !isReadmeView && (@@ -370,10 +440,9 @@ const DetailHeader = ({detail={detail}modalStates={modalStates}targetVersion={versionPicker.targetVersion}- isDowngrade={versionPicker.isDowngrade}- isAutoUpgradeEnabled={isAutoUpgradeEnabled}onUpdatedFromMarketplace={handleUpdatedFromMarketplace}onDelete={handleDelete}+ deleting={deleting}/></div>)diff --git a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsxindex 7728758caa3..b85cc07c65c 100644--- a/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx+++ b/web/app/components/plugins/plugin-item/__tests__/action.spec.tsx@@ -5,7 +5,6 @@ import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { expectLoadingButton } from '@/test/button'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createDeferred } from '@/test/deferred'-import { PluginSource } from '../../types'import Action from '../action'const requests = vi.hoisted(() => ({@@ -170,7 +169,6 @@ describe('installed plugin actions', () => {expect(requests.updateModal).toHaveBeenCalledWith({onSaveCallback: expect.any(Function),payload: {- type: PluginSource.github,category: 'tool',github: {originalPackageInfo: {diff --git a/web/app/components/plugins/plugin-item/action.tsx b/web/app/components/plugins/plugin-item/action.tsxindex 06f56805466..c3a46fb3bf0 100644--- a/web/app/components/plugins/plugin-item/action.tsx+++ b/web/app/components/plugins/plugin-item/action.tsx@@ -12,6 +12,7 @@ import {AlertDialogHeader,AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'+import { Dialog, DialogContent } from '@langgenius/dify-ui/dialog'import { IconButton } from '@langgenius/dify-ui/icon-button'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { useBoolean } from 'ahooks'@@ -23,8 +24,7 @@ import { useModalContext } from '@/context/modal-context'import { uninstallPlugin } from '@/service/plugins'import { useInvalidateInstalledPluginList } from '@/service/use-plugins'import { checkForUpdates, fetchReleases } from '../install-plugin/hooks'-import PluginInfo from '../plugin-page/plugin-info'-import { PluginSource } from '../types'+import PluginInfoContent from '../plugin-page/plugin-info'const i18nPrefix = 'action'@@ -73,7 +73,6 @@ const Action: FC<Props> = ({invalidateInstalledPluginList(category)},payload: {- type: PluginSource.github,category,github: {originalPackageInfo: {@@ -169,14 +168,20 @@ const Action: FC<Props> = ({</Tooltip>)}- {isShowPluginInfo && (- <PluginInfo- repository={meta!.repo}- release={meta!.version}- packageName={meta!.package}- onHide={hidePluginInfo}- />- )}+ <Dialog+ open={isShowPluginInfo}+ onOpenChange={(open) => {+ if (!open) hidePluginInfo()+ }}+ >+ <DialogContent className="w-120">+ <PluginInfoContent+ repository={meta?.repo}+ release={meta?.version}+ packageName={meta?.package}+ />+ </DialogContent>+ </Dialog><AlertDialog open={isShowDeleteConfirm} onOpenChange={(open) => !open && hideDeleteConfirm()}><AlertDialogContent backdropProps={{ forceRender: true }}><AlertDialogHeader>diff --git a/web/app/components/plugins/plugin-mutation-model/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-mutation-model/__tests__/index.spec.tsxdeleted file mode 100644index 9d034586ac5..00000000000--- a/web/app/components/plugins/plugin-mutation-model/__tests__/index.spec.tsx+++ /dev/null@@ -1,98 +0,0 @@-import type { ComponentProps } from 'react'-import type { Plugin } from '../../types'-import { screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { describe, expect, it, vi } from 'vite-plus/test'-import { expectLoadingButton } from '@/test/button'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'-import { PluginCategoryEnum } from '../../types'-import PluginMutationModal from '../index'--const createMockPlugin = (overrides?: Partial<Plugin>): Plugin => ({- type: 'plugin',- org: 'test-org',- name: 'test-plugin',- plugin_id: 'plugin-123',- version: '1.0.0',- latest_version: '1.0.0',- latest_package_identifier: 'test-org/test-plugin:1.0.0',- icon: '/test-icon.png',- verified: false,- label: { en_US: 'Test Plugin' },- brief: { en_US: 'Test plugin description' },- description: { en_US: 'Full test plugin description' },- introduction: 'Test plugin introduction',- repository: 'https://github.com/test/plugin',- category: PluginCategoryEnum.tool,- install_count: 1000,- endpoint: { settings: [] },- tags: [{ name: 'search' }],- badges: [],- verification: { authorized_category: 'community' },- from: 'marketplace',- ...overrides,-})--const props = (): ComponentProps<typeof PluginMutationModal> => ({- plugin: createMockPlugin(),- onCancel: vi.fn(),- mutation: { isSuccess: false, isPending: false },- mutate: vi.fn(),- confirmButtonText: 'Update',- cancelButtonText: 'Cancel',- modelTitle: <span>Update plugin</span>,- description: 'Install the selected version?',- cardTitleLeft: <span>v2.0.0</span>,- modalBottomLeft: <a href="https://example.com/release">Release notes</a>,-})--describe('PluginMutationModal', () => {- it('identifies the plugin and selected version before confirming the action', async () => {- const user = userEvent.setup()- const input = props()- render(<PluginMutationModal {...input} />)- expect(screen.getByRole('dialog', { name: 'Update plugin' })).toBeInTheDocument()- expect(screen.getByText('Install the selected version?')).toBeInTheDocument()- expect(screen.getByText('Test Plugin')).toBeInTheDocument()- expect(screen.getByText('Test plugin description')).toBeInTheDocument()- expect(screen.getByText('test-org')).toBeInTheDocument()- expect(screen.getByText('v2.0.0')).toBeInTheDocument()- expect(screen.getByRole('link', { name: 'Release notes' })).toHaveAttribute(- 'href',- 'https://example.com/release',- )- await user.click(screen.getByRole('button', { name: 'Update' }))- expect(input.mutate).toHaveBeenCalledOnce()- expect(input.onCancel).not.toHaveBeenCalled()- })-- it.each(['Cancel', 'common.operation.close', 'Escape'])(- 'dismisses with %s without mutating the plugin',- async (action) => {- const user = userEvent.setup()- const input = props()- render(<PluginMutationModal {...input} />)- if (action === 'Escape') await user.keyboard('{Escape}')- else await user.click(screen.getByRole('button', { name: action }))- expect(input.onCancel).toHaveBeenCalledOnce()- expect(input.mutate).not.toHaveBeenCalled()- },- )-- it('blocks repeated confirmation while pending and restores actions after it settles', async () => {- const user = userEvent.setup()- const input = props()- const { rerender } = render(- <PluginMutationModal {...input} mutation={{ isSuccess: false, isPending: true }} />,- )- const confirm = screen.getByRole('button', { name: 'Update' })- expectLoadingButton(confirm)- expect(screen.queryByRole('button', { name: 'Cancel' })).not.toBeInTheDocument()- await user.click(confirm)- expect(input.mutate).not.toHaveBeenCalled()- rerender(<PluginMutationModal {...input} />)- expect(screen.getByRole('button', { name: 'Cancel' })).toBeEnabled()- await user.click(screen.getByRole('button', { name: 'Update' }))- expect(input.mutate).toHaveBeenCalledOnce()- })-})diff --git a/web/app/components/plugins/plugin-mutation-model/index.tsx b/web/app/components/plugins/plugin-mutation-model/index.tsxdeleted file mode 100644index 29327568611..00000000000--- a/web/app/components/plugins/plugin-mutation-model/index.tsx+++ /dev/null@@ -1,83 +0,0 @@-import type { UseMutationResult } from '@tanstack/react-query'-import type { FC, ReactNode } from 'react'-import type { Plugin } from '../types'-import { Button } from '@langgenius/dify-ui/button'-import {- Dialog,- DialogBody,- DialogContent,- DialogFooter,- DialogHeader,- DialogHeaderCloseButton,- DialogTitle,-} from '@langgenius/dify-ui/dialog'-import * as React from 'react'-import { memo } from 'react'-import { useTranslation } from 'react-i18next'-import Card from '@/app/components/plugins/card'--type Props = Readonly<{- plugin: Plugin- onCancel: () => void- mutation: Pick<UseMutationResult, 'isSuccess' | 'isPending'>- mutate: () => void- confirmButtonText: ReactNode- cancelButtonText: ReactNode- modelTitle: ReactNode- description: ReactNode- cardTitleLeft: ReactNode- modalBottomLeft?: ReactNode-}>--const PluginMutationModal: FC<Props> = ({- plugin,- onCancel,- mutation,- confirmButtonText,- cancelButtonText,- modelTitle,- description,- cardTitleLeft,- mutate,- modalBottomLeft,-}: Props) => {- const { t } = useTranslation(['common'])-- return (- <Dialog- open- onOpenChange={(open) => {- if (!open) onCancel()- }}- >- <DialogContent className="w-140">- <DialogHeader>- <DialogTitle>{modelTitle}</DialogTitle>- <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />- </DialogHeader>- <DialogBody>- <div className="mb-2 system-md-regular text-text-secondary">{description}</div>- <div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">- <Card- installed={mutation.isSuccess}- payload={plugin}- className="w-full"- titleLeft={cardTitleLeft}- />- </div>- </DialogBody>- <DialogFooter>- <div className="me-auto">{modalBottomLeft}</div>- {!mutation.isPending && <Button onClick={onCancel}>{cancelButtonText}</Button>}- <Button variant="primary" loading={mutation.isPending} onClick={mutate}>- {confirmButtonText}- </Button>- </DialogFooter>- </DialogContent>- </Dialog>- )-}--PluginMutationModal.displayName = 'PluginMutationModal'--export default memo(PluginMutationModal)diff --git a/web/app/components/plugins/plugin-page/plugin-info.tsx b/web/app/components/plugins/plugin-page/plugin-info.tsxindex 260ee9a449c..6fa42c6c406 100644--- a/web/app/components/plugins/plugin-page/plugin-info.tsx+++ b/web/app/components/plugins/plugin-page/plugin-info.tsx@@ -1,9 +1,7 @@'use client'import type { FC } from 'react'import {- Dialog,DialogBody,- DialogContent,DialogHeader,DialogHeaderCloseButton,DialogTitle,@@ -18,50 +16,42 @@ type Props = Readonly<{repository?: stringrelease?: stringpackageName?: string- onHide: () => void}>-const PlugInfo: FC<Props> = ({ repository, release, packageName, onHide }) => {+const PluginInfoContent: FC<Props> = ({ repository, release, packageName }) => {const { t } = useTranslation(['common', 'plugin'])const labelWidthClassName = 'w-[96px]'return (- <Dialog- open- onOpenChange={(open) => {- if (!open) onHide()- }}- >- <DialogContent className="w-120">- <DialogHeader>- <DialogTitle>{t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}</DialogTitle>- <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />- </DialogHeader>- <DialogBody className="space-y-3">- {repository && (- <KeyValueItem- label={t(($) => $[`${i18nPrefix}.repository`], { ns: 'plugin' })}- labelWidthClassName={labelWidthClassName}- value={`${convertRepoToUrl(repository)}`}- valueMaxWidthClassName="max-w-[190px]"- />- )}- {release && (- <KeyValueItem- label={t(($) => $[`${i18nPrefix}.release`], { ns: 'plugin' })}- labelWidthClassName={labelWidthClassName}- value={release}- />- )}- {packageName && (- <KeyValueItem- label={t(($) => $[`${i18nPrefix}.packageName`], { ns: 'plugin' })}- labelWidthClassName={labelWidthClassName}- value={packageName}- />- )}- </DialogBody>- </DialogContent>- </Dialog>+ <>+ <DialogHeader>+ <DialogTitle>{t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}</DialogTitle>+ <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />+ </DialogHeader>+ <DialogBody className="space-y-3">+ {repository && (+ <KeyValueItem+ label={t(($) => $[`${i18nPrefix}.repository`], { ns: 'plugin' })}+ labelWidthClassName={labelWidthClassName}+ value={`${convertRepoToUrl(repository)}`}+ valueMaxWidthClassName="max-w-[190px]"+ />+ )}+ {release && (+ <KeyValueItem+ label={t(($) => $[`${i18nPrefix}.release`], { ns: 'plugin' })}+ labelWidthClassName={labelWidthClassName}+ value={release}+ />+ )}+ {packageName && (+ <KeyValueItem+ label={t(($) => $[`${i18nPrefix}.packageName`], { ns: 'plugin' })}+ labelWidthClassName={labelWidthClassName}+ value={packageName}+ />+ )}+ </DialogBody>+ </>)}-export default React.memo(PlugInfo)+export default React.memo(PluginInfoContent)diff --git a/web/app/components/plugins/types.ts b/web/app/components/plugins/types.tsindex 93f4b70440b..35ded886671 100644--- a/web/app/components/plugins/types.ts+++ b/web/app/components/plugins/types.ts@@ -293,15 +293,8 @@ export type UpdateFromGitHubPayload = {}export type UpdatePluginPayload = {- type: PluginSourcecategory: PluginCategoryEnum- marketPlace?: UpdateFromMarketPlacePayload- github?: UpdateFromGitHubPayload-}--export type UpdatePluginModalType = UpdatePluginPayload & {- onCancel: () => void- onSave: () => void | Promise<void>+ github: UpdateFromGitHubPayload}export const InstallStepFromGitHub = {@@ -411,20 +404,6 @@ export type PackageDependency = {export type Dependency = GitHubItemAndMarketPlaceDependency | PackageDependency-type Version = {- plugin_org: string- plugin_name: string- version: string- file_name: string- checksum: string- created_at: string- unique_identifier: string-}--export type VersionListResponse = {- versions: Version[]-}-export type VersionInfo = {installedId: string // use to uninstallinstalledVersion: stringdiff --git a/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx b/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsxindex 625d363acf9..bb64417f7f1 100644--- a/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx+++ b/web/app/components/plugins/update-plugin/__tests__/from-market-place.spec.tsx@@ -7,16 +7,14 @@ import { PluginCategoryEnum, TaskStatus } from '@/app/components/plugins/types'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import { createDeferred } from '@/test/deferred'import { createPluginDeclarationFixture } from '@/test/fixtures/plugin'-import UpdateFromMarketplace from '../from-market-place'+import MarketplaceUpdateDialog from '../from-market-place'const {- mockCheck,mockHandleInstallTaskStart,mockRemoveAutoUpgrade,mockUpdateFromMarketPlace,mockToastError,} = vi.hoisted(() => ({- mockCheck: vi.fn(),mockHandleInstallTaskStart: vi.fn(),mockRemoveAutoUpgrade: vi.fn(),mockUpdateFromMarketPlace: vi.fn(),@@ -36,11 +34,6 @@ vi.mock('@/app/notifications', () => ({},}))-vi.mock('@/service/plugins', () => ({- updateFromMarketPlace: mockUpdateFromMarketPlace,- checkTaskStatus: mockCheck,-}))-vi.mock('@/service/use-plugins', async (importOriginal) => ({...(await importOriginal<typeof import('@/service/use-plugins')>()),usePluginTaskList: () => ({@@ -71,7 +64,9 @@ vi.mock('@/service/console', async (importOriginal) => {const { withConsoleClientResponses } = await import('@/test/console/service-responses')return {...actual,+consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'workspaces.current.plugin.upgrade.marketplace.post': mockUpdateFromMarketPlace,'workspaces.current.plugin.autoUpgrade.exclude.post': (...args: unknown[]) =>mockRemoveAutoUpgrade(...args),}),@@ -81,9 +76,6 @@ vi.mock('@/service/console', async (importOriginal) => {describe('UpdateFromMarketplace', () => {beforeEach(() => {vi.resetAllMocks()- mockCheck.mockResolvedValue({- task: { plugins: [{ plugin_unique_identifier: '[email protected]', status: TaskStatus.success }] },- })mockUpdateFromMarketPlace.mockResolvedValue({all_installed: true,task_id: 'task-1',@@ -118,14 +110,21 @@ describe('UpdateFromMarketplace', () => {}mockUpdateFromMarketPlace.mockResolvedValueOnce(failedResponse)- render(<UpdateFromMarketplace payload={createPayload()} onSave={onSave} onCancel={vi.fn()} />)+ render(+ <MarketplaceUpdateDialog+ open+ onClose={vi.fn()}+ payload={createPayload()}+ onRefresh={onSave}+ pluginId="plugin-1"+ />,+ )await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))await waitFor(() => {expect(mockToastError).toHaveBeenCalledWith('upgrade failed')})- expect(mockCheck).not.toHaveBeenCalled()expect(mockHandleInstallTaskStart).not.toHaveBeenCalled()expect(onSave).not.toHaveBeenCalled()await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))@@ -137,13 +136,17 @@ describe('UpdateFromMarketplace', () => {const exclusion = createDeferred<object>()mockRemoveAutoUpgrade.mockReturnValueOnce(exclusion.promise)const onSave = vi.fn()+ const onClose = vi.fn()+ const upgrade = createDeferred<PluginInstallTaskStartResponse>()+ mockUpdateFromMarketPlace.mockReturnValueOnce(upgrade.promise)render(- <UpdateFromMarketplace+ <MarketplaceUpdateDialog+ open+ onClose={onClose}payload={createPayload({ targetPackageInfo: { id: '[email protected]', version: '0.9.0' } })}pluginId="plugin-1"- onSave={onSave}- onCancel={vi.fn()}- isShowDowngradeWarningModal+ onRefresh={onSave}+ warnAboutAutoUpdate/>,)@@ -160,25 +163,41 @@ describe('UpdateFromMarketplace', () => {})})expect(mockUpdateFromMarketPlace).not.toHaveBeenCalled()+ expect(screen.getByRole('alertdialog')).toHaveAccessibleDescription(+ 'plugin.autoUpdate.pluginDowngradeWarning.description',+ )+ await user.keyboard('{Escape}')+ expect(onClose).not.toHaveBeenCalled()+ expect(screen.getByRole('button', { name: 'app.newApp.Cancel' })).toBeDisabled()await act(async () => exclusion.resolve({}))+ await waitFor(() => expect(mockUpdateFromMarketPlace).toHaveBeenCalledOnce())+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ await user.keyboard('{Escape}')+ expect(onClose).not.toHaveBeenCalled()+ await act(async () => upgrade.resolve({ all_installed: true, task_id: '' }))await waitFor(() => expect(onSave).toHaveBeenCalledOnce())+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce())expect(mockUpdateFromMarketPlace).toHaveBeenCalledWith({- original_plugin_unique_identifier: '[email protected]',- new_plugin_unique_identifier: '[email protected]',+ body: {+ original_plugin_unique_identifier: '[email protected]',+ new_plugin_unique_identifier: '[email protected]',+ },})})it('downgrades without excluding future automatic upgrades when that action is chosen', async () => {const user = userEvent.setup()const onSave = vi.fn()render(- <UpdateFromMarketplace+ <MarketplaceUpdateDialog+ open+ onClose={vi.fn()}payload={createPayload({ targetPackageInfo: { id: '[email protected]', version: '0.9.0' } })}pluginId="plugin-1"- onSave={onSave}- onCancel={vi.fn()}- isShowDowngradeWarningModal+ onRefresh={onSave}+ warnAboutAutoUpdate/>,)@@ -187,53 +206,60 @@ describe('UpdateFromMarketplace', () => {)await waitFor(() => expect(onSave).toHaveBeenCalledOnce())expect(mockUpdateFromMarketPlace).toHaveBeenCalledExactlyOnceWith({- original_plugin_unique_identifier: '[email protected]',- new_plugin_unique_identifier: '[email protected]',+ body: {+ original_plugin_unique_identifier: '[email protected]',+ new_plugin_unique_identifier: '[email protected]',+ },})expect(mockRemoveAutoUpgrade).not.toHaveBeenCalled()})- it('waits for the upgrade task before reporting success and prevents duplicate submissions', async () => {+ it('hands an accepted installation to background tasks and closes without claiming completion', async () => {const user = userEvent.setup()- const pending = createDeferred<{- task: { plugins: { plugin_unique_identifier: string; status: TaskStatus }[] }- }>()+ const pending = createDeferred<PluginInstallTaskStartResponse>()+ mockUpdateFromMarketPlace.mockReturnValueOnce(pending.promise)+ const onRefresh = vi.fn()+ const onClose = vi.fn()+ render(+ <MarketplaceUpdateDialog+ open+ payload={createPayload()}+ pluginId="plugin-1"+ onRefresh={onRefresh}+ onClose={onClose}+ warnAboutAutoUpdate+ />,+ )+ const submit = screen.getByRole('button', {+ name: 'plugin.autoUpdate.pluginDowngradeWarning.downgrade',+ })+ await user.click(submit)+ await user.click(submit)+ expect(mockUpdateFromMarketPlace).toHaveBeenCalledOnce()+ expect(onClose).not.toHaveBeenCalled()const response: PluginInstallTaskStartResponse = {all_installed: false,task_id: 'upgrade-task',}- mockUpdateFromMarketPlace.mockResolvedValueOnce(response)- mockCheck.mockReturnValueOnce(pending.promise)- const onSave = vi.fn()- render(<UpdateFromMarketplace payload={createPayload()} onSave={onSave} onCancel={vi.fn()} />)-- await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))- await waitFor(() => expect(mockCheck).toHaveBeenCalledExactlyOnceWith('upgrade-task'))- const upgrading = screen.getByRole('button', { name: 'plugin.upgrade.upgrading' })- expect(upgrading).toHaveAttribute('aria-disabled', 'true')- expect(- screen.queryByRole('button', { name: 'common.operation.cancel' }),- ).not.toBeInTheDocument()- await user.click(upgrading)- expect(mockUpdateFromMarketPlace).toHaveBeenCalledOnce()+ await act(async () => pending.resolve(response))+ await waitFor(() => expect(onClose).toHaveBeenCalledOnce())expect(mockHandleInstallTaskStart).toHaveBeenCalledExactlyOnceWith(response)- expect(onSave).not.toHaveBeenCalled()-- await act(async () =>- pending.resolve({- task: {- plugins: [{ plugin_unique_identifier: '[email protected]', status: TaskStatus.success }],- },- }),- )- await waitFor(() => expect(onSave).toHaveBeenCalledOnce())+ expect(onRefresh).not.toHaveBeenCalled()})it('allows retrying after an upgrade request rejects', async () => {const user = userEvent.setup()mockUpdateFromMarketPlace.mockRejectedValueOnce(new Error('Upgrade request failed'))const onSave = vi.fn()- render(<UpdateFromMarketplace payload={createPayload()} onSave={onSave} onCancel={vi.fn()} />)+ render(+ <MarketplaceUpdateDialog+ open+ onClose={vi.fn()}+ payload={createPayload()}+ onRefresh={onSave}+ pluginId="plugin-1"+ />,+ )await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))expect(onSave).not.toHaveBeenCalled()@@ -241,58 +267,4 @@ describe('UpdateFromMarketplace', () => {await waitFor(() => expect(onSave).toHaveBeenCalledOnce())expect(mockUpdateFromMarketPlace).toHaveBeenCalledTimes(2)})-- it('shows a task failure and restores the upgrade action for retry', async () => {- const user = userEvent.setup()- mockUpdateFromMarketPlace.mockResolvedValueOnce({- all_installed: false,- task_id: 'failed-task',- })- mockCheck.mockResolvedValueOnce({- task: {- plugins: [- {- plugin_unique_identifier: '[email protected]',- status: TaskStatus.failed,- message: 'Dependency conflict',- },- ],- },- })- const onSave = vi.fn()- render(<UpdateFromMarketplace payload={createPayload()} onSave={onSave} onCancel={vi.fn()} />)-- await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))- await waitFor(() => expect(mockToastError).toHaveBeenCalledWith('Dependency conflict'))- expect(onSave).not.toHaveBeenCalled()- expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeEnabled()- await user.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))- await waitFor(() => expect(onSave).toHaveBeenCalledOnce())- })-- it.each([- { warning: false, button: 'common.operation.cancel' },- { warning: true, button: 'app.newApp.Cancel' },- { warning: false, button: 'common.operation.close' },- { warning: true, button: 'common.operation.close' },- ])(- 'cancels via $button before any update or exclusion request (warning=$warning)',- async ({ warning, button }) => {- const user = userEvent.setup()- const onCancel = vi.fn()- render(- <UpdateFromMarketplace- payload={createPayload()}- pluginId="plugin-1"- onSave={vi.fn()}- onCancel={onCancel}- isShowDowngradeWarningModal={warning}- />,- )- await user.click(screen.getByRole('button', { name: button }))- expect(onCancel).toHaveBeenCalledOnce()- expect(mockUpdateFromMarketPlace).not.toHaveBeenCalled()- expect(mockRemoveAutoUpgrade).not.toHaveBeenCalled()- },- )})diff --git a/web/app/components/plugins/update-plugin/__tests__/plugin-version-picker.spec.tsx b/web/app/components/plugins/update-plugin/__tests__/plugin-version-picker.spec.tsxdeleted file mode 100644index ef4687daf1e..00000000000--- a/web/app/components/plugins/update-plugin/__tests__/plugin-version-picker.spec.tsx+++ /dev/null@@ -1,118 +0,0 @@-import type { VersionListResponse } from '../../types'-import { act, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { useState } from 'react'-import { renderWithConsoleQuery as render } from '@/test/console/query-data'-import { createDeferred } from '@/test/deferred'-import PluginVersionPicker from '../plugin-version-picker'--const { getVersions } = vi.hoisted(() => ({ getVersions: vi.fn() }))-vi.mock('@/service/base', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/base')>()),- getMarketplace: getVersions,-}))-vi.mock('@/hooks/use-timestamp', () => ({- default: () => ({ formatDate: (value: string) => value }),-}))--const response: { data: VersionListResponse } = {- data: {- versions: ['2.0.0', '1.0.0'].map((version) => ({- plugin_org: 'test',- plugin_name: 'plugin',- version,- file_name: 'plugin.difypkg',- checksum: `checksum-${version}`,- created_at: '2024-01-02T00:00:00Z',- unique_identifier: `test/plugin:${version}`,- })),- },-}--const Picker = ({- disabled = false,- currentVersion = '2.0.0',- onSelect = vi.fn(),-}: {- disabled?: boolean- currentVersion?: string- onSelect?: (selection: {- version: string- unique_identifier: string- isDowngrade: boolean- }) => void-}) => {- const [open, setOpen] = useState(false)- return (- <PluginVersionPicker- disabled={disabled}- isShow={open}- onShowChange={setOpen}- pluginID="test/plugin"- currentVersion={currentVersion}- trigger={(isOpen) => <span>{isOpen ? 'Close versions' : 'Select version'}</span>}- onSelect={onSelect}- />- )-}--beforeEach(() => {- vi.resetAllMocks()- getVersions.mockResolvedValue(response)-})--it('fetches versions only after opening and replaces loading with the current-version marker', async () => {- const user = userEvent.setup()- const pending = createDeferred<typeof response>()- getVersions.mockReturnValueOnce(pending.promise)- render(<Picker />)- expect(getVersions).not.toHaveBeenCalled()- await user.click(screen.getByRole('button', { name: 'Select version' }))-- expect(await screen.findByRole('status', { name: 'common.loading' })).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'Close versions' })).toBeInTheDocument()- expect(getVersions).toHaveBeenCalledExactlyOnceWith('/plugins/test/plugin/versions', {- params: { page: 1, page_size: 100 },- })- await act(async () => pending.resolve(response))- expect(await screen.findByRole('button', { name: /2\.0\.0.*CURRENT/ })).toBeDisabled()- expect(screen.queryByRole('status', { name: 'common.loading' })).not.toBeInTheDocument()-})--it.each([- { currentVersion: '2.0.0', selectedVersion: '1.0.0', isDowngrade: true },- { currentVersion: '1.0.0', selectedVersion: '2.0.0', isDowngrade: false },-])(- 'selects $selectedVersion from $currentVersion and closes the picker',- async ({ currentVersion, selectedVersion, isDowngrade }) => {- const user = userEvent.setup()- const onSelect = vi.fn()- render(<Picker currentVersion={currentVersion} onSelect={onSelect} />)- await user.click(screen.getByRole('button', { name: 'Select version' }))- await user.click(- await screen.findByRole('button', {- name: new RegExp(selectedVersion.replaceAll('.', '\\.')),- }),- )-- expect(onSelect).toHaveBeenCalledExactlyOnceWith({- version: selectedVersion,- unique_identifier: `test/plugin:${selectedVersion}`,- isDowngrade,- })- await waitFor(() =>- expect(screen.queryByRole('button', { name: /CURRENT/ })).not.toBeInTheDocument(),- )- expect(screen.getByRole('button', { name: 'Select version' })).toBeInTheDocument()- },-)--it('does not open or request versions while disabled', async () => {- const user = userEvent.setup()- render(<Picker disabled />)- const trigger = screen.getByRole('button', { name: 'Select version' })- expect(trigger).toBeDisabled()- await user.click(trigger)- expect(getVersions).not.toHaveBeenCalled()- expect(screen.queryByText('plugin.detailPanel.switchVersion')).not.toBeInTheDocument()-})diff --git a/web/app/components/plugins/update-plugin/check-github-update.ts b/web/app/components/plugins/update-plugin/check-github-update.tsnew file mode 100644index 00000000000..17600f74919--- /dev/null+++ b/web/app/components/plugins/update-plugin/check-github-update.ts@@ -0,0 +1,43 @@+import type { PluginDetail } from '../types'+import type { useModalContext } from '@/context/modal-context'+import { toast } from '@/app/notifications'+import { checkForUpdates, fetchReleases } from '../install-plugin/hooks'++export async function checkGitHubPluginUpdate(+ detail: PluginDetail,+ showUpdateModal: ReturnType<typeof useModalContext>['setShowUpdatePluginModal'],+ onUpdated: () => void | Promise<void>,+) {+ const { meta } = detail+ const { author, category, name } = detail.declaration || detail+ if (!meta?.repo || !meta?.version || !meta?.package) {+ toast.error('Missing plugin metadata for GitHub update')+ return+ }++ const owner = meta.repo.split('/')[0] || author+ const repo = meta.repo.split('/')[1] || name+ const fetchedReleases = await fetchReleases(owner, repo)+ if (fetchedReleases.length === 0) return++ const { needUpdate, toastProps } = checkForUpdates(fetchedReleases, meta.version)+ toast(toastProps.message, { type: toastProps.type })++ if (needUpdate) {+ showUpdateModal({+ onSaveCallback: () => onUpdated(),+ payload: {+ category,+ github: {+ originalPackageInfo: {+ id: detail.plugin_unique_identifier,+ repo: meta.repo,+ version: meta.version,+ package: meta.package,+ releases: fetchedReleases,+ },+ },+ },+ })+ }+}diff --git a/web/app/components/plugins/update-plugin/downgrade-warning.tsx b/web/app/components/plugins/update-plugin/downgrade-warning.tsxindex ceb9abefeb3..8f899885a8e 100644--- a/web/app/components/plugins/update-plugin/downgrade-warning.tsx+++ b/web/app/components/plugins/update-plugin/downgrade-warning.tsx@@ -1,47 +1,62 @@-import { Button } from '@langgenius/dify-ui/button'import {- DialogFooter,- DialogHeader,- DialogHeaderCloseButton,- DialogTitle,-} from '@langgenius/dify-ui/dialog'+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogDescription,+ AlertDialogFooter,+ AlertDialogHeader,+ AlertDialogTitle,+} from '@langgenius/dify-ui/alert-dialog'import { useTranslation } from 'react-i18next'const i18nPrefix = 'autoUpdate.pluginDowngradeWarning'type Props = Readonly<{- onCancel: () => void+ excluding: boolean+ downgrading: booleanonJustDowngrade: () => voidonExcludeAndDowngrade: () => void}>-const DowngradeWarningModal = ({ onCancel, onJustDowngrade, onExcludeAndDowngrade }: Props) => {+const DowngradeWarningContent = ({+ excluding,+ downgrading,+ onJustDowngrade,+ onExcludeAndDowngrade,+}: Props) => {const { t } = useTranslation(['app', 'plugin', 'common'])return (<>- <DialogHeader- // oxlint-disable-next-line shadcn/no-restyle -- Preserve the warning's 8px title-to-description gap.- className="pb-2"- >- <DialogTitle>{t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}</DialogTitle>- <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />- </DialogHeader>- <div className="px-6 pb-4 system-md-regular text-text-secondary">- {t(($) => $[`${i18nPrefix}.description`], { ns: 'plugin' })}- </div>- <DialogFooter>- <Button variant="secondary" onClick={() => onCancel()}>+ <AlertDialogHeader>+ <AlertDialogTitle>{t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}</AlertDialogTitle>+ <AlertDialogDescription>+ {t(($) => $[`${i18nPrefix}.description`], { ns: 'plugin' })}+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogCancelButton disabled={excluding || downgrading}>{t(($) => $['newApp.Cancel'], { ns: 'app' })}- </Button>- <Button variant="secondary" tone="destructive" onClick={onJustDowngrade}>+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton+ variant="secondary"+ tone="destructive"+ disabled={excluding}+ loading={downgrading}+ onClick={onJustDowngrade}+ >{t(($) => $[`${i18nPrefix}.downgrade`], { ns: 'plugin' })}- </Button>- <Button variant="primary" onClick={onExcludeAndDowngrade}>+ </AlertDialogConfirmButton>+ <AlertDialogConfirmButton+ variant="primary"+ tone="default"+ disabled={downgrading}+ loading={excluding}+ onClick={onExcludeAndDowngrade}+ >{t(($) => $[`${i18nPrefix}.exclude`], { ns: 'plugin' })}- </Button>- </DialogFooter>+ </AlertDialogConfirmButton>+ </AlertDialogFooter></>)}-export default DowngradeWarningModal+export default DowngradeWarningContentdiff --git a/web/app/components/plugins/update-plugin/from-github.tsx b/web/app/components/plugins/update-plugin/from-github.tsxdeleted file mode 100644index e6f00cdfa8c..00000000000--- a/web/app/components/plugins/update-plugin/from-github.tsx+++ /dev/null@@ -1,16 +0,0 @@-'use client'-import type { FC } from 'react'-import type { UpdateFromGitHubPayload } from '../types'-import * as React from 'react'-import InstallFromGitHub from '../install-plugin/install-from-github'--type Props = Readonly<{- payload: UpdateFromGitHubPayload- onSave: () => void | Promise<void>- onCancel: () => void-}>--const FromGitHub: FC<Props> = ({ payload, onSave, onCancel }) => {- return <InstallFromGitHub updatePayload={payload} onClose={onCancel} onSuccess={onSave} />-}-export default React.memo(FromGitHub)diff --git a/web/app/components/plugins/update-plugin/from-market-place.tsx b/web/app/components/plugins/update-plugin/from-market-place.tsxindex d958dd52533..509a71d5534 100644--- a/web/app/components/plugins/update-plugin/from-market-place.tsx+++ b/web/app/components/plugins/update-plugin/from-market-place.tsx@@ -1,226 +1,191 @@'use client'import type { UpdateFromMarketPlacePayload } from '../types'+import { AlertDialog, AlertDialogContent } from '@langgenius/dify-ui/alert-dialog'import { Button } from '@langgenius/dify-ui/button'-import { cn } from '@langgenius/dify-ui/cn'import {Dialog,DialogBody,+ DialogClose,DialogContent,DialogFooter,DialogHeader,DialogHeaderCloseButton,DialogTitle,} from '@langgenius/dify-ui/dialog'+import { useIsMutating, useMutation } from '@tanstack/react-query'import * as React from 'react'-import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'import Badge from '@/app/components/base/badge/index'import Card from '@/app/components/plugins/card'-import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-task-status'import { pluginManifestToCardPluginProps } from '@/app/components/plugins/install-plugin/utils'import { toast } from '@/app/notifications'-import { updateFromMarketPlace } from '@/service/plugins'+import { consoleClient } from '@/service/console'import { usePluginTaskList, useRemoveAutoUpgrade } from '@/service/use-plugins'import useGetIcon from '../install-plugin/base/use-get-icon'import { TaskStatus } from '../types'-import DowngradeWarningModal from './downgrade-warning'+import DowngradeWarningContent from './downgrade-warning'const i18nPrefix = 'upgrade'type Props = Readonly<{payload: UpdateFromMarketPlacePayload- pluginId?: string- onSave: () => void | Promise<void>- onCancel: () => void- isShowDowngradeWarningModal?: boolean+ pluginId: string+ onRefresh: () => void | Promise<void>+ onSuccess: () => void+ warnAboutAutoUpdate?: boolean}>-type FailedUpgradeResponse = {- task?: {- status?: TaskStatus- plugins?: Array<{- plugin_unique_identifier: string- message: string- }>- }-}--const UploadStep = {- notStarted: 'notStarted',- upgrading: 'upgrading',- installed: 'installed',-} as const--type UploadStep = (typeof UploadStep)[keyof typeof UploadStep]+const updateMutationKey = (payload: UpdateFromMarketPlacePayload) => [+ 'plugin-marketplace-update',+ payload.originalPackageInfo.id,+ payload.targetPackageInfo.id,+]-const UpdatePluginModal = ({+const UpdateFromMarketplaceContent = ({payload,pluginId,- onSave,- onCancel,- isShowDowngradeWarningModal,+ onRefresh,+ onSuccess,+ warnAboutAutoUpdate,}: Props) => {const { originalPackageInfo, targetPackageInfo } = payloadconst { t } = useTranslation(['common', 'plugin'])const upgradeButtonLabelId = React.useId()const { getIconUrl } = useGetIcon()- const [icon, setIcon] = useState<string>(originalPackageInfo.payload.icon)- useEffect(() => {- ;(async () => {- const icon = await getIconUrl(originalPackageInfo.payload.icon)- setIcon(icon)- })()- }, [originalPackageInfo, getIconUrl])- const { check, stop } = checkTaskStatus()- const handleCancel = () => {- stop()- onCancel()- }+ const icon = getIconUrl(originalPackageInfo.payload.icon)- const [uploadStep, setUploadStep] = useState<UploadStep>(UploadStep.notStarted)const { handleInstallTaskStart } = usePluginTaskList(payload.category)-- const configBtnText = {- [UploadStep.notStarted]: t(($) => $[`${i18nPrefix}.upgrade`], { ns: 'plugin' }),- [UploadStep.upgrading]: t(($) => $[`${i18nPrefix}.upgrading`], { ns: 'plugin' }),- [UploadStep.installed]: t(($) => $[`${i18nPrefix}.close`], { ns: 'plugin' }),- }[uploadStep]-- const handleConfirm = useCallback(async () => {- if (uploadStep === UploadStep.notStarted) {- setUploadStep(UploadStep.upgrading)- try {- const response = (await updateFromMarketPlace({+ const exclude = useRemoveAutoUpgrade()+ const upgrade = useMutation({+ mutationKey: updateMutationKey(payload),+ // Keep exclusion and task creation in one submission. The task list owns installation progress.+ mutationFn: async (excludeFromAutoUpdate: boolean) => {+ if (excludeFromAutoUpdate)+ await exclude.mutateAsync({ plugin_id: pluginId, category: payload.category })+ const response = await consoleClient.workspaces.current.plugin.upgrade.marketplace.post({+ body: {original_plugin_unique_identifier: originalPackageInfo.id,new_plugin_unique_identifier: targetPackageInfo.id,- })) as Awaited<ReturnType<typeof updateFromMarketPlace>> & FailedUpgradeResponse-- if (response.task?.status === TaskStatus.failed) {- const failedPlugin =- response.task.plugins?.find(- (plugin) => plugin.plugin_unique_identifier === targetPackageInfo.id,- ) ?? response.task.plugins?.[0]- toast.error(failedPlugin?.message || t(($) => $.error, { ns: 'common' }))- setUploadStep(UploadStep.notStarted)- return- }-- const { all_installed: isInstalled, task_id: taskId } = response-- if (isInstalled) {- await onSave()- return- }- handleInstallTaskStart(response)- const { status, error } = await check({- taskId,- pluginUniqueIdentifier: targetPackageInfo.id,- })- if (status === TaskStatus.failed) {- toast.error(error!)- setUploadStep(UploadStep.notStarted)- return- }- await onSave()- } catch {- setUploadStep(UploadStep.notStarted)+ },+ })+ if (response.task?.status === TaskStatus.failed) {+ const failedPlugin =+ response.task.plugins?.find(+ (plugin) => plugin.plugin_unique_identifier === targetPackageInfo.id,+ ) ?? response.task.plugins?.[0]+ const message = failedPlugin?.message || t(($) => $.error, { ns: 'common' })+ toast.error(message)+ throw new Error(message)}- return- }- if (uploadStep === UploadStep.installed) onSave()- }, [- onSave,- uploadStep,- check,- originalPackageInfo.id,- handleInstallTaskStart,- t,- targetPackageInfo.id,- ])+ return response+ },+ onSuccess: async (response) => {+ if (response.all_installed) await onRefresh()+ else handleInstallTaskStart(response)+ },+ })+ const handleConfirm = () => upgrade.mutate(false, { onSuccess })+ const handleExcludeAndDowngrade = () => upgrade.mutate(true, { onSuccess })+ const configBtnText = upgrade.isPending+ ? t(($) => $['upgrade.upgrading'], { ns: 'plugin' })+ : t(($) => $['upgrade.upgrade'], { ns: 'plugin' })- const { mutateAsync } = useRemoveAutoUpgrade()- const handleExcludeAndDownload = async () => {- if (pluginId) {- await mutateAsync({- plugin_id: pluginId,- category: payload.category,- })- }- handleConfirm()- }- const doShowDowngradeWarningModal =- isShowDowngradeWarningModal && uploadStep === UploadStep.notStarted+ return (+ <>+ {warnAboutAutoUpdate && (+ <DowngradeWarningContent+ onJustDowngrade={handleConfirm}+ onExcludeAndDowngrade={handleExcludeAndDowngrade}+ excluding={upgrade.isPending && upgrade.variables === true}+ downgrading={upgrade.isPending && upgrade.variables === false}+ />+ )}+ {!warnAboutAutoUpdate && (+ <>+ <DialogHeader>+ <DialogTitle>{t(($) => $[`${i18nPrefix}.title`], { ns: 'plugin' })}</DialogTitle>+ <DialogHeaderCloseButton+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}+ />+ </DialogHeader>+ <DialogBody>+ <div className="mb-2 system-md-regular text-text-secondary">+ {t(($) => $[`${i18nPrefix}.description`], { ns: 'plugin' })}+ </div>+ <div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">+ <Card+ installed={upgrade.isSuccess}+ payload={pluginManifestToCardPluginProps({+ ...originalPackageInfo.payload,+ icon,+ })}+ className="w-full"+ titleLeft={+ <>+ <Badge className="mx-1" size="s" variant="warning">+ {`${originalPackageInfo.payload.version} -> ${targetPackageInfo.version}`}+ </Badge>+ </>+ }+ />+ </div>+ </DialogBody>+ <DialogFooter>+ {!upgrade.isPending && (+ <DialogClose render={<Button />}>+ {t(($) => $['operation.cancel'], { ns: 'common' })}+ </DialogClose>+ )}+ <Button+ variant="primary"+ loading={upgrade.isPending}+ onClick={handleConfirm}+ aria-labelledby={upgradeButtonLabelId}+ >+ <span id={upgradeButtonLabelId}>{configBtnText}</span>+ </Button>+ </DialogFooter>+ </>+ )}+ </>+ )+}+type MarketplaceUpdateDialogProps = Omit<Props, 'onSuccess' | 'warnAboutAutoUpdate'> & {+ open: boolean+ onClose: () => void+ warnAboutAutoUpdate?: boolean+}+export default function MarketplaceUpdateDialog({+ open,+ onClose,+ warnAboutAutoUpdate = false,+ ...session+}: MarketplaceUpdateDialogProps) {+ const pending = useIsMutating({ mutationKey: updateMutationKey(session.payload) }) > 0return (- <Dialog open onOpenChange={() => onCancel()}>- <DialogContent- backdropProps={{ forceRender: true }}- className={cn('min-w-140', doShowDowngradeWarningModal && 'min-w-160')}+ <>+ <Dialog+ open={open && !warnAboutAutoUpdate}+ onOpenChange={(nextOpen) => {+ if (!nextOpen) onClose()+ }}>- {doShowDowngradeWarningModal && (- <DowngradeWarningModal- onCancel={onCancel}- onJustDowngrade={handleConfirm}- onExcludeAndDowngrade={handleExcludeAndDownload}- />- )}- {!doShowDowngradeWarningModal && (- <>- <DialogHeader>- <DialogTitle>- {t(- ($) =>- $[- `${i18nPrefix}.${uploadStep === UploadStep.installed ? 'successfulTitle' : 'title'}`- ],- { ns: 'plugin' },- )}- </DialogTitle>- <DialogHeaderCloseButton- aria-label={t(($) => $['operation.close'], { ns: 'common' })}- />- </DialogHeader>- <DialogBody>- <div className="mb-2 system-md-regular text-text-secondary">- {t(($) => $[`${i18nPrefix}.description`], { ns: 'plugin' })}- </div>- <div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">- <Card- installed={uploadStep === UploadStep.installed}- payload={pluginManifestToCardPluginProps({- ...originalPackageInfo.payload,- icon: icon!,- })}- className="w-full"- titleLeft={- <>- <Badge className="mx-1" size="s" variant="warning">- {`${originalPackageInfo.payload.version} -> ${targetPackageInfo.version}`}- </Badge>- </>- }- />- </div>- </DialogBody>- <DialogFooter>- {uploadStep === UploadStep.notStarted && (- <Button onClick={handleCancel}>- {t(($) => $['operation.cancel'], { ns: 'common' })}- </Button>- )}- <Button- variant="primary"- loading={uploadStep === UploadStep.upgrading}- onClick={handleConfirm}- aria-labelledby={upgradeButtonLabelId}- >- <span id={upgradeButtonLabelId}>{configBtnText}</span>- </Button>- </DialogFooter>- </>- )}- </DialogContent>- </Dialog>+ <DialogContent className="w-140" backdropProps={{ forceRender: true }}>+ <UpdateFromMarketplaceContent {...session} onSuccess={onClose} />+ </DialogContent>+ </Dialog>+ <AlertDialog+ open={open && warnAboutAutoUpdate}+ onOpenChange={(nextOpen, details) => {+ if (!nextOpen && pending) details.cancel()+ else if (!nextOpen) onClose()+ }}+ >+ <AlertDialogContent className="w-160" backdropProps={{ forceRender: true }}>+ <UpdateFromMarketplaceContent {...session} warnAboutAutoUpdate onSuccess={onClose} />+ </AlertDialogContent>+ </AlertDialog>+ </>)}-export default React.memo(UpdatePluginModal)diff --git a/web/app/components/plugins/update-plugin/index.tsx b/web/app/components/plugins/update-plugin/index.tsxdeleted file mode 100644index 82c7d5ddcd5..00000000000--- a/web/app/components/plugins/update-plugin/index.tsx+++ /dev/null@@ -1,21 +0,0 @@-'use client'-import type { FC } from 'react'-import type { UpdatePluginModalType } from '../types'-import * as React from 'react'-import { PluginSource } from '../types'-import UpdateFromGitHub from './from-github'-import UpdateFromMarketplace from './from-market-place'--const UpdatePlugin: FC<UpdatePluginModalType> = ({- type,- marketPlace,- github,- onCancel,- onSave,-}) => {- if (type === PluginSource.github) {- return <UpdateFromGitHub payload={github!} onSave={onSave} onCancel={onCancel} />- }- return <UpdateFromMarketplace payload={marketPlace!} onSave={onSave} onCancel={onCancel} />-}-export default React.memo(UpdatePlugin)diff --git a/web/app/components/plugins/update-plugin/plugin-version-picker.tsx b/web/app/components/plugins/update-plugin/plugin-version-picker.tsxdeleted file mode 100644index bb3a03a6e7e..00000000000--- a/web/app/components/plugins/update-plugin/plugin-version-picker.tsx+++ /dev/null@@ -1,153 +0,0 @@-'use client'-import type { PopoverContentProps } from '@langgenius/dify-ui/popover'-import type { FC } from 'react'-import { cn } from '@langgenius/dify-ui/cn'-import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import * as React from 'react'-import { useCallback } from 'react'-import { useTranslation } from 'react-i18next'-import Badge from '@/app/components/base/badge'-import useTimestamp from '@/hooks/use-timestamp'-import { useVersionListOfPlugin } from '@/service/use-plugins'-import { isEarlierThanVersion } from '@/utils/semver'--type Props = Readonly<- Pick<PopoverContentProps, 'sideOffset' | 'alignOffset'> & {- disabled?: boolean- isShow: boolean- onShowChange: (isShow: boolean) => void- pluginID: string- currentVersion: string- trigger: (open: boolean) => React.ReactNode- triggerAccessibleName?: string- onSelect: ({- version,- unique_identifier,- isDowngrade,- }: {- version: string- unique_identifier: string- isDowngrade: boolean- }) => void- }->--const PluginVersionPicker: FC<Props> = ({- disabled = false,- isShow,- onShowChange,- pluginID,- currentVersion,- trigger,- triggerAccessibleName,- sideOffset = 4,- alignOffset = 0,- onSelect,-}) => {- const { t } = useTranslation(['appLog', 'common', 'plugin'])- const format = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]- const { formatDate } = useTimestamp()-- const { data: res, isLoading } = useVersionListOfPlugin(pluginID, isShow && !disabled)-- const handleSelect = useCallback(- ({- version,- unique_identifier,- isDowngrade,- }: {- version: string- unique_identifier: string- isDowngrade: boolean- }) => {- if (currentVersion === version) return- onSelect({ version, unique_identifier, isDowngrade })- onShowChange(false)- },- [currentVersion, onSelect, onShowChange],- )-- return (- <Popover- open={isShow}- onOpenChange={(open) => {- if (!disabled) onShowChange(open)- }}- >- <PopoverTrigger- disabled={disabled}- render={(props, state) => (- <button- {...props}- type="button"- aria-label={triggerAccessibleName}- className={cn(- 'inline-flex cursor-pointer items-center data-disabled:cursor-default',- props.className,- )}- >- {trigger(state.open)}- </button>- )}- />-- <PopoverContent- placement="bottom-start"- sideOffset={sideOffset}- alignOffset={alignOffset}- className="relative w-52.25 bg-components-panel-bg-blur p-1 backdrop-blur-[5px]"- >- <div className="px-3 pt-1 pb-0.5 system-xs-medium-uppercase text-text-tertiary">- {t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}- </div>- <div className="relative max-h-56 overflow-y-auto">- {isLoading ? (- <div- role="status"- aria-label={t(($) => $.loading, { ns: 'common' })}- className="flex h-12 items-center justify-center"- >- <span- aria-hidden- className="i-ri-loader-2-line size-4 animate-spin text-text-tertiary"- />- </div>- ) : (- res?.data.versions.map((version) => (- <button- key={version.unique_identifier}- type="button"- disabled={currentVersion === version.version}- className={cn(- 'flex w-full cursor-pointer items-center rounded-lg border-0 px-2 py-1 text-left outline-hidden hover:bg-state-base-hover focus-visible:ring-2 focus-visible:ring-state-accent-solid disabled:cursor-default disabled:hover:bg-transparent',- currentVersion === version.version && 'cursor-default opacity-30',- )}- onClick={() =>- handleSelect({- version: version.version,- unique_identifier: version.unique_identifier,- isDowngrade: isEarlierThanVersion(version.version, currentVersion),- })- }- >- <div className="flex min-h-5 min-w-0 grow items-center gap-1 px-1">- <div className="min-w-0 grow truncate system-sm-medium text-text-secondary">- {version.version}- </div>- {currentVersion === version.version && (- <Badge className="shrink-0" variant="dimm" text="CURRENT" />- )}- <div className="shrink-0 system-xs-regular text-text-tertiary">- {formatDate(version.created_at, format!)}- </div>- </div>- </button>- ))- )}- </div>- </PopoverContent>- </Popover>- )-}--export default React.memo(PluginVersionPicker)diff --git a/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsx b/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsxnew file mode 100644index 00000000000..ed04af0a6f6--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/__tests__/switch-plugin-version.spec.tsx@@ -0,0 +1,97 @@+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'+import type { consoleClient } from '@/service/console'+import { act, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { expectLoadingButton } from '@/test/button'+import { renderWithConsoleQuery } from '@/test/console/query-data'+import { createDeferred } from '@/test/deferred'+import { createPluginEntity } from '@/test/fixtures/plugin'+import { SwitchPluginVersion } from '../switch-plugin-version'++const api = vi.hoisted(() => ({+ detail: vi.fn<typeof consoleClient.workspaces.current.plugin.list.installations.ids.post>(),+ upgrade: vi.fn<typeof consoleClient.workspaces.current.plugin.upgrade.marketplace.post>(),+ versions: vi.fn<() => Promise<PluginVersionsResponse>>(),+}))+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleResponses, withConsoleClientResponses } =+ await import('@/test/console/service-responses')+ return {+ ...actual,+ consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'workspaces.current.plugin.list.installations.ids.post': api.detail,+ }),+ consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'workspaces.current.plugin.upgrade.marketplace.post': api.upgrade,+ }),+ }+})+vi.mock('@/service/marketplace', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/marketplace')>()+ const { createTanstackQueryUtils } = await import('@orpc/tanstack-query')+ return {+ ...actual,+ marketplaceQuery: createTanstackQueryUtils(+ { ...actual.marketplaceClient, pluginVersions: api.versions },+ { path: ['marketplace'] },+ ),+ }+})+const installed = createPluginEntity()+const identifier = (version: string) => `langgenius/plugin-entity:${version}@test`+beforeEach(() => {+ api.detail.mockReset().mockResolvedValue({ plugins: [installed] })+ api.upgrade.mockReset().mockResolvedValue({ all_installed: true, task_id: '' })+ api.versions.mockReset().mockResolvedValue({+ data: {+ versions: ['2.0.0', '1.0.0', '0.5.0'].map((version) => ({+ plugin_org: 'langgenius',+ plugin_name: 'plugin-entity',+ version,+ file_name: 'plugin.difypkg',+ checksum: version,+ created_at: '2026-06-01T00:00:00Z',+ unique_identifier: identifier(version),+ })),+ },+ })+})+function setup() {+ const onChange = vi.fn()+ renderWithConsoleQuery(+ <SwitchPluginVersion+ uniqueIdentifier={installed.plugin_unique_identifier}+ tooltip="Switch to a compatible version"+ onChange={onChange}+ />,+ {+ workspacePermissionKeys: ['plugin.install'],+ },+ )+ return { user: userEvent.setup(), onChange }+}+it('submits the selected package once and reports the version only after success', async () => {+ const result = createDeferred<Awaited<ReturnType<typeof api.upgrade>>>()+ api.upgrade.mockReturnValueOnce(result.promise)+ const { user, onChange } = setup()+ await user.click(await screen.findByRole('button', { name: /switchVersion 1\.0\.0/ }))+ await user.click(await screen.findByRole('menuitem', { name: /^2\.0\.0/ }))+ const dialog = await screen.findByRole('dialog')+ const confirm = within(dialog).getByRole('button', {+ name: 'workflowAgent.nodes.agent.installPlugin.install',+ })+ await user.click(confirm)+ expectLoadingButton(confirm)+ await user.click(confirm)+ expect(api.upgrade).toHaveBeenCalledExactlyOnceWith({+ body: {+ original_plugin_unique_identifier: installed.plugin_unique_identifier,+ new_plugin_unique_identifier: identifier('2.0.0'),+ },+ })+ expect(onChange).not.toHaveBeenCalled()+ await act(async () => result.resolve({ all_installed: true, task_id: '' }))+ await waitFor(() => expect(dialog).not.toBeInTheDocument())+ expect(onChange).toHaveBeenCalledExactlyOnceWith('2.0.0')+})diff --git a/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx b/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsxindex 8fd0995597f..aabda4e7042 100644--- a/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx+++ b/web/app/components/workflow/nodes/_base/components/switch-plugin-version.tsx@@ -1,21 +1,53 @@'use client'+import type { PluginVersionsResponse } from '@dify/contracts/marketplace'import type { FC, ReactNode } from 'react'+import type { PluginDetail } from '@/app/components/plugins/types'+import { Button } from '@langgenius/dify-ui/button'import { cn } from '@langgenius/dify-ui/cn'-import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'-import { useCallback, useState } from 'react'+import {+ Dialog,+ DialogBody,+ DialogClose,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogHeaderCloseButton,+ DialogTitle,+} from '@langgenius/dify-ui/dialog'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuGroupLabel,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@langgenius/dify-ui/dropdown-menu'+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'+import { skipToken, useQuery } from '@tanstack/react-query'+import { useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Badge from '@/app/components/base/badge'import { Badge as Badge2 } from '@/app/components/base/badge/index'+import Card from '@/app/components/plugins/card'import useGetIcon from '@/app/components/plugins/install-plugin/base/use-get-icon'import useWorkspacePluginInstallPermission from '@/app/components/plugins/install-plugin/hooks/use-workspace-plugin-install-permission'import { pluginManifestToCardPluginProps } from '@/app/components/plugins/install-plugin/utils'-import PluginMutationModel from '@/app/components/plugins/plugin-mutation-model'-import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'+import useTimestamp from '@/hooks/use-timestamp'import Link from '@/next/link'-import { useCheckInstalled, useUpdatePackageFromMarketPlace } from '@/service/use-plugins'+import { consoleQuery } from '@/service/console'+import { marketplaceQuery } from '@/service/marketplace'+import {+ normalizeInstalledPluginDetail,+ useUpdatePackageFromMarketPlace,+} from '@/service/use-plugins'import { getMarketplaceUrl } from '@/utils/var'+type PluginVersionSelection = {+ plugin: PluginDetail+ target: Pick<PluginVersionsResponse['data']['versions'][number], 'version' | 'unique_identifier'>+}+type SwitchPluginVersionProps = {uniqueIdentifier: stringtooltip?: ReactNode@@ -26,142 +58,213 @@ type SwitchPluginVersionProps = {export const SwitchPluginVersion: FC<SwitchPluginVersionProps> = (props) => {const { uniqueIdentifier, tooltip, onChange, className } = props- const [pluginId] = uniqueIdentifier?.split(':') || ['']- const [isShow, setIsShow] = useState(false)- const [isShowUpdateModal, setIsShowUpdateModal] = useState(false)- const [target, setTarget] = useState<{- version: string- pluginUniqueIden: string- }>()+ const [pluginId] = uniqueIdentifier.split(':')+ const triggerRef = useRef<HTMLButtonElement>(null)+ const [requestedOpen, setRequestedOpen] = useState(false)+ const [installOpen, setInstallOpen] = useState(false)+ const [selection, setSelection] = useState<PluginVersionSelection>()const { canUpdatePlugin } = useWorkspacePluginInstallPermission()- const pluginDetails = useCheckInstalled({- pluginIds: [pluginId!],- enabled: true,- })- const pluginDetail = pluginDetails.data?.plugins.at(0)+ const pluginDetails = useQuery(+ consoleQuery.workspaces.current.plugin.list.installations.ids.post.queryOptions({+ input: pluginId ? { body: { plugin_ids: [pluginId] } } : skipToken,+ enabled: canUpdatePlugin,+ staleTime: 0,+ select: (response) =>+ response.plugins[0] ? normalizeInstalledPluginDetail(response.plugins[0]) : undefined,+ }),+ )+ const pluginDetail = pluginDetails.data- const handleUpdatedFromMarketplace = useCallback(() => {- setIsShowUpdateModal(false)- pluginDetails.refetch()- onChange?.(target!.version)- }, [onChange, pluginDetails, target])- const { getIconUrl } = useGetIcon()- const icon = pluginDetail?.declaration.icon- ? getIconUrl(pluginDetail.declaration.icon)- : undefined- const mutation = useUpdatePackageFromMarketPlace()- const install = () => {- mutation.mutate(- {- new_plugin_unique_identifier: target!.pluginUniqueIden,- original_plugin_unique_identifier: uniqueIdentifier,- },- {- onSuccess() {- handleUpdatedFromMarketplace()- },- },- )- }- const { t } = useTranslation(['workflowAgent'])+ const { t } = useTranslation(['workflowAgent', 'plugin', 'common', 'appLog'])+ const versionMenuLabelId = useId()+ const { formatDate } = useTimestamp()+ const dateFormat = t(($) => $.dateTimeFormat, { ns: 'appLog' }).split(' ')[0]!- // Guard against null/undefined uniqueIdentifier to prevent app crash- if (!uniqueIdentifier || !pluginId || !canUpdatePlugin) return null+ const [organization, pluginName] = pluginId?.split('/') ?? []+ const versionsQuery = useQuery(+ marketplaceQuery.pluginVersions.queryOptions({+ input:+ organization && pluginName+ ? { params: { organization, pluginName }, query: { page: 1, page_size: 100 } }+ : skipToken,+ enabled: requestedOpen && canUpdatePlugin,+ retry: false,+ }),+ )+ const loadingVersions = requestedOpen && versionsQuery.isPending- const content = (+ return (<divclassName={cn('flex w-fit items-center justify-center', className)}onClick={(e) => e.stopPropagation()}>- {isShowUpdateModal && pluginDetail && (- <PluginMutationModel- onCancel={() => setIsShowUpdateModal(false)}- plugin={pluginManifestToCardPluginProps({- ...pluginDetail.declaration,- icon: icon!,- })}- mutation={mutation}- mutate={install}- confirmButtonText={t(($) => $['nodes.agent.installPlugin.install'], {- ns: 'workflowAgent',- })}- cancelButtonText={t(($) => $['nodes.agent.installPlugin.cancel'], {- ns: 'workflowAgent',- })}- modelTitle={t(($) => $['nodes.agent.installPlugin.title'], { ns: 'workflowAgent' })}- description={t(($) => $['nodes.agent.installPlugin.desc'], { ns: 'workflowAgent' })}- cardTitleLeft={- <>- <Badge2 className="mx-1" size="s" variant="warning">- {`${pluginDetail.version} -> ${target!.version}`}- </Badge2>- </>- }- modalBottomLeft={- <Link- className="flex items-center justify-center gap-1"- href={getMarketplaceUrl(- `/plugins/${pluginDetail.declaration.author}/${pluginDetail.declaration.name}`,- )}- target="_blank"- rel="noopener noreferrer"- >- <span className="system-xs-regular text-xs text-text-accent">- {t(($) => $['nodes.agent.installPlugin.changelog'], { ns: 'workflowAgent' })}- </span>- <span className="i-ri-external-link-line size-3 text-text-accent" />- </Link>- }- />- )}- {pluginDetail && (- <PluginVersionPicker- isShow={isShow}- onShowChange={setIsShow}- pluginID={pluginId}- currentVersion={pluginDetail.version}- onSelect={(state) => {- setTarget({- pluginUniqueIden: state.unique_identifier,- version: state.version,- })- setIsShowUpdateModal(true)- }}- trigger={(open) => (- <Badge- className={cn('mx-1 flex hover:bg-state-base-hover', open && 'bg-state-base-hover')}- uppercase={true}- text={- <>- <div>{pluginDetail.version}</div>- <span className="ml-1 i-ri-arrow-left-right-line size-3 text-text-tertiary" />- </>- }- hasRedCornerMark={true}+ <Dialog open={installOpen} onOpenChange={setInstallOpen}>+ <DialogContent className="w-140" finalFocus={triggerRef}>+ {selection && (+ <PluginVersionInstallConfirmation+ selection={selection}+ onInstalled={(version) => {+ void pluginDetails.refetch()+ onChange?.(version)+ setInstallOpen(false)+ }}/>)}- />- )}+ </DialogContent>+ </Dialog>+ <DropdownMenu+ open={requestedOpen && !!pluginDetail && canUpdatePlugin && !loadingVersions}+ onOpenChange={setRequestedOpen}+ >+ {pluginDetail && canUpdatePlugin && (+ <Tooltip disabled={!tooltip || requestedOpen}>+ <TooltipTrigger+ render={+ <DropdownMenuTrigger+ ref={triggerRef}+ render={+ <Button+ variant="ghost"+ size="small"+ loading={loadingVersions}+ className="relative mx-1 h-5 overflow-visible rounded-[5px] border border-divider-deep px-1.25 system-2xs-medium-uppercase text-text-tertiary"+ >+ <span className="absolute -top-0.5 -right-0.5 size-1.5 rounded-xs border border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg shadow-sm" />+ <span className="sr-only">+ {t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}{' '}+ </span>+ <span>{pluginDetail.version}</span>+ {!loadingVersions && (+ <span aria-hidden className="i-ri-arrow-left-right-line size-3" />+ )}+ </Button>+ }+ />+ }+ />+ <TooltipContent>{tooltip}</TooltipContent>+ </Tooltip>+ )}+ <DropdownMenuContent+ className="max-h-[min(16rem,var(--available-height))]"+ placement="bottom-start"+ aria-labelledby={versionMenuLabelId}+ >+ <DropdownMenuGroup>+ <DropdownMenuGroupLabel id={versionMenuLabelId}>+ {t(($) => $['detailPanel.switchVersion'], { ns: 'plugin' })}+ </DropdownMenuGroupLabel>+ {versionsQuery.data && pluginDetail ? (+ versionsQuery.data.data.versions.map((item) => (+ <DropdownMenuItem+ key={item.unique_identifier}+ disabled={pluginDetail.version === item.version}+ onClick={() => {+ setSelection({ plugin: pluginDetail, target: item })+ setInstallOpen(true)+ }}+ >+ <span>{item.version}</span>+ {pluginDetail.version === item.version && (+ <Badge className="shrink-0" variant="dimm" text="CURRENT" />+ )}+ <span className="ms-auto text-text-tertiary">+ {formatDate(item.created_at, dateFormat)}+ </span>+ </DropdownMenuItem>+ ))+ ) : (+ <DropdownMenuItem closeOnClick={false} onClick={() => void versionsQuery.refetch()}>+ {t(($) => $['operation.retry'], { ns: 'common' })}+ </DropdownMenuItem>+ )}+ </DropdownMenuGroup>+ </DropdownMenuContent>+ </DropdownMenu></div>)+}- if (!tooltip || isShow || isShowUpdateModal) return content-+function PluginVersionInstallConfirmation({+ selection,+ onInstalled,+}: {+ selection: PluginVersionSelection+ onInstalled: (version: PluginVersionSelection['target']['version']) => void+}) {+ const { t } = useTranslation(['workflowAgent', 'common'])+ const { canUpdatePlugin } = useWorkspacePluginInstallPermission()+ const { getIconUrl } = useGetIcon()+ const mutation = useUpdatePackageFromMarketPlace()return (- <Popover>- <PopoverTrigger- openOnHover- nativeButton={false}- aria-label={- typeof tooltip === 'string'- ? tooltip- : t(($) => $['nodes.agent.installPlugin.title'], { ns: 'workflowAgent' })- }- render={content}- />- <PopoverContent className="px-3 py-2 system-xs-regular text-text-tertiary">- {tooltip}- </PopoverContent>- </Popover>+ <>+ <DialogHeader>+ <DialogTitle>+ {t(($) => $['nodes.agent.installPlugin.title'], { ns: 'workflowAgent' })}+ </DialogTitle>+ <DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />+ </DialogHeader>+ <DialogBody>+ <div className="mb-2 system-md-regular text-text-secondary">+ {t(($) => $['nodes.agent.installPlugin.desc'], { ns: 'workflowAgent' })}+ </div>+ <div className="flex flex-wrap content-start items-start gap-1 self-stretch rounded-2xl bg-background-section-burn p-2">+ <Card+ installed={mutation.isSuccess}+ payload={pluginManifestToCardPluginProps({+ ...selection.plugin.declaration,+ icon: getIconUrl(selection.plugin.declaration.icon),+ })}+ className="w-full"+ titleLeft={+ <Badge2 className="mx-1" size="s" variant="warning">+ {`${selection.plugin.version} -> ${selection.target.version}`}+ </Badge2>+ }+ />+ </div>+ </DialogBody>+ <DialogFooter>+ <Link+ className="me-auto flex items-center justify-center gap-1"+ href={getMarketplaceUrl(+ `/plugins/${selection.plugin.declaration.author}/${selection.plugin.declaration.name}`,+ )}+ target="_blank"+ rel="noopener noreferrer"+ >+ <span className="system-xs-regular text-xs text-text-accent">+ {t(($) => $['nodes.agent.installPlugin.changelog'], { ns: 'workflowAgent' })}+ </span>+ <span className="i-ri-external-link-line size-3 text-text-accent" />+ </Link>+ {!mutation.isPending && (+ <DialogClose render={<Button />}>+ {t(($) => $['nodes.agent.installPlugin.cancel'], { ns: 'workflowAgent' })}+ </DialogClose>+ )}+ <Button+ variant="primary"+ loading={mutation.isPending}+ disabled={!canUpdatePlugin}+ onClick={() => {+ if (!canUpdatePlugin) return+ mutation.mutate(+ {+ new_plugin_unique_identifier: selection.target.unique_identifier,+ original_plugin_unique_identifier: selection.plugin.plugin_unique_identifier,+ },+ {+ onSuccess: () => {+ onInstalled(selection.target.version)+ },+ },+ )+ }}+ >+ {t(($) => $['nodes.agent.installPlugin.install'], { ns: 'workflowAgent' })}+ </Button>+ </DialogFooter>+ </>)}diff --git a/web/context/modal-context-provider.tsx b/web/context/modal-context-provider.tsxindex 6fa3599c09f..3919c148606 100644--- a/web/context/modal-context-provider.tsx+++ b/web/context/modal-context-provider.tsx@@ -51,9 +51,12 @@ const OpeningSettingModal = dynamic(ssr: false,},)-const UpdatePlugin = dynamic(() => import('@/app/components/plugins/update-plugin'), {- ssr: false,-})+const InstallFromGitHub = dynamic(+ () => import('@/app/components/plugins/install-plugin/install-from-github'),+ {+ ssr: false,+ },+)const TriggerEventsLimitModal = dynamic(() => import('@/app/components/billing/trigger-events-limit-modal'),@@ -257,13 +260,13 @@ export const ModalContextProvider = ({ children }: ModalContextProviderProps) =>)}{!!showUpdatePluginModal && (- <UpdatePlugin- {...showUpdatePluginModal.payload}- onCancel={() => {+ <InstallFromGitHub+ updatePayload={showUpdatePluginModal.payload.github}+ onClose={() => {setShowUpdatePluginModal(null)showUpdatePluginModal.onCancelCallback?.()}}- onSave={() => {+ onSuccess={() => {if (showUpdatePluginModal.payload.category !== PluginCategoryEnum.model) {setShowUpdatePluginModal(null)showUpdatePluginModal.onSaveCallback?.()diff --git a/web/context/modal-context.test.tsx b/web/context/modal-context.test.tsxindex 8fe35a77269..91e07cd570b 100644--- a/web/context/modal-context.test.tsx+++ b/web/context/modal-context.test.tsx@@ -3,7 +3,7 @@ import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import dayjs from 'dayjs'import * as React from 'react'-import { PluginCategoryEnum, PluginSource } from '@/app/components/plugins/types'+import { PluginCategoryEnum } from '@/app/components/plugins/types'import { useModalContextSelector } from '@/context/modal-context'import { ModalContextProvider } from '@/context/modal-context-provider'import { createConsoleQueryWrapper, seedFeatures } from '@/test/console/query-data'@@ -17,9 +17,9 @@ vi.mock('@/next/navigation', () => ({useSearchParams: vi.fn(() => new URLSearchParams()),}))-vi.mock('@/app/components/plugins/update-plugin', () => ({- default: ({ onSave }: { onSave: () => void | Promise<void> }) => (- <button data-testid="save-plugin-update" onClick={onSave}>+vi.mock('@/app/components/plugins/install-plugin/install-from-github', () => ({+ default: ({ onSuccess }: { onSuccess: () => void | Promise<void> }) => (+ <button data-testid="save-plugin-update" onClick={onSuccess}>Save plugin update</button>),@@ -48,7 +48,6 @@ const UpdatePluginTrigger = ({setShowUpdatePluginModal({onSaveCallback: onSave,payload: {- type: PluginSource.github,category,github: {originalPackageInfo: {diff --git a/web/i18n/locales/ar-TN/plugin.json b/web/i18n/locales/ar-TN/plugin.jsonindex 8ba98759203..bc0c7596c17 100644--- a/web/i18n/locales/ar-TN/plugin.json+++ b/web/i18n/locales/ar-TN/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "تثبيت الإضافات","task.successPlugins": "تم تثبيت الإضافات بنجاح","templatePublishingGuide": "دليل نشر القوالب",- "upgrade.close": "إغلاق","upgrade.description": "على وشك تثبيت الإضافة التالية",- "upgrade.successfulTitle": "تم التثبيت بنجاح","upgrade.title": "تثبيت الإضافة","upgrade.upgrade": "تثبيت","upgrade.upgrading": "جارٍ التثبيت..."diff --git a/web/i18n/locales/az-AZ/plugin.json b/web/i18n/locales/az-AZ/plugin.jsonindex df6e96cfb7d..ecbe7de4d46 100644--- a/web/i18n/locales/az-AZ/plugin.json+++ b/web/i18n/locales/az-AZ/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Quraşdırılan inteqrasiyalar","task.successPlugins": "Uğurla quraşdırılan inteqrasiyalar","templatePublishingGuide": "Şablon dərc etmə təlimatı",- "upgrade.close": "Bağla","upgrade.description": "Aşağıdakı inteqrasiya quraşdırılacaq",- "upgrade.successfulTitle": "Quraşdırma uğurla tamamlandı","upgrade.title": "İnteqrasiyanın quraşdırılması","upgrade.upgrade": "Quraşdır","upgrade.upgrading": "Quraşdırılır..."diff --git a/web/i18n/locales/de-DE/plugin.json b/web/i18n/locales/de-DE/plugin.jsonindex 5f2847ad8be..ac50cfd6a91 100644--- a/web/i18n/locales/de-DE/plugin.json+++ b/web/i18n/locales/de-DE/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Leitfaden zur Vorlagen-Veröffentlichung",- "upgrade.close": "Schließen","upgrade.description": "Über die Installation des folgenden Plugins",- "upgrade.successfulTitle": "Installation erfolgreich","upgrade.title": "Plugin installieren","upgrade.upgrade": "Installieren","upgrade.upgrading": "Installation..."diff --git a/web/i18n/locales/en-US/plugin.json b/web/i18n/locales/en-US/plugin.jsonindex 7c594e600e4..5c2e868a160 100644--- a/web/i18n/locales/en-US/plugin.json+++ b/web/i18n/locales/en-US/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Integrations","task.successPlugins": "Successfully Installed Integrations","templatePublishingGuide": "Template publishing guide",- "upgrade.close": "Close","upgrade.description": "About to install the following integration",- "upgrade.successfulTitle": "Install successful","upgrade.title": "Install Integration","upgrade.upgrade": "Install","upgrade.upgrading": "Installing..."diff --git a/web/i18n/locales/es-ES/plugin.json b/web/i18n/locales/es-ES/plugin.jsonindex 64b081f81ad..bbfe288998e 100644--- a/web/i18n/locales/es-ES/plugin.json+++ b/web/i18n/locales/es-ES/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Guía de publicación de plantillas",- "upgrade.close": "Cerrar","upgrade.description": "A punto de instalar el siguiente plugin",- "upgrade.successfulTitle": "Instalación correcta","upgrade.title": "Instalar plugin","upgrade.upgrade": "Instalar","upgrade.upgrading": "Instalar..."diff --git a/web/i18n/locales/fa-IR/plugin.json b/web/i18n/locales/fa-IR/plugin.jsonindex 17d803cd467..ca2eb7ef9ab 100644--- a/web/i18n/locales/fa-IR/plugin.json+++ b/web/i18n/locales/fa-IR/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "راهنمای انتشار الگو",- "upgrade.close": "نزدیک","upgrade.description": "در مورد نصب افزونه زیر",- "upgrade.successfulTitle": "نصب موفقیت آمیز","upgrade.title": "افزونه را نصب کنید","upgrade.upgrade": "نصب","upgrade.upgrading": "نصب..."diff --git a/web/i18n/locales/fr-FR/plugin.json b/web/i18n/locales/fr-FR/plugin.jsonindex 95ea11b3de5..ca1c355d1d1 100644--- a/web/i18n/locales/fr-FR/plugin.json+++ b/web/i18n/locales/fr-FR/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Guide de publication de modèle",- "upgrade.close": "Fermer","upgrade.description": "Sur le point d’installer le plugin suivant",- "upgrade.successfulTitle": "Installation réussie","upgrade.title": "Installer le plugin","upgrade.upgrade": "Installer","upgrade.upgrading": "Installation..."diff --git a/web/i18n/locales/hi-IN/plugin.json b/web/i18n/locales/hi-IN/plugin.jsonindex e9bf3a71b0f..208474ebcb3 100644--- a/web/i18n/locales/hi-IN/plugin.json+++ b/web/i18n/locales/hi-IN/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "टेम्पलेट प्रकाशन मार्गदर्शिका",- "upgrade.close": "करीब","upgrade.description": "निम्नलिखित प्लगइन स्थापित करने वाले हैं",- "upgrade.successfulTitle": "स्थापना सफल","upgrade.title": "प्लगइन स्थापित करें","upgrade.upgrade": "स्थापित करें","upgrade.upgrading": "स्थापित कर रहा है..."diff --git a/web/i18n/locales/id-ID/plugin.json b/web/i18n/locales/id-ID/plugin.jsonindex d58853fb0a3..2adc3b7a2e6 100644--- a/web/i18n/locales/id-ID/plugin.json+++ b/web/i18n/locales/id-ID/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Panduan penerbitan templat",- "upgrade.close": "Tutup","upgrade.description": "Tentang menginstal plugin berikut",- "upgrade.successfulTitle": "Instal berhasil","upgrade.title": "Instal Plugin","upgrade.upgrade": "Pasang","upgrade.upgrading": "Menginstal..."diff --git a/web/i18n/locales/it-IT/plugin.json b/web/i18n/locales/it-IT/plugin.jsonindex 62b9e85f2eb..57a4cb6d974 100644--- a/web/i18n/locales/it-IT/plugin.json+++ b/web/i18n/locales/it-IT/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Guida alla pubblicazione dei modelli",- "upgrade.close": "Chiudere","upgrade.description": "Sto per installare il seguente plugin",- "upgrade.successfulTitle": "Installazione riuscita","upgrade.title": "Installa il plugin","upgrade.upgrade": "Installare","upgrade.upgrading": "Installazione..."diff --git a/web/i18n/locales/ja-JP/plugin.json b/web/i18n/locales/ja-JP/plugin.jsonindex 46c08fc0381..c3ec4f66d48 100644--- a/web/i18n/locales/ja-JP/plugin.json+++ b/web/i18n/locales/ja-JP/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "インストール中のプラグイン","task.successPlugins": "インストール済みのプラグイン","templatePublishingGuide": "テンプレート公開ガイド",- "upgrade.close": "閉じる","upgrade.description": "次のプラグインをインストールしようとしています",- "upgrade.successfulTitle": "インストールに成功しました","upgrade.title": "プラグインをインストール","upgrade.upgrade": "インストール","upgrade.upgrading": "インストール中..."diff --git a/web/i18n/locales/ko-KR/plugin.json b/web/i18n/locales/ko-KR/plugin.jsonindex 307ca19ecf4..234929379e2 100644--- a/web/i18n/locales/ko-KR/plugin.json+++ b/web/i18n/locales/ko-KR/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "템플릿 게시 가이드",- "upgrade.close": "닫기","upgrade.description": "다음 플러그인을 설치하려고 합니다.",- "upgrade.successfulTitle": "설치 성공","upgrade.title": "플러그인 설치","upgrade.upgrade": "업그레이드","upgrade.upgrading": "설치..."diff --git a/web/i18n/locales/lo-LA/plugin.json b/web/i18n/locales/lo-LA/plugin.jsonindex 681d15d08be..6aa2ac151e2 100644--- a/web/i18n/locales/lo-LA/plugin.json+++ b/web/i18n/locales/lo-LA/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "ກຳລັງຕິດຕັ້ງການເຊື່ອມຕໍ່","task.successPlugins": "ຕິດຕັ້ງການເຊື່ອມຕໍ່ສຳເລັດແລ້ວ","templatePublishingGuide": "ຄູ່ມືການເຜີຍແຜ່ແທມເພຼດ",- "upgrade.close": "ປິດ","upgrade.description": "ກຳລັງຈະຕິດຕັ້ງການເຊື່ອມຕໍ່ຕໍ່ໄປນີ້",- "upgrade.successfulTitle": "ຕິດຕັ້ງສຳເລັດ","upgrade.title": "ຕິດຕັ້ງການເຊື່ອມຕໍ່","upgrade.upgrade": "ຕິດຕັ້ງ","upgrade.upgrading": "ກຳລັງຕິດຕັ້ງ..."diff --git a/web/i18n/locales/nl-NL/plugin.json b/web/i18n/locales/nl-NL/plugin.jsonindex 9e929a5312b..e11580931f5 100644--- a/web/i18n/locales/nl-NL/plugin.json+++ b/web/i18n/locales/nl-NL/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Handleiding voor templatepublicatie",- "upgrade.close": "Close","upgrade.description": "About to install the following plugin",- "upgrade.successfulTitle": "Install successful","upgrade.title": "Install Plugin","upgrade.upgrade": "Install","upgrade.upgrading": "Installing..."diff --git a/web/i18n/locales/pl-PL/plugin.json b/web/i18n/locales/pl-PL/plugin.jsonindex da425f53ae7..ce2f96b8231 100644--- a/web/i18n/locales/pl-PL/plugin.json+++ b/web/i18n/locales/pl-PL/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Przewodnik publikowania szablonów",- "upgrade.close": "Zamykać","upgrade.description": "Informacje o instalacji następującej wtyczki",- "upgrade.successfulTitle": "Instalacja powiodła się","upgrade.title": "Zainstaluj wtyczkę","upgrade.upgrade": "Instalować","upgrade.upgrading": "Instalowanie..."diff --git a/web/i18n/locales/pt-BR/plugin.json b/web/i18n/locales/pt-BR/plugin.jsonindex b778bcac15b..854fd502561 100644--- a/web/i18n/locales/pt-BR/plugin.json+++ b/web/i18n/locales/pt-BR/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Guia de publicação de modelos",- "upgrade.close": "Fechar","upgrade.description": "Prestes a instalar o seguinte plugin",- "upgrade.successfulTitle": "Instalação bem-sucedida","upgrade.title": "Instale o plugin","upgrade.upgrade": "Instalar","upgrade.upgrading": "Instalar..."diff --git a/web/i18n/locales/ro-RO/plugin.json b/web/i18n/locales/ro-RO/plugin.jsonindex 8a31c30eef5..01d729be431 100644--- a/web/i18n/locales/ro-RO/plugin.json+++ b/web/i18n/locales/ro-RO/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Ghid de publicare a șabloanelor",- "upgrade.close": "Închide","upgrade.description": "Despre instalarea următorului plugin",- "upgrade.successfulTitle": "Instalarea cu succes","upgrade.title": "Instalează pluginul","upgrade.upgrade": "Instala","upgrade.upgrading": "Instalarea..."diff --git a/web/i18n/locales/ru-RU/plugin.json b/web/i18n/locales/ru-RU/plugin.jsonindex ce0efbb376e..41084a11f42 100644--- a/web/i18n/locales/ru-RU/plugin.json+++ b/web/i18n/locales/ru-RU/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Руководство по публикации шаблонов",- "upgrade.close": "Закрывать","upgrade.description": "О программе установки следующего плагина",- "upgrade.successfulTitle": "Установка успешна","upgrade.title": "Установить плагин","upgrade.upgrade": "Устанавливать","upgrade.upgrading": "Установка..."diff --git a/web/i18n/locales/sl-SI/plugin.json b/web/i18n/locales/sl-SI/plugin.jsonindex e8a3b620d2b..6945ad8528c 100644--- a/web/i18n/locales/sl-SI/plugin.json+++ b/web/i18n/locales/sl-SI/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Vodnik za objavljanje predlog",- "upgrade.close": "Zapri","upgrade.description": "Namestitev naslednjega vtičnika",- "upgrade.successfulTitle": "Namestitev uspešna","upgrade.title": "Namestite vtičnik","upgrade.upgrade": "Namestite","upgrade.upgrading": "Nameščanje..."diff --git a/web/i18n/locales/th-TH/plugin.json b/web/i18n/locales/th-TH/plugin.jsonindex f6a61a9e482..53b0cbdd398 100644--- a/web/i18n/locales/th-TH/plugin.json+++ b/web/i18n/locales/th-TH/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "คู่มือการเผยแพร่เทมเพลต",- "upgrade.close": "ปิด","upgrade.description": "เกี่ยวกับการติดตั้งปลั๊กอินต่อไปนี้",- "upgrade.successfulTitle": "ติดตั้งสําเร็จ","upgrade.title": "ติดตั้งปลั๊กอิน","upgrade.upgrade": "ติดตั้ง","upgrade.upgrading": "ติด ตั้ง "diff --git a/web/i18n/locales/tr-TR/plugin.json b/web/i18n/locales/tr-TR/plugin.jsonindex f31893c5acc..2eba09e7054 100644--- a/web/i18n/locales/tr-TR/plugin.json+++ b/web/i18n/locales/tr-TR/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Eklentiler Yükleniyor","task.successPlugins": "Başarıyla Yüklenen Eklentiler","templatePublishingGuide": "Şablon yayınlama kılavuzu",- "upgrade.close": "Kapat","upgrade.description": "Aşağıdaki eklentiyi güncellemek üzeresiniz",- "upgrade.successfulTitle": "Güncelleme başarılı","upgrade.title": "Eklentiyi Güncelle","upgrade.upgrade": "Güncelle","upgrade.upgrading": "Güncelleniyor..."diff --git a/web/i18n/locales/uk-UA/plugin.json b/web/i18n/locales/uk-UA/plugin.jsonindex 7f8cbd39276..edca63e7353 100644--- a/web/i18n/locales/uk-UA/plugin.json+++ b/web/i18n/locales/uk-UA/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Посібник з публікації шаблонів",- "upgrade.close": "Закрити","upgrade.description": "Про встановлення наступного плагіна",- "upgrade.successfulTitle": "Установка успішна","upgrade.title": "Встановити плагін","upgrade.upgrade": "Інсталювати","upgrade.upgrading": "Установки..."diff --git a/web/i18n/locales/vi-VN/plugin.json b/web/i18n/locales/vi-VN/plugin.jsonindex 0eff881773d..0f719875a64 100644--- a/web/i18n/locales/vi-VN/plugin.json+++ b/web/i18n/locales/vi-VN/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "Hướng dẫn xuất bản mẫu",- "upgrade.close": "Đóng","upgrade.description": "Giới thiệu cài đặt plugin sau",- "upgrade.successfulTitle": "Cài đặt thành công","upgrade.title": "Cài đặt Plugin","upgrade.upgrade": "Cài đặt","upgrade.upgrading": "Cài đặt..."diff --git a/web/i18n/locales/zh-Hans/plugin.json b/web/i18n/locales/zh-Hans/plugin.jsonindex e07189605fe..b824315a48f 100644--- a/web/i18n/locales/zh-Hans/plugin.json+++ b/web/i18n/locales/zh-Hans/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "正在安装的集成","task.successPlugins": "安装成功的集成","templatePublishingGuide": "模板发布指南",- "upgrade.close": "关闭","upgrade.description": "即将安装以下集成",- "upgrade.successfulTitle": "安装成功","upgrade.title": "安装集成","upgrade.upgrade": "安装","upgrade.upgrading": "安装中..."diff --git a/web/i18n/locales/zh-Hant/plugin.json b/web/i18n/locales/zh-Hant/plugin.jsonindex 569ff1cdebd..99960a27331 100644--- a/web/i18n/locales/zh-Hant/plugin.json+++ b/web/i18n/locales/zh-Hant/plugin.json@@ -301,9 +301,7 @@"task.runningPlugins": "Installing Plugins","task.successPlugins": "Successfully Installed Plugins","templatePublishingGuide": "範本發佈指南",- "upgrade.close": "關閉","upgrade.description": "即將安裝以下插件",- "upgrade.successfulTitle": "安裝成功","upgrade.title": "安裝插件","upgrade.upgrade": "安裝","upgrade.upgrading": "安裝。。。"diff --git a/web/i18n/resources.generated.d.ts b/web/i18n/resources.generated.d.tsindex 3fa85d97dcb..bf7063d4c34 100644--- a/web/i18n/resources.generated.d.ts+++ b/web/i18n/resources.generated.d.ts@@ -3837,9 +3837,7 @@ export default interface Resources {'task.runningPlugins': 'Installing Integrations''task.successPlugins': 'Successfully Installed Integrations'templatePublishingGuide: 'Template publishing guide'- 'upgrade.close': 'Close''upgrade.description': 'About to install the following integration'- 'upgrade.successfulTitle': 'Install successful''upgrade.title': 'Install Integration''upgrade.upgrade': 'Install''upgrade.upgrading': 'Installing...'diff --git a/web/service/__tests__/use-plugins.spec.tsx b/web/service/__tests__/use-plugins.spec.tsxindex 1f3d6b2e957..ac530d6bd58 100644--- a/web/service/__tests__/use-plugins.spec.tsx+++ b/web/service/__tests__/use-plugins.spec.tsx@@ -32,7 +32,6 @@ import {usePluginAutoUpgradeSettings,usePluginTaskList,useRemoveFilteredInstalledPluginPageOnUnmount,- useVersionListOfPlugin,} from '../use-plugins'const { mockGet, mockGetMarketplace, mockPost, mockRequest } = vi.hoisted(() => ({@@ -672,37 +671,6 @@ describe('use-plugins mutations', () => {})})-describe('useVersionListOfPlugin', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- it('does not fetch versions while disabled', () => {- const queryClient = createQueryClient()-- renderHook(() => useVersionListOfPlugin('plugin-1', false), {- wrapper: createWrapper(queryClient),- })-- expect(mockGetMarketplace).not.toHaveBeenCalled()- })-- it('fetches versions when enabled', async () => {- const queryClient = createQueryClient()- mockGetMarketplace.mockResolvedValue({ data: { versions: [] } })-- renderHook(() => useVersionListOfPlugin('plugin-1'), {- wrapper: createWrapper(queryClient),- })-- await waitFor(() => {- expect(mockGetMarketplace).toHaveBeenCalledWith('/plugins/plugin-1/versions', {- params: { page: 1, page_size: 100 },- })- })- })-})-describe('useInstalledPluginList', () => {beforeEach(() => {vi.clearAllMocks()diff --git a/web/service/plugins.ts b/web/service/plugins.tsindex d55fdde0228..556b1bdfbde 100644--- a/web/service/plugins.ts+++ b/web/service/plugins.ts@@ -1,4 +1,3 @@-import type { ParserMarketplaceUpgrade } from '@dify/contracts/api/console/workspaces/types.gen'import type { PluginInfoFromMarketPlace } from '@dify/contracts/marketplace'import type { Dependency, PluginManifestInMarket } from '@/app/components/plugins/types'import { consoleClient } from '@/service/console'@@ -17,10 +16,6 @@ export const uploadFile = async (file: File, isBundle: boolean) => {)}-export const updateFromMarketPlace = async (body: ParserMarketplaceUpgrade) => {- return consoleClient.workspaces.current.plugin.upgrade.marketplace.post({ body })-}-export const updateFromGitHub = async (repoUrl: string,selectedVersion: string,diff --git a/web/service/use-plugins.ts b/web/service/use-plugins.tsindex 5f9f2f785ef..d3469ad1ccf 100644--- a/web/service/use-plugins.ts+++ b/web/service/use-plugins.ts@@ -31,7 +31,6 @@ import type {PluginTask,ReferenceSetting,VersionInfo,- VersionListResponse,} from '@/app/components/plugins/types'import type { Collection } from '@/app/components/tools/types'import {@@ -855,17 +854,6 @@ export const usePluginDeclarationFromMarketPlace = (pluginUniqueIdentifier: stri})}-export const useVersionListOfPlugin = (pluginID: string, enabled = true) => {- return useQuery<{ data: VersionListResponse }>({- enabled: enabled && !!pluginID,- queryKey: [NAME_SPACE, 'versions', pluginID],- queryFn: () =>- getMarketplace<{ data: VersionListResponse }>(`/plugins/${pluginID}/versions`, {- params: { page: 1, page_size: 100 },- }),- })-}-export const useInstallPackageFromLocal = () => {const queryClient = useQueryClient()return useMutation({