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
feat: enhance model plugin workflow checks and model provider management UX (#33289)
yyhbbe975c6bca3
diff --git a/.github/workflows/web-tests.yml b/.github/workflows/web-tests.ymlindex 11222146cf1..be2595a5992 100644--- a/.github/workflows/web-tests.yml+++ b/.github/workflows/web-tests.yml@@ -29,8 +29,8 @@ jobs:strategy:fail-fast: falsematrix:- shardIndex: [1, 2, 3, 4]- shardTotal: [4]+ shardIndex: [1, 2, 3, 4, 5, 6]+ shardTotal: [6]defaults:run:shell: bashdiff --git a/web/__tests__/billing/pricing-modal-flow.test.tsx b/web/__tests__/billing/pricing-modal-flow.test.tsxindex 6b8fb57f834..7326ee35599 100644--- a/web/__tests__/billing/pricing-modal-flow.test.tsx+++ b/web/__tests__/billing/pricing-modal-flow.test.tsx@@ -295,24 +295,7 @@ describe('Pricing Modal Flow', () => {})})- // ─── 6. Close Handling ───────────────────────────────────────────────────- describe('Close handling', () => {- it('should call onCancel when pressing ESC key', () => {- render(<Pricing onCancel={onCancel} />)-- // ahooks useKeyPress listens on document for keydown events- document.dispatchEvent(new KeyboardEvent('keydown', {- key: 'Escape',- code: 'Escape',- keyCode: 27,- bubbles: true,- }))-- expect(onCancel).toHaveBeenCalledTimes(1)- })- })-- // ─── 7. Pricing URL ─────────────────────────────────────────────────────+ // ─── 6. Pricing URL ─────────────────────────────────────────────────────describe('Pricing page URL', () => {it('should render pricing link with correct URL', () => {render(<Pricing onCancel={onCancel} />)diff --git a/web/__tests__/plugins/plugin-card-rendering.test.tsx b/web/__tests__/plugins/plugin-card-rendering.test.tsxindex 7abcb01b499..5bd7f0c8bf8 100644--- a/web/__tests__/plugins/plugin-card-rendering.test.tsx+++ b/web/__tests__/plugins/plugin-card-rendering.test.tsx@@ -8,6 +8,8 @@import { cleanup, render, screen } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'+let mockTheme = 'light'+vi.mock('#i18n', () => ({useTranslation: () => ({t: (key: string) => key,@@ -19,16 +21,16 @@ vi.mock('@/context/i18n', () => ({}))vi.mock('@/hooks/use-theme', () => ({- default: () => ({ theme: 'light' }),+ default: () => ({ theme: mockTheme }),}))vi.mock('@/i18n-config', () => ({renderI18nObject: (obj: Record<string, string>, locale: string) => obj[locale] || obj.en_US || '',}))-vi.mock('@/types/app', () => ({- Theme: { dark: 'dark', light: 'light' },-}))+vi.mock('@/types/app', async () => {+ return vi.importActual<typeof import('@/types/app')>('@/types/app')+})vi.mock('@/utils/classnames', () => ({cn: (...args: unknown[]) => args.filter(a => typeof a === 'string' && a).join(' '),@@ -100,6 +102,7 @@ type CardPayload = Parameters<typeof Card>[0]['payload']describe('Plugin Card Rendering Integration', () => {beforeEach(() => {cleanup()+ mockTheme = 'light'})const makePayload = (overrides = {}) => ({@@ -194,9 +197,7 @@ describe('Plugin Card Rendering Integration', () => {})it('uses dark icon when theme is dark and icon_dark is provided', () => {- vi.doMock('@/hooks/use-theme', () => ({- default: () => ({ theme: 'dark' }),- }))+ mockTheme = 'dark'const payload = makePayload({icon: 'https://example.com/icon-light.png',@@ -204,7 +205,7 @@ describe('Plugin Card Rendering Integration', () => {})render(<Card payload={payload} />)- expect(screen.getByTestId('card-icon')).toBeInTheDocument()+ expect(screen.getByTestId('card-icon')).toHaveTextContent('https://example.com/icon-dark.png')})it('shows loading placeholder when isLoading is true', () => {diff --git a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsxindex 9bd32d2576f..3fc677d8d80 100644--- a/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx+++ b/web/app/account/(commonLayout)/account-page/AvatarWithEdit.tsx@@ -160,7 +160,7 @@ const AvatarWithEdit = ({ onSave, ...props }: AvatarWithEditProps) => {isShow={isShowDeleteConfirm}onClose={() => setIsShowDeleteConfirm(false)}>- <div className="title-2xl-semi-bold mb-3 text-text-primary">{t('avatar.deleteTitle', { ns: 'common' })}</div>+ <div className="mb-3 text-text-primary title-2xl-semi-bold">{t('avatar.deleteTitle', { ns: 'common' })}</div><p className="mb-8 text-text-secondary">{t('avatar.deleteDescription', { ns: 'common' })}</p><div className="flex w-full items-center justify-center gap-2">diff --git a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx b/web/app/account/(commonLayout)/account-page/email-change-modal.tsxindex 463c27294a5..c146174ea92 100644--- a/web/app/account/(commonLayout)/account-page/email-change-modal.tsx+++ b/web/app/account/(commonLayout)/account-page/email-change-modal.tsx@@ -209,14 +209,14 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {</div>{step === STEP.start && (<>- <div className="title-2xl-semi-bold pb-3 text-text-primary">{t('account.changeEmail.title', { ns: 'common' })}</div>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.title', { ns: 'common' })}</div><div className="space-y-0.5 pb-2 pt-1">- <div className="body-md-medium text-text-warning">{t('account.changeEmail.authTip', { ns: 'common' })}</div>- <div className="body-md-regular text-text-secondary">+ <div className="text-text-warning body-md-medium">{t('account.changeEmail.authTip', { ns: 'common' })}</div>+ <div className="text-text-secondary body-md-regular"><Transi18nKey="account.changeEmail.content1"ns="common"- components={{ email: <span className="body-md-medium text-text-primary"></span> }}+ components={{ email: <span className="text-text-primary body-md-medium"></span> }}values={{ email }}/></div>@@ -241,19 +241,19 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {)}{step === STEP.verifyOrigin && (<>- <div className="title-2xl-semi-bold pb-3 text-text-primary">{t('account.changeEmail.verifyEmail', { ns: 'common' })}</div>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.verifyEmail', { ns: 'common' })}</div><div className="space-y-0.5 pb-2 pt-1">- <div className="body-md-regular text-text-secondary">+ <div className="text-text-secondary body-md-regular"><Transi18nKey="account.changeEmail.content2"ns="common"- components={{ email: <span className="body-md-medium text-text-primary"></span> }}+ components={{ email: <span className="text-text-primary body-md-medium"></span> }}values={{ email }}/></div></div><div className="pt-3">- <div className="system-sm-medium mb-1 flex h-6 items-center text-text-secondary">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div><InputclassName="!w-full"placeholder={t('account.changeEmail.codePlaceholder', { ns: 'common' })}@@ -278,25 +278,25 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {{t('operation.cancel', { ns: 'common' })}</Button></div>- <div className="system-xs-regular mt-3 flex items-center gap-1 text-text-tertiary">+ <div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular"><span>{t('account.changeEmail.resendTip', { ns: 'common' })}</span>{time > 0 && (<span>{t('account.changeEmail.resendCount', { ns: 'common', count: time })}</span>)}{!time && (- <span onClick={sendCodeToOriginEmail} className="system-xs-medium cursor-pointer text-text-accent-secondary">{t('account.changeEmail.resend', { ns: 'common' })}</span>+ <span onClick={sendCodeToOriginEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('account.changeEmail.resend', { ns: 'common' })}</span>)}</div></>)}{step === STEP.newEmail && (<>- <div className="title-2xl-semi-bold pb-3 text-text-primary">{t('account.changeEmail.newEmail', { ns: 'common' })}</div>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.newEmail', { ns: 'common' })}</div><div className="space-y-0.5 pb-2 pt-1">- <div className="body-md-regular text-text-secondary">{t('account.changeEmail.content3', { ns: 'common' })}</div>+ <div className="text-text-secondary body-md-regular">{t('account.changeEmail.content3', { ns: 'common' })}</div></div><div className="pt-3">- <div className="system-sm-medium mb-1 flex h-6 items-center text-text-secondary">{t('account.changeEmail.emailLabel', { ns: 'common' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.emailLabel', { ns: 'common' })}</div><InputclassName="!w-full"placeholder={t('account.changeEmail.emailPlaceholder', { ns: 'common' })}@@ -305,10 +305,10 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {destructive={newEmailExited || unAvailableEmail}/>{newEmailExited && (- <div className="body-xs-regular mt-1 py-0.5 text-text-destructive">{t('account.changeEmail.existingEmail', { ns: 'common' })}</div>+ <div className="mt-1 py-0.5 text-text-destructive body-xs-regular">{t('account.changeEmail.existingEmail', { ns: 'common' })}</div>)}{unAvailableEmail && (- <div className="body-xs-regular mt-1 py-0.5 text-text-destructive">{t('account.changeEmail.unAvailableEmail', { ns: 'common' })}</div>+ <div className="mt-1 py-0.5 text-text-destructive body-xs-regular">{t('account.changeEmail.unAvailableEmail', { ns: 'common' })}</div>)}</div><div className="mt-3 space-y-2">@@ -331,19 +331,19 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {)}{step === STEP.verifyNew && (<>- <div className="title-2xl-semi-bold pb-3 text-text-primary">{t('account.changeEmail.verifyNew', { ns: 'common' })}</div>+ <div className="pb-3 text-text-primary title-2xl-semi-bold">{t('account.changeEmail.verifyNew', { ns: 'common' })}</div><div className="space-y-0.5 pb-2 pt-1">- <div className="body-md-regular text-text-secondary">+ <div className="text-text-secondary body-md-regular"><Transi18nKey="account.changeEmail.content4"ns="common"- components={{ email: <span className="body-md-medium text-text-primary"></span> }}+ components={{ email: <span className="text-text-primary body-md-medium"></span> }}values={{ email: mail }}/></div></div><div className="pt-3">- <div className="system-sm-medium mb-1 flex h-6 items-center text-text-secondary">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-medium">{t('account.changeEmail.codeLabel', { ns: 'common' })}</div><InputclassName="!w-full"placeholder={t('account.changeEmail.codePlaceholder', { ns: 'common' })}@@ -368,13 +368,13 @@ const EmailChangeModal = ({ onClose, email, show }: Props) => {{t('operation.cancel', { ns: 'common' })}</Button></div>- <div className="system-xs-regular mt-3 flex items-center gap-1 text-text-tertiary">+ <div className="mt-3 flex items-center gap-1 text-text-tertiary system-xs-regular"><span>{t('account.changeEmail.resendTip', { ns: 'common' })}</span>{time > 0 && (<span>{t('account.changeEmail.resendCount', { ns: 'common', count: time })}</span>)}{!time && (- <span onClick={sendCodeToNewEmail} className="system-xs-medium cursor-pointer text-text-accent-secondary">{t('account.changeEmail.resend', { ns: 'common' })}</span>+ <span onClick={sendCodeToNewEmail} className="cursor-pointer text-text-accent-secondary system-xs-medium">{t('account.changeEmail.resend', { ns: 'common' })}</span>)}</div></>diff --git a/web/app/account/(commonLayout)/account-page/index.tsx b/web/app/account/(commonLayout)/account-page/index.tsxindex 58331e3a778..9a104619da7 100644--- a/web/app/account/(commonLayout)/account-page/index.tsx+++ b/web/app/account/(commonLayout)/account-page/index.tsx@@ -145,7 +145,7 @@ export default function AccountPage() {imageUrl={icon_url}/></div>- <div className="system-sm-medium mt-[3px] text-text-secondary">{item.name}</div>+ <div className="mt-[3px] text-text-secondary system-sm-medium">{item.name}</div></div>)}@@ -153,12 +153,12 @@ export default function AccountPage() {return (<><div className="pb-3 pt-2">- <h4 className="title-2xl-semi-bold text-text-primary">{t('account.myAccount', { ns: 'common' })}</h4>+ <h4 className="text-text-primary title-2xl-semi-bold">{t('account.myAccount', { ns: 'common' })}</h4></div><div className="mb-8 flex items-center rounded-xl bg-gradient-to-r from-background-gradient-bg-fill-chat-bg-2 to-background-gradient-bg-fill-chat-bg-1 p-6"><AvatarWithEdit avatar={userProfile.avatar_url} name={userProfile.name} onSave={mutateUserProfile} size="3xl" /><div className="ml-4">- <p className="system-xl-semibold text-text-primary">+ <p className="text-text-primary system-xl-semibold">{userProfile.name}{isEducationAccount && (<PremiumBadge size="s" color="blue" className="ml-1 !px-2">@@ -167,16 +167,16 @@ export default function AccountPage() {</PremiumBadge>)}</p>- <p className="system-xs-regular text-text-tertiary">{userProfile.email}</p>+ <p className="text-text-tertiary system-xs-regular">{userProfile.email}</p></div></div><div className="mb-8"><div className={titleClassName}>{t('account.name', { ns: 'common' })}</div><div className="mt-2 flex w-full items-center justify-between gap-2">- <div className="system-sm-regular flex-1 rounded-lg bg-components-input-bg-normal p-2 text-components-input-text-filled ">+ <div className="flex-1 rounded-lg bg-components-input-bg-normal p-2 text-components-input-text-filled system-sm-regular"><span className="pl-1">{userProfile.name}</span></div>- <div className="system-sm-medium cursor-pointer rounded-lg bg-components-button-tertiary-bg px-3 py-2 text-components-button-tertiary-text" onClick={handleEditName}>+ <div className="cursor-pointer rounded-lg bg-components-button-tertiary-bg px-3 py-2 text-components-button-tertiary-text system-sm-medium" onClick={handleEditName}>{t('operation.edit', { ns: 'common' })}</div></div>@@ -184,11 +184,11 @@ export default function AccountPage() {<div className="mb-8"><div className={titleClassName}>{t('account.email', { ns: 'common' })}</div><div className="mt-2 flex w-full items-center justify-between gap-2">- <div className="system-sm-regular flex-1 rounded-lg bg-components-input-bg-normal p-2 text-components-input-text-filled ">+ <div className="flex-1 rounded-lg bg-components-input-bg-normal p-2 text-components-input-text-filled system-sm-regular"><span className="pl-1">{userProfile.email}</span></div>{systemFeatures.enable_change_email && (- <div className="system-sm-medium cursor-pointer rounded-lg bg-components-button-tertiary-bg px-3 py-2 text-components-button-tertiary-text" onClick={() => setShowUpdateEmail(true)}>+ <div className="cursor-pointer rounded-lg bg-components-button-tertiary-bg px-3 py-2 text-components-button-tertiary-text system-sm-medium" onClick={() => setShowUpdateEmail(true)}>{t('operation.change', { ns: 'common' })}</div>)}@@ -198,8 +198,8 @@ export default function AccountPage() {systemFeatures.enable_email_password_login && (<div className="mb-8 flex justify-between gap-2"><div>- <div className="system-sm-semibold mb-1 text-text-secondary">{t('account.password', { ns: 'common' })}</div>- <div className="body-xs-regular mb-2 text-text-tertiary">{t('account.passwordTip', { ns: 'common' })}</div>+ <div className="mb-1 text-text-secondary system-sm-semibold">{t('account.password', { ns: 'common' })}</div>+ <div className="mb-2 text-text-tertiary body-xs-regular">{t('account.passwordTip', { ns: 'common' })}</div></div><Button onClick={() => setEditPasswordModalVisible(true)}>{userProfile.is_password_set ? t('account.resetPassword', { ns: 'common' }) : t('account.setPassword', { ns: 'common' })}</Button></div>@@ -226,7 +226,7 @@ export default function AccountPage() {onClose={() => setEditNameModalVisible(false)}className="!w-[420px] !p-6">- <div className="title-2xl-semi-bold mb-6 text-text-primary">{t('account.editName', { ns: 'common' })}</div>+ <div className="mb-6 text-text-primary title-2xl-semi-bold">{t('account.editName', { ns: 'common' })}</div><div className={titleClassName}>{t('account.name', { ns: 'common' })}</div><InputclassName="mt-2"@@ -256,7 +256,7 @@ export default function AccountPage() {}}className="!w-[420px] !p-6">- <div className="title-2xl-semi-bold mb-6 text-text-primary">{userProfile.is_password_set ? t('account.resetPassword', { ns: 'common' }) : t('account.setPassword', { ns: 'common' })}</div>+ <div className="mb-6 text-text-primary title-2xl-semi-bold">{userProfile.is_password_set ? t('account.resetPassword', { ns: 'common' }) : t('account.setPassword', { ns: 'common' })}</div>{userProfile.is_password_set && (<><div className={titleClassName}>{t('account.currentPassword', { ns: 'common' })}</div>@@ -279,7 +279,7 @@ export default function AccountPage() {</div></>)}- <div className="system-sm-semibold mt-8 text-text-secondary">+ <div className="mt-8 text-text-secondary system-sm-semibold">{userProfile.is_password_set ? t('account.newPassword', { ns: 'common' }) : t('account.password', { ns: 'common' })}</div><div className="relative mt-2">@@ -298,7 +298,7 @@ export default function AccountPage() {</Button></div></div>- <div className="system-sm-semibold mt-8 text-text-secondary">{t('account.confirmPassword', { ns: 'common' })}</div>+ <div className="mt-8 text-text-secondary system-sm-semibold">{t('account.confirmPassword', { ns: 'common' })}</div><div className="relative mt-2"><Inputtype={showConfirmPassword ? 'text' : 'password'}diff --git a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx b/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsxindex 118eaea58e0..a969b3d491c 100644--- a/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx+++ b/web/app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx@@ -94,7 +94,7 @@ const CSVUploader: FC<Props> = ({/><div ref={dropRef}>{!file && (- <div className={cn('system-sm-regular flex h-20 items-center rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg', dragging && 'border border-components-dropzone-border-accent bg-components-dropzone-bg-accent')}>+ <div className={cn('flex h-20 items-center rounded-xl border border-dashed border-components-dropzone-border bg-components-dropzone-bg system-sm-regular', dragging && 'border border-components-dropzone-border-accent bg-components-dropzone-bg-accent')}><div className="flex w-full items-center justify-center space-x-2"><CSVIcon className="shrink-0" /><div className="text-text-tertiary">diff --git a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsx b/web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsxindex be4377bfd9b..abcf5795d0b 100644--- a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsx+++ b/web/app/components/app/configuration/base/warning-mask/has-not-set-api.spec.tsx@@ -2,25 +2,19 @@ import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'import HasNotSetAPI from './has-not-set-api'-describe('HasNotSetAPI WarningMask', () => {- it('should show default title when trial not finished', () => {- render(<HasNotSetAPI isTrailFinished={false} onSetting={vi.fn()} />)+describe('HasNotSetAPI', () => {+ it('should render the empty state copy', () => {+ render(<HasNotSetAPI onSetting={vi.fn()} />)- expect(screen.getByText('appDebug.notSetAPIKey.title')).toBeInTheDocument()- expect(screen.getByText('appDebug.notSetAPIKey.description')).toBeInTheDocument()+ expect(screen.getByText('appDebug.noModelProviderConfigured')).toBeInTheDocument()+ expect(screen.getByText('appDebug.noModelProviderConfiguredTip')).toBeInTheDocument()})- it('should show trail finished title when flag is true', () => {- render(<HasNotSetAPI isTrailFinished onSetting={vi.fn()} />)-- expect(screen.getByText('appDebug.notSetAPIKey.trailFinished')).toBeInTheDocument()- })-- it('should call onSetting when primary button clicked', () => {+ it('should call onSetting when manage models button is clicked', () => {const onSetting = vi.fn()- render(<HasNotSetAPI isTrailFinished={false} onSetting={onSetting} />)+ render(<HasNotSetAPI onSetting={onSetting} />)- fireEvent.click(screen.getByRole('button', { name: 'appDebug.notSetAPIKey.settingBtn' }))+ fireEvent.click(screen.getByRole('button', { name: 'appDebug.manageModels' }))expect(onSetting).toHaveBeenCalledTimes(1)})})diff --git a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsx b/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsxindex 84323e64f5d..2c5fc5ff2fc 100644--- a/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsx+++ b/web/app/components/app/configuration/base/warning-mask/has-not-set-api.tsx@@ -2,38 +2,38 @@import type { FC } from 'react'import * as React from 'react'import { useTranslation } from 'react-i18next'-import Button from '@/app/components/base/button'-import WarningMask from '.'export type IHasNotSetAPIProps = {- isTrailFinished: booleanonSetting: () => void}-const icon = (- <svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">- <path d="M14 6.00001L14 2.00001M14 2.00001H9.99999M14 2.00001L8 8M6.66667 2H5.2C4.0799 2 3.51984 2 3.09202 2.21799C2.71569 2.40973 2.40973 2.71569 2.21799 3.09202C2 3.51984 2 4.07989 2 5.2V10.8C2 11.9201 2 12.4802 2.21799 12.908C2.40973 13.2843 2.71569 13.5903 3.09202 13.782C3.51984 14 4.07989 14 5.2 14H10.8C11.9201 14 12.4802 14 12.908 13.782C13.2843 13.5903 13.5903 13.2843 13.782 12.908C14 12.4802 14 11.9201 14 10.8V9.33333" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />- </svg>--)-const HasNotSetAPI: FC<IHasNotSetAPIProps> = ({- isTrailFinished,onSetting,}) => {const { t } = useTranslation()return (- <WarningMask- title={isTrailFinished ? t('notSetAPIKey.trailFinished', { ns: 'appDebug' }) : t('notSetAPIKey.title', { ns: 'appDebug' })}- description={t('notSetAPIKey.description', { ns: 'appDebug' })}- footer={(- <Button variant="primary" className="flex space-x-2" onClick={onSetting}>- <span>{t('notSetAPIKey.settingBtn', { ns: 'appDebug' })}</span>- {icon}- </Button>- )}- />+ <div className="flex grow flex-col items-center justify-center pb-[120px]">+ <div className="flex w-full max-w-[400px] flex-col gap-2 px-4 py-4">+ <div className="flex h-10 w-10 items-center justify-center rounded-[10px]">+ <div className="flex h-full w-full items-center justify-center overflow-hidden rounded-[10px] border-[0.5px] border-components-card-border bg-components-card-bg p-1 shadow-lg backdrop-blur-[5px]">+ <span className="i-ri-brain-2-line h-5 w-5 text-text-tertiary" />+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <div className="text-text-secondary system-md-semibold">{t('noModelProviderConfigured', { ns: 'appDebug' })}</div>+ <div className="text-text-tertiary system-xs-regular">{t('noModelProviderConfiguredTip', { ns: 'appDebug' })}</div>+ </div>+ <button+ type="button"+ className="flex w-fit items-center gap-1 rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg px-3 py-2 shadow-xs backdrop-blur-[5px]"+ onClick={onSetting}+ >+ <span className="text-components-button-secondary-accent-text system-sm-medium">{t('manageModels', { ns: 'appDebug' })}</span>+ <span className="i-ri-arrow-right-line h-4 w-4 text-components-button-secondary-accent-text" />+ </button>+ </div>+ </div>)}export default React.memo(HasNotSetAPI)diff --git a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsxindex c33d55873d1..39a16990636 100644--- a/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx+++ b/web/app/components/app/configuration/config-prompt/simple-prompt-input.tsx@@ -178,7 +178,7 @@ const Prompt: FC<ISimplePromptInput> = ({{!noTitle && (<div className="flex h-11 items-center justify-between pl-3 pr-2.5"><div className="flex items-center space-x-1">- <div className="h2 system-sm-semibold-uppercase text-text-secondary">{mode !== AppModeEnum.COMPLETION ? t('chatSubTitle', { ns: 'appDebug' }) : t('completionSubTitle', { ns: 'appDebug' })}</div>+ <div className="h2 text-text-secondary system-sm-semibold-uppercase">{mode !== AppModeEnum.COMPLETION ? t('chatSubTitle', { ns: 'appDebug' }) : t('completionSubTitle', { ns: 'appDebug' })}</div>{!readonly && (<TooltippopupContent={(diff --git a/web/app/components/app/configuration/config/agent/prompt-editor.tsx b/web/app/components/app/configuration/config/agent/prompt-editor.tsxindex 9f1f04ba3c7..f719d872613 100644--- a/web/app/components/app/configuration/config/agent/prompt-editor.tsx+++ b/web/app/components/app/configuration/config/agent/prompt-editor.tsx@@ -96,7 +96,7 @@ const Editor: FC<Props> = ({)}</div></div>- <div className={cn(editorHeight, ' min-h-[102px] overflow-y-auto px-4 text-sm text-gray-700')}>+ <div className={cn(editorHeight, 'min-h-[102px] overflow-y-auto px-4 text-sm text-gray-700')}><PromptEditorclassName={editorHeight}value={value}diff --git a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsxindex 5166ae49f3e..da651c93e1c 100644--- a/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx+++ b/web/app/components/app/configuration/config/code-generator/get-code-generator-res.tsx@@ -3,8 +3,10 @@ import type { FormValue } from '@/app/components/header/account-setting/model-primport type { CodeLanguage } from '@/app/components/workflow/nodes/code/types'import type { GenRes } from '@/service/debug'import type { AppModeEnum, CompletionParams, Model, ModelModeType } from '@/types/app'-import { useSessionStorageState } from 'ahooks'-import useBoolean from 'ahooks/lib/useBoolean'+import {+ useBoolean,+ useSessionStorageState,+} from 'ahooks'import * as React from 'react'import { useCallback, useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -224,7 +226,7 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = (</div><div><div className="text-[0px]">- <div className="system-sm-semibold-uppercase mb-1.5 text-text-secondary">{t('codegen.instruction', { ns: 'appDebug' })}</div>+ <div className="mb-1.5 text-text-secondary system-sm-semibold-uppercase">{t('codegen.instruction', { ns: 'appDebug' })}</div><InstructionEditoreditorKey={editorKey}value={instruction}@@ -248,7 +250,7 @@ export const GetCodeGeneratorResModal: FC<IGetCodeGeneratorResProps> = (disabled={isLoading}><Generator className="h-4 w-4" />- <span className="text-xs font-semibold ">{t('codegen.generate', { ns: 'appDebug' })}</span>+ <span className="text-xs font-semibold">{t('codegen.generate', { ns: 'appDebug' })}</span></Button></div></div>diff --git a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsxindex c9c8d080f21..bc534599dec 100644--- a/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx+++ b/web/app/components/app/configuration/dataset-config/settings-modal/index.tsx@@ -210,7 +210,7 @@ const SettingsModal: FC<SettingsModalProps> = ({<div className="overflow-y-auto border-b border-divider-regular p-6 pb-[68px] pt-5"><div className={cn(rowClass, 'items-center')}><div className={labelClass}>- <div className="system-sm-semibold text-text-secondary">{t('form.name', { ns: 'datasetSettings' })}</div>+ <div className="text-text-secondary system-sm-semibold">{t('form.name', { ns: 'datasetSettings' })}</div></div><Inputvalue={localeCurrentDataset.name}@@ -221,7 +221,7 @@ const SettingsModal: FC<SettingsModalProps> = ({</div><div className={cn(rowClass)}><div className={labelClass}>- <div className="system-sm-semibold text-text-secondary">{t('form.desc', { ns: 'datasetSettings' })}</div>+ <div className="text-text-secondary system-sm-semibold">{t('form.desc', { ns: 'datasetSettings' })}</div></div><div className="w-full"><Textarea@@ -234,7 +234,7 @@ const SettingsModal: FC<SettingsModalProps> = ({</div><div className={rowClass}><div className={labelClass}>- <div className="system-sm-semibold text-text-secondary">{t('form.permissions', { ns: 'datasetSettings' })}</div>+ <div className="text-text-secondary system-sm-semibold">{t('form.permissions', { ns: 'datasetSettings' })}</div></div><div className="w-full"><PermissionSelector@@ -250,7 +250,7 @@ const SettingsModal: FC<SettingsModalProps> = ({{!!(currentDataset && currentDataset.indexing_technique) && (<div className={cn(rowClass)}><div className={labelClass}>- <div className="system-sm-semibold text-text-secondary">{t('form.indexMethod', { ns: 'datasetSettings' })}</div>+ <div className="text-text-secondary system-sm-semibold">{t('form.indexMethod', { ns: 'datasetSettings' })}</div></div><div className="grow"><IndexMethod@@ -267,7 +267,7 @@ const SettingsModal: FC<SettingsModalProps> = ({{indexMethod === IndexingType.QUALIFIED && (<div className={cn(rowClass)}><div className={labelClass}>- <div className="system-sm-semibold text-text-secondary">{t('form.embeddingModel', { ns: 'datasetSettings' })}</div>+ <div className="text-text-secondary system-sm-semibold">{t('form.embeddingModel', { ns: 'datasetSettings' })}</div></div><div className="w-full"><div className="h-8 w-full rounded-lg bg-components-input-bg-normal opacity-60">diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsxindex 5ef1dcadbb9..96fac39c501 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.spec.tsx@@ -1,13 +1,25 @@import type { ReactNode } from 'react'import type { ModelAndParameter } from '../types'-import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type {+ FormValue,+ ModelProvider,+} from '@/app/components/header/account-setting/model-provider-page/declarations'import { render, screen } from '@testing-library/react'-import { ModelStatusEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { createMockProviderContextValue } from '@/__mocks__/provider-context'+import {+ ConfigurationMethodEnum,+ CurrentSystemQuotaTypeEnum,+ CustomConfigurationStatusEnum,+ ModelStatusEnum,+ ModelTypeEnum,+ PreferredProviderTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'import ModelParameterTrigger from './model-parameter-trigger'const mockUseDebugConfigurationContext = vi.fn()const mockUseDebugWithMultipleModelContext = vi.fn()-const mockUseLanguage = vi.fn()+const mockUseProviderContext = vi.fn()+const mockUseCredentialPanelState = vi.fn()type RenderTriggerProps = {open: boolean@@ -35,8 +47,12 @@ vi.mock('./context', () => ({useDebugWithMultipleModelContext: () => mockUseDebugWithMultipleModelContext(),}))-vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({- useLanguage: () => mockUseLanguage(),+vi.mock('@/context/provider-context', () => ({+ useProviderContext: () => mockUseProviderContext(),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state', () => ({+ useCredentialPanelState: () => mockUseCredentialPanelState(),}))vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal', () => ({@@ -84,6 +100,41 @@ const createModelAndParameter = (overrides: Partial<ModelAndParameter> = {}): Mo...overrides,})+const createModelProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'openai',+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ help: {+ title: { en_US: 'Help', zh_Hans: 'Help' },+ url: { en_US: 'https://example.com', zh_Hans: 'https://example.com' },+ },+ icon_small: { en_US: '', zh_Hans: '' },+ supported_model_types: [ModelTypeEnum.textGeneration],+ configurate_methods: [ConfigurationMethodEnum.predefinedModel],+ provider_credential_schema: {+ credential_form_schemas: [],+ },+ model_credential_schema: {+ model: {+ label: { en_US: 'Model', zh_Hans: 'Model' },+ placeholder: { en_US: 'Select model', zh_Hans: 'Select model' },+ },+ credential_form_schemas: [],+ },+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: 'cred-1',+ current_credential_name: 'Primary Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Primary Key' }],+ },+ system_configuration: {+ enabled: true,+ current_quota_type: CurrentSystemQuotaTypeEnum.trial,+ quota_configurations: [],+ },+ ...overrides,+})+const renderComponent = (props: Partial<{ modelAndParameter: ModelAndParameter }> = {}) => {const defaultProps = {modelAndParameter: createModelAndParameter(),@@ -106,8 +157,19 @@ describe('ModelParameterTrigger', () => {onMultipleModelConfigsChange: vi.fn(),onDebugWithMultipleModelChange: vi.fn(),})-- mockUseLanguage.mockReturnValue('en_US')+ mockUseProviderContext.mockReturnValue(createMockProviderContextValue({+ modelProviders: [createModelProvider()],+ }))+ mockUseCredentialPanelState.mockReturnValue({+ variant: 'api-active',+ priority: 'apiKey',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: true,+ isCreditsExhausted: false,+ credentialName: 'Primary Key',+ credits: 10,+ })})describe('rendering', () => {@@ -311,23 +373,66 @@ describe('ModelParameterTrigger', () => {expect(screen.getByTestId('model-parameter-modal')).toBeInTheDocument()})- it('should render "Select Model" text when no provider/model', () => {- renderComponent()+ it('should render "Select Model" text when no provider or model is configured', () => {+ renderComponent({+ modelAndParameter: createModelAndParameter({+ provider: '',+ model: '',+ }),+ })// When currentProvider and currentModel are null, shows "Select Model"expect(screen.getByText('common.modelProvider.selectModel')).toBeInTheDocument()})- })-- describe('language context', () => {- it('should use language from useLanguage hook', () => {- mockUseLanguage.mockReturnValue('zh_Hans')+ it('should render configured model id and incompatible tooltip when model is missing from the provider list', () => {renderComponent()- // The language is used for MODEL_STATUS_TEXT tooltip- // We verify the hook is called- expect(mockUseLanguage).toHaveBeenCalled()+ expect(screen.getByText('gpt-3.5-turbo')).toBeInTheDocument()+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-content', 'common.modelProvider.selector.incompatibleTip')+ })++ it('should render configure required tooltip for no-configure status', () => {+ const { unmount } = renderComponent()+ const triggerContent = capturedModalProps?.renderTrigger({+ open: false,+ currentProvider: { provider: 'openai' },+ currentModel: { model: 'gpt-3.5-turbo', status: ModelStatusEnum.noConfigure },+ })++ unmount()+ render(<>{triggerContent}</>)++ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-content', 'common.modelProvider.selector.configureRequired')+ })++ it('should render disabled tooltip for disabled status', () => {+ const { unmount } = renderComponent()+ const triggerContent = capturedModalProps?.renderTrigger({+ open: false,+ currentProvider: { provider: 'openai' },+ currentModel: { model: 'gpt-3.5-turbo', status: ModelStatusEnum.disabled },+ })++ unmount()+ render(<>{triggerContent}</>)++ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-content', 'common.modelProvider.selector.disabled')+ })++ it('should apply expanded and warning styles when the trigger is open for a non-active status', () => {+ const { unmount } = renderComponent()+ const triggerContent = capturedModalProps?.renderTrigger({+ open: true,+ currentProvider: { provider: 'openai' },+ currentModel: { model: 'gpt-3.5-turbo', status: ModelStatusEnum.noConfigure },+ })++ unmount()+ const { container } = render(<>{triggerContent}</>)++ expect(container.firstChild).toHaveClass('bg-state-base-hover')+ expect(container.firstChild).toHaveClass('!bg-[#FFFAEB]')})})diff --git a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx b/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsxindex afe292c5ee3..43282d3300c 100644--- a/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx+++ b/web/app/components/app/configuration/debug/debug-with-multiple-model/model-parameter-trigger.tsx@@ -1,22 +1,20 @@import type { FC } from 'react'import type { ModelAndParameter } from '../types'import type { FormValue } from '@/app/components/header/account-setting/model-provider-page/declarations'-import { RiArrowDownSLine } from '@remixicon/react'import { memo } from 'react'import { useTranslation } from 'react-i18next'-import { AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'-import { CubeOutline } from '@/app/components/base/icons/src/vender/line/shapes'import Tooltip from '@/app/components/base/tooltip'import {-- MODEL_STATUS_TEXT,- ModelStatusEnum,-} from '@/app/components/header/account-setting/model-provider-page/declarations'-import { useLanguage } from '@/app/components/header/account-setting/model-provider-page/hooks'+ DERIVED_MODEL_STATUS_BADGE_I18N,+ DERIVED_MODEL_STATUS_TOOLTIP_I18N,+ deriveModelStatus,+} from '@/app/components/header/account-setting/model-provider-page/derive-model-status'import ModelIcon from '@/app/components/header/account-setting/model-provider-page/model-icon'import ModelName from '@/app/components/header/account-setting/model-provider-page/model-name'import ModelParameterModal from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal'+import { useCredentialPanelState } from '@/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state'import { useDebugConfigurationContext } from '@/context/debug-configuration'+import { useProviderContext } from '@/context/provider-context'import { useDebugWithMultipleModelContext } from './context'type ModelParameterTriggerProps = {@@ -34,8 +32,10 @@ const ModelParameterTrigger: FC<ModelParameterTriggerProps> = ({onMultipleModelConfigsChange,onDebugWithMultipleModelChange,} = useDebugWithMultipleModelContext()- const language = useLanguage()+ const { modelProviders } = useProviderContext()const index = multipleModelConfigs.findIndex(v => v.id === modelAndParameter.id)+ const providerMeta = modelProviders.find(provider => provider.provider === modelAndParameter.provider)+ const credentialState = useCredentialPanelState(providerMeta)const handleSelectModel = ({ modelId, provider }: { modelId: string, provider: string }) => {const newModelConfigs = [...multipleModelConfigs]@@ -69,55 +69,77 @@ const ModelParameterTrigger: FC<ModelParameterTriggerProps> = ({open,currentProvider,currentModel,- }) => (- <div- className={`- flex h-8 max-w-[200px] cursor-pointer items-center rounded-lg px-2- ${open && 'bg-state-base-hover'}- ${currentModel && currentModel.status !== ModelStatusEnum.active && '!bg-[#FFFAEB]'}- `}- >- {- currentProvider && (- <ModelIcon- className="mr-1 !h-4 !w-4"- provider={currentProvider}- modelName={currentModel?.model}- />- )- }- {- !currentProvider && (- <div className="mr-1 flex h-4 w-4 items-center justify-center rounded">- <CubeOutline className="h-4 w-4 text-text-accent" />- </div>- )- }- {- currentModel && (- <ModelName- className="mr-0.5 text-text-secondary"- modelItem={currentModel}- />- )- }- {- !currentModel && (- <div className="mr-0.5 truncate text-[13px] font-medium text-text-accent">- {t('modelProvider.selectModel', { ns: 'common' })}- </div>- )- }- <RiArrowDownSLine className={`h-3 w-3 ${(currentModel && currentProvider) ? 'text-text-tertiary' : 'text-text-accent'}`} />- {- currentModel && currentModel.status !== ModelStatusEnum.active && (- <Tooltip popupContent={MODEL_STATUS_TEXT[currentModel.status][language]}>- <AlertTriangle className="h-4 w-4 text-[#F79009]" />- </Tooltip>- )- }- </div>- )}+ }) => {+ const status = deriveModelStatus(+ modelAndParameter.model,+ modelAndParameter.provider,+ providerMeta,+ currentModel ?? undefined,+ credentialState,+ )+ const iconProvider = currentProvider || providerMeta+ const statusLabelKey = DERIVED_MODEL_STATUS_BADGE_I18N[status as keyof typeof DERIVED_MODEL_STATUS_BADGE_I18N]+ const statusTooltipKey = DERIVED_MODEL_STATUS_TOOLTIP_I18N[status as keyof typeof DERIVED_MODEL_STATUS_TOOLTIP_I18N]+ const isEmpty = status === 'empty'+ const isActive = status === 'active'++ return (+ <div+ className={`+ flex h-8 max-w-[200px] cursor-pointer items-center rounded-lg px-2+ ${open && 'bg-state-base-hover'}+ ${!isEmpty && !isActive && '!bg-[#FFFAEB]'}+ `}+ >+ {+ iconProvider && !isEmpty && (+ <ModelIcon+ className="mr-1 !h-4 !w-4"+ provider={iconProvider}+ modelName={currentModel?.model || modelAndParameter.model}+ />+ )+ }+ {+ (!iconProvider || isEmpty) && (+ <div className="mr-1 flex h-4 w-4 items-center justify-center rounded">+ <span className="i-custom-vender-line-shapes-cube-outline h-4 w-4 text-text-accent" />+ </div>+ )+ }+ {+ currentModel && (+ <ModelName+ className="mr-0.5 text-text-secondary"+ modelItem={currentModel}+ />+ )+ }+ {+ !currentModel && !isEmpty && (+ <div className="mr-0.5 truncate text-[13px] font-medium text-text-secondary">+ {modelAndParameter.model}+ </div>+ )+ }+ {+ isEmpty && (+ <div className="mr-0.5 truncate text-[13px] font-medium text-text-accent">+ {t('modelProvider.selectModel', { ns: 'common' })}+ </div>+ )+ }+ <span className={`i-ri-arrow-down-s-line h-3 w-3 ${isEmpty ? 'text-text-accent' : 'text-text-tertiary'}`} />+ {+ !isEmpty && !isActive && statusLabelKey && (+ <Tooltip popupContent={t((statusTooltipKey || statusLabelKey) as 'modelProvider.selector.incompatible', { ns: 'common' })}>+ <span className="i-custom-vender-line-alertsAndFeedback-alert-triangle h-4 w-4 text-[#F79009]" />+ </Tooltip>+ )+ }+ </div>+ )+ }}/>)}diff --git a/web/app/components/app/configuration/debug/index.spec.tsx b/web/app/components/app/configuration/debug/index.spec.tsxnew file mode 100644index 00000000000..e94695f1ef1--- /dev/null+++ b/web/app/components/app/configuration/debug/index.spec.tsx@@ -0,0 +1,1021 @@+import type { ComponentProps } from 'react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import * as React from 'react'+import { ToastContext } from '@/app/components/base/toast/context'+import { ModelFeatureEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import ConfigContext from '@/context/debug-configuration'+import { AppModeEnum, ModelModeType, TransferMethod } from '@/types/app'+import Debug from './index'+import { APP_CHAT_WITH_MULTIPLE_MODEL, APP_CHAT_WITH_MULTIPLE_MODEL_RESTART } from './types'++type DebugContextValue = ComponentProps<typeof ConfigContext.Provider>['value']+type DebugProps = ComponentProps<typeof Debug>++const mockState = vi.hoisted(() => ({+ mockSendCompletionMessage: vi.fn(),+ mockHandleRestart: vi.fn(),+ mockSetFeatures: vi.fn(),+ mockEventEmitterEmit: vi.fn(),+ mockText2speechDefaultModel: null as unknown,+ mockStoreState: {+ currentLogItem: null as unknown,+ setCurrentLogItem: vi.fn(),+ showPromptLogModal: false,+ setShowPromptLogModal: vi.fn(),+ showAgentLogModal: false,+ setShowAgentLogModal: vi.fn(),+ },+ mockFeaturesState: {+ moreLikeThis: { enabled: false },+ moderation: { enabled: false },+ text2speech: { enabled: false },+ file: { enabled: false, allowed_file_upload_methods: [] as string[], fileUploadConfig: undefined as { image_file_size_limit?: number } | undefined },+ },+ mockProviderContext: {+ textGenerationModelList: [] as Array<{+ provider: string+ models: Array<{+ model: string+ features?: string[]+ model_properties: { mode?: string }+ }>+ }>,+ },+}))++vi.mock('@/app/components/app/configuration/debug/chat-user-input', () => ({+ default: () => <div data-testid="chat-user-input">ChatUserInput</div>,+}))++vi.mock('@/app/components/app/configuration/prompt-value-panel', () => ({+ default: ({ onSend, onVisionFilesChange }: {+ onSend: () => void+ onVisionFilesChange: (files: Array<Record<string, unknown>>) => void+ }) => (+ <div data-testid="prompt-value-panel">+ <button type="button" data-testid="panel-send" onClick={onSend}>Send</button>+ <button+ type="button"+ data-testid="panel-set-pending-file"+ onClick={() => onVisionFilesChange([{ transfer_method: TransferMethod.local_file }])}+ >+ Pending File+ </button>+ <button+ type="button"+ data-testid="panel-set-uploaded-file"+ onClick={() => onVisionFilesChange([{ transfer_method: TransferMethod.local_file, upload_file_id: 'file-id' }])}+ >+ Uploaded File+ </button>+ <button+ type="button"+ data-testid="panel-set-remote-file"+ onClick={() => onVisionFilesChange([{ transfer_method: TransferMethod.remote_url, url: 'https://example.com/file.png' }])}+ >+ Remote File+ </button>+ </div>+ ),+}))++vi.mock('@/app/components/app/store', () => ({+ useStore: (selector: (state: {+ currentLogItem: unknown+ setCurrentLogItem: () => void+ showPromptLogModal: boolean+ setShowPromptLogModal: () => void+ showAgentLogModal: boolean+ setShowAgentLogModal: () => void+ }) => unknown) => selector(mockState.mockStoreState),+}))++vi.mock('@/app/components/app/text-generate/item', () => ({+ default: ({ content, isLoading, isShowTextToSpeech, messageId }: {+ content: string+ isLoading: boolean+ isShowTextToSpeech: boolean+ messageId: string | null+ }) => (+ <div+ data-testid="text-generation"+ data-loading={isLoading ? 'true' : 'false'}+ data-tts={isShowTextToSpeech ? 'true' : 'false'}+ data-message-id={messageId || ''}+ >+ {content}+ </div>+ ),+}))++vi.mock('@/app/components/base/action-button', () => ({+ default: ({ children, onClick, state }: { children: React.ReactNode, onClick?: () => void, state?: string }) => (+ <button type="button" data-testid="action-button" data-state={state} onClick={onClick}>+ {children}+ </button>+ ),+ ActionButtonState: {+ Active: 'active',+ },+}))++vi.mock('@/app/components/base/agent-log-modal', () => ({+ default: ({ onCancel }: { onCancel: () => void }) => (+ <div data-testid="agent-log-modal">+ <button type="button" data-testid="agent-log-cancel" onClick={onCancel}>Cancel</button>+ </div>+ ),+}))++vi.mock('@/app/components/base/features/hooks', () => ({+ useFeatures: (selector: (state: { features: {+ moreLikeThis: { enabled: boolean }+ moderation: { enabled: boolean }+ text2speech: { enabled: boolean }+ file: { enabled: boolean, allowed_file_upload_methods: string[], fileUploadConfig?: { image_file_size_limit?: number } }+ } }) => unknown) => selector({ features: mockState.mockFeaturesState }),+ useFeaturesStore: () => ({+ getState: () => ({+ features: mockState.mockFeaturesState,+ setFeatures: mockState.mockSetFeatures,+ }),+ }),+}))++vi.mock('@/app/components/base/prompt-log-modal', () => ({+ default: ({ onCancel }: { onCancel: () => void }) => (+ <div data-testid="prompt-log-modal">+ <button type="button" data-testid="prompt-log-cancel" onClick={onCancel}>Cancel</button>+ </div>+ ),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useDefaultModel: () => ({ data: mockState.mockText2speechDefaultModel }),+}))++vi.mock('@/context/event-emitter', () => ({+ useEventEmitterContextContext: () => ({+ eventEmitter: { emit: mockState.mockEventEmitterEmit },+ }),+}))++vi.mock('@/context/provider-context', () => ({+ useProviderContext: () => mockState.mockProviderContext,+}))++vi.mock('@/service/debug', () => ({+ sendCompletionMessage: mockState.mockSendCompletionMessage,+}))++vi.mock('../base/group-name', () => ({+ default: ({ name }: { name: string }) => <div>{name}</div>,+}))++vi.mock('../base/warning-mask/cannot-query-dataset', () => ({+ default: ({ onConfirm }: { onConfirm: () => void }) => (+ <div data-testid="cannot-query-dataset">+ <button type="button" data-testid="cannot-query-confirm" onClick={onConfirm}>Confirm</button>+ </div>+ ),+}))++vi.mock('../base/warning-mask/formatting-changed', () => ({+ default: ({ onConfirm, onCancel }: { onConfirm: () => void, onCancel: () => void }) => (+ <div data-testid="formatting-changed">+ <button type="button" data-testid="formatting-confirm" onClick={onConfirm}>Confirm</button>+ <button type="button" data-testid="formatting-cancel" onClick={onCancel}>Cancel</button>+ </div>+ ),+}))++vi.mock('./debug-with-multiple-model', () => ({+ default: ({+ checkCanSend,+ onDebugWithMultipleModelChange,+ }: {+ checkCanSend: () => boolean+ onDebugWithMultipleModelChange: (item: { id: string, model: string, provider: string, parameters: Record<string, unknown> }) => void+ }) => (+ <div data-testid="debug-with-multiple-model">+ <button type="button" data-testid="multiple-check-can-send" onClick={() => checkCanSend()}>Check</button>+ <button+ type="button"+ data-testid="multiple-switch-to-single"+ onClick={() => onDebugWithMultipleModelChange({+ id: 'model-1',+ model: 'vision-model',+ provider: 'openai',+ parameters: { temperature: 0.2 },+ })}+ >+ Switch+ </button>+ </div>+ ),+}))++vi.mock('./debug-with-single-model', () => ({+ default: React.forwardRef((props: { checkCanSend: () => boolean }, ref) => {+ React.useImperativeHandle(ref, () => ({+ handleRestart: mockState.mockHandleRestart,+ }))++ return (+ <div data-testid="debug-with-single-model">+ <button type="button" data-testid="single-check-can-send" onClick={() => props.checkCanSend()}>Check</button>+ </div>+ )+ }),+}))++const createContextValue = (overrides: Partial<DebugContextValue> = {}): DebugContextValue => ({+ readonly: false,+ appId: 'app-id',+ isAPIKeySet: true,+ isTrailFinished: false,+ mode: AppModeEnum.CHAT,+ modelModeType: ModelModeType.chat,+ promptMode: 'simple' as DebugContextValue['promptMode'],+ setPromptMode: vi.fn(),+ isAdvancedMode: false,+ isAgent: false,+ isFunctionCall: false,+ isOpenAI: true,+ collectionList: [],+ canReturnToSimpleMode: false,+ setCanReturnToSimpleMode: vi.fn(),+ chatPromptConfig: { prompt: [] } as DebugContextValue['chatPromptConfig'],+ completionPromptConfig: {+ prompt: { text: '' },+ conversation_histories_role: { user_prefix: 'user', assistant_prefix: 'assistant' },+ } as DebugContextValue['completionPromptConfig'],+ currentAdvancedPrompt: [],+ setCurrentAdvancedPrompt: vi.fn(),+ showHistoryModal: vi.fn(),+ conversationHistoriesRole: { user_prefix: 'user', assistant_prefix: 'assistant' },+ setConversationHistoriesRole: vi.fn(),+ hasSetBlockStatus: { context: false, history: true, query: true },+ conversationId: null,+ setConversationId: vi.fn(),+ introduction: '',+ setIntroduction: vi.fn(),+ suggestedQuestions: [],+ setSuggestedQuestions: vi.fn(),+ controlClearChatMessage: 0,+ setControlClearChatMessage: vi.fn(),+ prevPromptConfig: { prompt_template: '', prompt_variables: [] },+ setPrevPromptConfig: vi.fn(),+ moreLikeThisConfig: { enabled: false },+ setMoreLikeThisConfig: vi.fn(),+ suggestedQuestionsAfterAnswerConfig: { enabled: false },+ setSuggestedQuestionsAfterAnswerConfig: vi.fn(),+ speechToTextConfig: { enabled: false },+ setSpeechToTextConfig: vi.fn(),+ textToSpeechConfig: { enabled: false, voice: '', language: '' },+ setTextToSpeechConfig: vi.fn(),+ citationConfig: { enabled: false },+ setCitationConfig: vi.fn(),+ annotationConfig: {+ id: '',+ enabled: false,+ score_threshold: 0.7,+ embedding_model: {+ embedding_model_name: '',+ embedding_provider_name: '',+ },+ },+ setAnnotationConfig: vi.fn(),+ moderationConfig: { enabled: false },+ setModerationConfig: vi.fn(),+ externalDataToolsConfig: [],+ setExternalDataToolsConfig: vi.fn(),+ formattingChanged: false,+ setFormattingChanged: vi.fn(),+ inputs: {},+ setInputs: vi.fn(),+ query: '',+ setQuery: vi.fn(),+ completionParams: {},+ setCompletionParams: vi.fn(),+ modelConfig: {+ provider: 'openai',+ model_id: 'gpt-4',+ mode: ModelModeType.chat,+ configs: {+ prompt_template: '',+ prompt_variables: [],+ },+ chat_prompt_config: { prompt: [] },+ completion_prompt_config: {+ prompt: { text: '' },+ conversation_histories_role: { user_prefix: 'user', assistant_prefix: 'assistant' },+ },+ more_like_this: null,+ opening_statement: '',+ suggested_questions: [],+ sensitive_word_avoidance: null,+ speech_to_text: null,+ text_to_speech: null,+ file_upload: null,+ suggested_questions_after_answer: null,+ retriever_resource: null,+ annotation_reply: null,+ external_data_tools: [],+ system_parameters: {+ audio_file_size_limit: 0,+ file_size_limit: 0,+ image_file_size_limit: 0,+ video_file_size_limit: 0,+ workflow_file_upload_limit: 0,+ },+ dataSets: [],+ agentConfig: {+ enabled: false,+ max_iteration: 5,+ tools: [],+ strategy: 'react',+ },+ } as DebugContextValue['modelConfig'],+ setModelConfig: vi.fn(),+ dataSets: [],+ setDataSets: vi.fn(),+ showSelectDataSet: vi.fn(),+ datasetConfigs: {+ retrieval_model: 'single',+ reranking_model: {+ reranking_provider_name: '',+ reranking_model_name: '',+ },+ top_k: 4,+ score_threshold_enabled: false,+ score_threshold: 0.7,+ datasets: { datasets: [] },+ } as DebugContextValue['datasetConfigs'],+ datasetConfigsRef: { current: null } as unknown as DebugContextValue['datasetConfigsRef'],+ setDatasetConfigs: vi.fn(),+ hasSetContextVar: false,+ isShowVisionConfig: false,+ visionConfig: {+ enabled: false,+ number_limits: 2,+ detail: 'low',+ transfer_methods: [],+ } as DebugContextValue['visionConfig'],+ setVisionConfig: vi.fn(),+ isAllowVideoUpload: false,+ isShowDocumentConfig: false,+ isShowAudioConfig: false,+ rerankSettingModalOpen: false,+ setRerankSettingModalOpen: vi.fn(),+ ...overrides,+})++const renderDebug = (options: {+ contextValue?: Partial<DebugContextValue>+ props?: Partial<DebugProps>+} = {}) => {+ const onSetting = vi.fn()+ const notify = vi.fn()+ const props: ComponentProps<typeof Debug> = {+ isAPIKeySet: true,+ onSetting,+ inputs: {},+ modelParameterParams: {+ setModel: vi.fn(),+ onCompletionParamsChange: vi.fn(),+ },+ debugWithMultipleModel: false,+ multipleModelConfigs: [],+ onMultipleModelConfigsChange: vi.fn(),+ ...options.props,+ }++ render(+ <ToastContext.Provider value={{ notify, close: vi.fn() }}>+ <ConfigContext.Provider value={createContextValue(options.contextValue)}>+ <Debug {...props} />+ </ConfigContext.Provider>+ </ToastContext.Provider>,+ )++ return { onSetting, notify, props }+}++describe('Debug', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockState.mockSendCompletionMessage.mockReset()+ mockState.mockHandleRestart.mockReset()+ mockState.mockSetFeatures.mockReset()+ mockState.mockEventEmitterEmit.mockReset()+ mockState.mockText2speechDefaultModel = null+ mockState.mockStoreState = {+ currentLogItem: null,+ setCurrentLogItem: vi.fn(),+ showPromptLogModal: false,+ setShowPromptLogModal: vi.fn(),+ showAgentLogModal: false,+ setShowAgentLogModal: vi.fn(),+ }+ mockState.mockFeaturesState = {+ moreLikeThis: { enabled: false },+ moderation: { enabled: false },+ text2speech: { enabled: false },+ file: { enabled: false, allowed_file_upload_methods: [], fileUploadConfig: undefined },+ }+ mockState.mockProviderContext = {+ textGenerationModelList: [{+ provider: 'openai',+ models: [{+ model: 'vision-model',+ features: [ModelFeatureEnum.vision],+ model_properties: { mode: 'chat' },+ }],+ }],+ }+ })++ describe('Empty states', () => {+ it('should render no-provider empty state and forward manage action', () => {+ const { onSetting } = renderDebug({+ contextValue: {+ modelConfig: {+ ...createContextValue().modelConfig,+ provider: '',+ model_id: '',+ },+ },+ props: {+ isAPIKeySet: false,+ },+ })++ expect(screen.getByText('appDebug.noModelProviderConfigured')).toBeInTheDocument()+ expect(screen.getByText('appDebug.noModelProviderConfiguredTip')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'appDebug.manageModels' }))+ expect(onSetting).toHaveBeenCalledTimes(1)+ })++ it('should render no-model-selected empty state when provider exists but model is missing', () => {+ renderDebug({+ contextValue: {+ modelConfig: {+ ...createContextValue().modelConfig,+ provider: 'openai',+ model_id: '',+ },+ },+ props: {+ isAPIKeySet: true,+ },+ })++ expect(screen.getByText('appDebug.noModelSelected')).toBeInTheDocument()+ expect(screen.getByText('appDebug.noModelSelectedTip')).toBeInTheDocument()+ expect(screen.queryByText('appDebug.noModelProviderConfigured')).not.toBeInTheDocument()+ })+ })++ describe('Single model mode', () => {+ it('should render single-model panel and refresh conversation', () => {+ renderDebug()++ expect(screen.getByTestId('debug-with-single-model')).toBeInTheDocument()++ fireEvent.click(screen.getAllByTestId('action-button')[0])+ expect(mockState.mockHandleRestart).toHaveBeenCalledTimes(1)+ })++ it('should toggle chat input visibility when variable panel button is clicked', () => {+ renderDebug({+ contextValue: {+ inputs: { question: 'hello' },+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [{+ key: 'question',+ name: 'Question',+ type: 'string',+ required: true,+ }] as DebugContextValue['modelConfig']['configs']['prompt_variables'],+ },+ },+ },+ })++ expect(screen.getByTestId('chat-user-input')).toBeInTheDocument()+ fireEvent.click(screen.getAllByTestId('action-button')[1])+ expect(screen.queryByTestId('chat-user-input')).not.toBeInTheDocument()+ })++ it('should not render refresh action when readonly is true', () => {+ renderDebug({+ contextValue: {+ readonly: true,+ },+ })++ expect(screen.queryByTestId('action-button')).not.toBeInTheDocument()+ })++ it('should show formatting confirmation and handle cancel', () => {+ const setFormattingChanged = vi.fn()++ renderDebug({+ contextValue: {+ formattingChanged: true,+ setFormattingChanged,+ },+ })++ expect(screen.getByTestId('formatting-changed')).toBeInTheDocument()+ fireEvent.click(screen.getByTestId('formatting-cancel'))+ expect(setFormattingChanged).toHaveBeenCalledWith(false)+ })++ it('should handle formatting confirmation with restart', () => {+ const setFormattingChanged = vi.fn()++ renderDebug({+ contextValue: {+ formattingChanged: true,+ setFormattingChanged,+ },+ })++ fireEvent.click(screen.getByTestId('formatting-confirm'))+ expect(setFormattingChanged).toHaveBeenCalledWith(false)+ expect(mockState.mockHandleRestart).toHaveBeenCalledTimes(1)+ })++ it('should notify when history block is missing in advanced completion mode', () => {+ const { notify } = renderDebug({+ contextValue: {+ isAdvancedMode: true,+ mode: AppModeEnum.CHAT,+ modelModeType: ModelModeType.completion,+ hasSetBlockStatus: { context: false, history: false, query: true },+ },+ })++ fireEvent.click(screen.getByTestId('single-check-can-send'))+ expect(notify).toHaveBeenCalledWith({+ type: 'error',+ message: 'appDebug.otherError.historyNoBeEmpty',+ })+ })++ it('should notify when query block is missing in advanced completion mode', () => {+ const { notify } = renderDebug({+ contextValue: {+ isAdvancedMode: true,+ mode: AppModeEnum.CHAT,+ modelModeType: ModelModeType.completion,+ hasSetBlockStatus: { context: false, history: true, query: false },+ },+ })++ fireEvent.click(screen.getByTestId('single-check-can-send'))+ expect(notify).toHaveBeenCalledWith({+ type: 'error',+ message: 'appDebug.otherError.queryNoBeEmpty',+ })+ })+ })++ describe('Completion mode', () => {+ it('should render prompt value panel and no-result placeholder', () => {+ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ },+ })++ expect(screen.getByTestId('prompt-value-panel')).toBeInTheDocument()+ expect(screen.getByText('appDebug.noResult')).toBeInTheDocument()+ })++ it('should notify when required input is missing', () => {+ const { notify } = renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ inputs: {},+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [{+ key: 'question',+ name: 'Question',+ type: 'string',+ required: true,+ }] as DebugContextValue['modelConfig']['configs']['prompt_variables'],+ },+ },+ },+ })++ fireEvent.click(screen.getByTestId('panel-send'))+ expect(notify).toHaveBeenCalledWith({+ type: 'error',+ message: 'appDebug.errorMessage.valueOfVarRequired:{"key":"Question"}',+ })+ expect(mockState.mockSendCompletionMessage).not.toHaveBeenCalled()+ })++ it('should notify when local file upload is still pending', () => {+ const { notify } = renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [],+ },+ },+ },+ })++ fireEvent.click(screen.getByTestId('panel-set-pending-file'))+ fireEvent.click(screen.getByTestId('panel-send'))++ expect(notify).toHaveBeenCalledWith({+ type: 'info',+ message: 'appDebug.errorMessage.waitForFileUpload',+ })+ expect(mockState.mockSendCompletionMessage).not.toHaveBeenCalled()+ })++ it('should show cannot-query-dataset warning when dataset context variable is missing', () => {+ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ dataSets: [{ id: 'dataset-1' }] as DebugContextValue['dataSets'],+ hasSetContextVar: false,+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [],+ },+ },+ },+ })++ fireEvent.click(screen.getByTestId('panel-send'))+ expect(screen.getByTestId('cannot-query-dataset')).toBeInTheDocument()++ fireEvent.click(screen.getByTestId('cannot-query-confirm'))+ expect(screen.queryByTestId('cannot-query-dataset')).not.toBeInTheDocument()+ })++ it('should send completion request and render completion result', async () => {+ mockState.mockText2speechDefaultModel = { provider: 'openai' }+ mockState.mockFeaturesState = {+ ...mockState.mockFeaturesState,+ text2speech: { enabled: true },+ file: {+ enabled: true,+ allowed_file_upload_methods: [],+ fileUploadConfig: { image_file_size_limit: 2 },+ },+ }++ mockState.mockSendCompletionMessage.mockImplementation((_appId, _data, handlers: {+ onData: (chunk: string, isFirst: boolean, payload: { messageId: string }) => void+ onMessageReplace: (payload: { answer: string }) => void+ onCompleted: () => void+ onError: () => void+ }) => {+ handlers.onData('hello', true, { messageId: 'msg-1' })+ handlers.onMessageReplace({ answer: 'final answer' })+ handlers.onCompleted()+ })++ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ promptMode: 'simple' as DebugContextValue['promptMode'],+ textToSpeechConfig: { enabled: true, voice: 'alloy', language: 'en' },+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: 'Prompt',+ prompt_variables: [{+ key: 'question',+ name: 'Question',+ type: 'string',+ required: true,+ is_context_var: true,+ }] as DebugContextValue['modelConfig']['configs']['prompt_variables'],+ },+ },+ },+ props: {+ inputs: { question: 'hello' },+ },+ })++ fireEvent.click(screen.getByTestId('panel-send'))++ await waitFor(() => expect(mockState.mockSendCompletionMessage).toHaveBeenCalledTimes(1))+ const [, requestData] = mockState.mockSendCompletionMessage.mock.calls[0]+ expect(requestData).toMatchObject({+ inputs: { question: 'hello' },+ model_config: {+ model: {+ provider: 'openai',+ name: 'gpt-4',+ },+ dataset_query_variable: 'question',+ },+ })+ expect(screen.getByTestId('text-generation')).toHaveTextContent('final answer')+ expect(screen.getByTestId('text-generation')).toHaveAttribute('data-message-id', 'msg-1')+ expect(screen.getByTestId('text-generation')).toHaveAttribute('data-tts', 'true')+ })++ it('should notify when sending again while a response is in progress', async () => {+ mockState.mockSendCompletionMessage.mockImplementation(() => undefined)+ const { notify } = renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [],+ },+ },+ },+ })++ fireEvent.click(screen.getByTestId('panel-send'))+ fireEvent.click(screen.getByTestId('panel-send'))++ await waitFor(() => expect(mockState.mockSendCompletionMessage).toHaveBeenCalledTimes(1))+ expect(notify).toHaveBeenCalledWith({+ type: 'info',+ message: 'appDebug.errorMessage.waitForResponse',+ })+ })++ it('should keep remote files and reset responding state on send error', async () => {+ mockState.mockFeaturesState = {+ ...mockState.mockFeaturesState,+ file: {+ enabled: true,+ allowed_file_upload_methods: [],+ fileUploadConfig: undefined,+ },+ }++ mockState.mockSendCompletionMessage.mockImplementation((_appId, data, handlers: {+ onError: () => void+ }) => {+ expect(data.files).toEqual([{+ transfer_method: TransferMethod.remote_url,+ url: 'https://example.com/file.png',+ }])+ handlers.onError()+ })++ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [],+ },+ },+ },+ })++ fireEvent.click(screen.getByTestId('panel-set-remote-file'))+ fireEvent.click(screen.getByTestId('panel-send'))++ await waitFor(() => expect(mockState.mockSendCompletionMessage).toHaveBeenCalledTimes(1))+ expect(screen.getByText('appDebug.noResult')).toBeInTheDocument()+ })++ it('should render prompt log modal in completion mode when store flag is enabled', () => {+ mockState.mockStoreState = {+ ...mockState.mockStoreState,+ showPromptLogModal: true,+ }++ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ },+ })++ expect(screen.getByTestId('prompt-log-modal')).toBeInTheDocument()+ })++ it('should close prompt log modal in completion mode', () => {+ const setCurrentLogItem = vi.fn()+ const setShowPromptLogModal = vi.fn()++ mockState.mockStoreState = {+ ...mockState.mockStoreState,+ currentLogItem: { id: 'log-1' },+ setCurrentLogItem,+ showPromptLogModal: true,+ setShowPromptLogModal,+ }++ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ },+ })++ fireEvent.click(screen.getByTestId('prompt-log-cancel'))+ expect(setCurrentLogItem).toHaveBeenCalledTimes(1)+ expect(setShowPromptLogModal).toHaveBeenCalledWith(false)+ })+ })++ describe('Multiple model mode', () => {+ it('should append a blank model when add-model button is clicked', () => {+ const onMultipleModelConfigsChange = vi.fn()++ renderDebug({+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: 'model-1', model: 'vision-model', provider: 'openai', parameters: {} }],+ onMultipleModelConfigsChange,+ },+ })++ fireEvent.click(screen.getByRole('button', { name: 'common.modelProvider.addModel(1/4)' }))+ expect(onMultipleModelConfigsChange).toHaveBeenCalledWith(true, [+ { id: 'model-1', model: 'vision-model', provider: 'openai', parameters: {} },+ expect.objectContaining({ model: '', provider: '', parameters: {} }),+ ])+ })++ it('should disable add-model button when there are already four models', () => {+ renderDebug({+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [+ { id: '1', model: 'a', provider: 'p', parameters: {} },+ { id: '2', model: 'b', provider: 'p', parameters: {} },+ { id: '3', model: 'c', provider: 'p', parameters: {} },+ { id: '4', model: 'd', provider: 'p', parameters: {} },+ ],+ },+ })++ expect(screen.getByRole('button', { name: 'common.modelProvider.addModel(4/4)' })).toBeDisabled()+ })++ it('should emit completion event in multiple-model completion mode', () => {+ renderDebug({+ contextValue: {+ mode: AppModeEnum.COMPLETION,+ modelConfig: {+ ...createContextValue().modelConfig,+ configs: {+ prompt_template: '',+ prompt_variables: [],+ },+ },+ },+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: '1', model: 'vision-model', provider: 'openai', parameters: {} }],+ },+ })++ fireEvent.click(screen.getByTestId('panel-set-uploaded-file'))+ fireEvent.click(screen.getByTestId('panel-send'))++ expect(mockState.mockEventEmitterEmit).toHaveBeenCalledWith({+ type: APP_CHAT_WITH_MULTIPLE_MODEL,+ payload: {+ message: '',+ files: [{ transfer_method: TransferMethod.local_file, upload_file_id: 'file-id' }],+ },+ })+ })++ it('should emit restart event when refresh is clicked in multiple-model mode', () => {+ renderDebug({+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: '1', model: 'vision-model', provider: 'openai', parameters: {} }],+ },+ })++ fireEvent.click(screen.getAllByTestId('action-button')[0])+ expect(mockState.mockEventEmitterEmit).toHaveBeenCalledWith({+ type: APP_CHAT_WITH_MULTIPLE_MODEL_RESTART,+ })+ })++ it('should switch from multiple model to single model with selected parameters', () => {+ const setModel = vi.fn()+ const onCompletionParamsChange = vi.fn()+ const onMultipleModelConfigsChange = vi.fn()++ renderDebug({+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: 'model-1', model: 'vision-model', provider: 'openai', parameters: { temperature: 0.2 } }],+ onMultipleModelConfigsChange,+ modelParameterParams: {+ setModel,+ onCompletionParamsChange,+ },+ },+ })++ fireEvent.click(screen.getByTestId('multiple-switch-to-single'))++ expect(setModel).toHaveBeenCalledWith({+ modelId: 'vision-model',+ provider: 'openai',+ mode: 'chat',+ features: [ModelFeatureEnum.vision],+ })+ expect(onCompletionParamsChange).toHaveBeenCalledWith({ temperature: 0.2 })+ expect(onMultipleModelConfigsChange).toHaveBeenCalledWith(false, [])+ })++ it('should update feature store according to multiple-model vision support', () => {+ renderDebug({+ contextValue: {+ mode: AppModeEnum.CHAT,+ },+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: '1', model: 'vision-model', provider: 'openai', parameters: {} }],+ },+ })++ expect(mockState.mockSetFeatures).toHaveBeenCalledWith(expect.objectContaining({+ file: expect.objectContaining({+ enabled: true,+ }),+ }))+ })++ it('should render prompt and agent log modals in multiple-model mode', () => {+ mockState.mockStoreState = {+ ...mockState.mockStoreState,+ showPromptLogModal: true,+ showAgentLogModal: true,+ }++ renderDebug({+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: '1', model: 'vision-model', provider: 'openai', parameters: {} }],+ },+ })++ expect(screen.getByTestId('prompt-log-modal')).toBeInTheDocument()+ expect(screen.getByTestId('agent-log-modal')).toBeInTheDocument()+ })++ it('should close prompt and agent log modals in multiple-model mode', () => {+ const setCurrentLogItem = vi.fn()+ const setShowPromptLogModal = vi.fn()+ const setShowAgentLogModal = vi.fn()++ mockState.mockStoreState = {+ ...mockState.mockStoreState,+ currentLogItem: { id: 'log-1' },+ setCurrentLogItem,+ showPromptLogModal: true,+ setShowPromptLogModal,+ showAgentLogModal: true,+ setShowAgentLogModal,+ }++ renderDebug({+ props: {+ debugWithMultipleModel: true,+ multipleModelConfigs: [{ id: '1', model: 'vision-model', provider: 'openai', parameters: {} }],+ },+ })++ fireEvent.click(screen.getByTestId('prompt-log-cancel'))+ fireEvent.click(screen.getByTestId('agent-log-cancel'))++ expect(setCurrentLogItem).toHaveBeenCalledTimes(2)+ expect(setShowPromptLogModal).toHaveBeenCalledWith(false)+ expect(setShowAgentLogModal).toHaveBeenCalledWith(false)+ })+ })+})diff --git a/web/app/components/app/configuration/debug/index.tsx b/web/app/components/app/configuration/debug/index.tsxindex 1a6f9e264f8..cd07885f0cb 100644--- a/web/app/components/app/configuration/debug/index.tsx+++ b/web/app/components/app/configuration/debug/index.tsx@@ -33,7 +33,7 @@ import { ToastContext } from '@/app/components/base/toast/context'import TooltipPlus from '@/app/components/base/tooltip'import { ModelFeatureEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'-import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG, IS_CE_EDITION } from '@/config'+import { DEFAULT_CHAT_PROMPT_CONFIG, DEFAULT_COMPLETION_PROMPT_CONFIG } from '@/config'import ConfigContext from '@/context/debug-configuration'import { useEventEmitterContextContext } from '@/context/event-emitter'import { useProviderContext } from '@/context/provider-context'@@ -394,7 +394,7 @@ const Debug: FC<IDebug> = ({<><div className="shrink-0"><div className="flex items-center justify-between px-4 pb-2 pt-3">- <div className="system-xl-semibold text-text-primary">{t('inputs.title', { ns: 'appDebug' })}</div>+ <div className="text-text-primary system-xl-semibold">{t('inputs.title', { ns: 'appDebug' })}</div><div className="flex items-center">{debugWithMultipleModel@@ -505,6 +505,26 @@ const Debug: FC<IDebug> = ({{!debugWithMultipleModel && (<div className="flex grow flex-col" ref={ref}>+ {/* No model provider configured */}+ {(!modelConfig.provider || !isAPIKeySet) && (+ <HasNotSetAPIKEY onSetting={onSetting} />+ )}+ {/* No model selected */}+ {modelConfig.provider && isAPIKeySet && !modelConfig.model_id && (+ <div className="flex grow flex-col items-center justify-center pb-[120px]">+ <div className="flex w-full max-w-[400px] flex-col gap-2 px-4 py-4">+ <div className="flex h-10 w-10 items-center justify-center rounded-[10px]">+ <div className="flex h-full w-full items-center justify-center overflow-hidden rounded-[10px] border-[0.5px] border-components-card-border bg-components-card-bg p-1 shadow-lg backdrop-blur-[5px]">+ <span className="i-ri-brain-2-line h-5 w-5 text-text-tertiary" />+ </div>+ </div>+ <div className="flex flex-col gap-1">+ <div className="text-text-secondary system-md-semibold">{t('noModelSelected', { ns: 'appDebug' })}</div>+ <div className="text-text-tertiary system-xs-regular">{t('noModelSelectedTip', { ns: 'appDebug' })}</div>+ </div>+ </div>+ </div>+ )}{/* Chat */}{mode !== AppModeEnum.COMPLETION && (<div className="h-0 grow overflow-hidden">@@ -539,7 +559,7 @@ const Debug: FC<IDebug> = ({{!completionRes && !isResponding && (<div className="flex grow flex-col items-center justify-center gap-2"><RiSparklingFill className="h-12 w-12 text-text-empty-state-icon" />- <div className="system-sm-regular text-text-quaternary">{t('noResult', { ns: 'appDebug' })}</div>+ <div className="text-text-quaternary system-sm-regular">{t('noResult', { ns: 'appDebug' })}</div></div>)}</>@@ -570,7 +590,6 @@ const Debug: FC<IDebug> = ({/>)}- {!isAPIKeySet && !readonly && (<HasNotSetAPIKEY isTrailFinished={!IS_CE_EDITION} onSetting={onSetting} />)}</>)}diff --git a/web/app/components/app/configuration/index.tsx b/web/app/components/app/configuration/index.tsxindex a39eb3c63ef..0e6ffb1e846 100644--- a/web/app/components/app/configuration/index.tsx+++ b/web/app/components/app/configuration/index.tsx@@ -966,10 +966,10 @@ const Configuration: FC = () => {<div className="bg-default-subtle absolute left-0 top-0 h-14 w-full"><div className="flex h-14 items-center justify-between px-6"><div className="flex items-center">- <div className="system-xl-semibold text-text-primary">{t('orchestrate', { ns: 'appDebug' })}</div>+ <div className="text-text-primary system-xl-semibold">{t('orchestrate', { ns: 'appDebug' })}</div><div className="flex h-[14px] items-center space-x-1 text-xs">{isAdvancedMode && (- <div className="system-xs-medium-uppercase ml-1 flex h-5 items-center rounded-md border border-components-button-secondary-border px-1.5 uppercase text-text-tertiary">{t('promptMode.advanced', { ns: 'appDebug' })}</div>+ <div className="ml-1 flex h-5 items-center rounded-md border border-components-button-secondary-border px-1.5 uppercase text-text-tertiary system-xs-medium-uppercase">{t('promptMode.advanced', { ns: 'appDebug' })}</div>)}</div></div>@@ -1030,8 +1030,8 @@ const Configuration: FC = () => {<Config /></div>{!isMobile && (- <div className="relative flex h-full w-1/2 grow flex-col overflow-y-auto " style={{ borderColor: 'rgba(0, 0, 0, 0.02)' }}>- <div className="flex grow flex-col rounded-tl-2xl border-l-[0.5px] border-t-[0.5px] border-components-panel-border bg-chatbot-bg ">+ <div className="relative flex h-full w-1/2 grow flex-col overflow-y-auto" style={{ borderColor: 'rgba(0, 0, 0, 0.02)' }}>+ <div className="flex grow flex-col rounded-tl-2xl border-l-[0.5px] border-t-[0.5px] border-components-panel-border bg-chatbot-bg"><DebugisAPIKeySet={isAPIKeySet}onSetting={() => setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })}diff --git a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx b/web/app/components/app/configuration/tools/external-data-tool-modal.tsxindex 35ba59a5fb2..dd7a0c6a6cc 100644--- a/web/app/components/app/configuration/tools/external-data-tool-modal.tsx+++ b/web/app/components/app/configuration/tools/external-data-tool-modal.tsx@@ -217,7 +217,7 @@ const ExternalDataToolModal: FC<ExternalDataToolModalProps> = ({<AppIconsize="large"onClick={() => { setShowEmojiPicker(true) }}- className="!h-9 !w-9 cursor-pointer rounded-lg border-[0.5px] border-components-panel-border "+ className="!h-9 !w-9 cursor-pointer rounded-lg border-[0.5px] border-components-panel-border"icon={localeData.icon}background={localeData.icon_background}/>diff --git a/web/app/components/app/create-from-dsl-modal/index.tsx b/web/app/components/app/create-from-dsl-modal/index.tsxindex a542ef059fd..a0c8360c29a 100644--- a/web/app/components/app/create-from-dsl-modal/index.tsx+++ b/web/app/components/app/create-from-dsl-modal/index.tsx@@ -232,7 +232,7 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSisShow={show}onClose={noop}>- <div className="title-2xl-semi-bold flex items-center justify-between pb-3 pl-6 pr-5 pt-6 text-text-primary">+ <div className="flex items-center justify-between pb-3 pl-6 pr-5 pt-6 text-text-primary title-2xl-semi-bold">{t('importFromDSL', { ns: 'app' })}<divclassName="flex h-8 w-8 cursor-pointer items-center"@@ -241,7 +241,7 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS<RiCloseLine className="h-5 w-5 text-text-tertiary" /></div></div>- <div className="system-md-semibold flex h-9 items-center space-x-6 border-b border-divider-subtle px-6 text-text-tertiary">+ <div className="flex h-9 items-center space-x-6 border-b border-divider-subtle px-6 text-text-tertiary system-md-semibold">{tabs.map(tab => (<div@@ -275,7 +275,7 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDS{currentTab === CreateFromDSLModalTab.FROM_URL && (<div>- <div className="system-md-semibold mb-1 text-text-secondary">DSL URL</div>+ <div className="mb-1 text-text-secondary system-md-semibold">DSL URL</div><Inputplaceholder={t('importFromDSLUrlPlaceholder', { ns: 'app' }) || ''}value={dslUrlValue}@@ -309,8 +309,8 @@ const CreateFromDSLModal = ({ show, onSuccess, onClose, activeTab = CreateFromDSclassName="w-[480px]"><div className="flex flex-col items-start gap-2 self-stretch pb-4">- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>- <div className="system-md-regular flex grow flex-col text-text-secondary">+ <div className="text-text-primary title-2xl-semi-bold">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>+ <div className="flex grow flex-col text-text-secondary system-md-regular"><div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div><div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div><br />diff --git a/web/app/components/app/create-from-dsl-modal/uploader.tsx b/web/app/components/app/create-from-dsl-modal/uploader.tsxindex 6b7ca4db61b..74c8e5f48ec 100644--- a/web/app/components/app/create-from-dsl-modal/uploader.tsx+++ b/web/app/components/app/create-from-dsl-modal/uploader.tsx@@ -121,7 +121,7 @@ const Uploader: FC<Props> = ({</div>)}{file && (- <div className={cn('group flex items-center rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs', ' hover:bg-components-panel-on-panel-item-bg-hover')}>+ <div className={cn('group flex items-center rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-on-panel-item-bg shadow-xs', 'hover:bg-components-panel-on-panel-item-bg-hover')}><div className="flex items-center justify-center p-3"><YamlIcon className="h-6 w-6 shrink-0" /></div>diff --git a/web/app/components/app/log/list.tsx b/web/app/components/app/log/list.tsxindex 4eb733a02cb..146af44a10d 100644--- a/web/app/components/app/log/list.tsx+++ b/web/app/components/app/log/list.tsx@@ -96,7 +96,7 @@ const statusTdRender = (statusCount: StatusCount) => {if (statusCount.paused > 0) {return (- <div className="system-xs-semibold-uppercase inline-flex items-center gap-1">+ <div className="inline-flex items-center gap-1 system-xs-semibold-uppercase"><Indicator color="yellow" /><span className="text-util-colors-warning-warning-600">Pending</span></div>@@ -104,7 +104,7 @@ const statusTdRender = (statusCount: StatusCount) => {}else if (statusCount.partial_success + statusCount.failed === 0) {return (- <div className="system-xs-semibold-uppercase inline-flex items-center gap-1">+ <div className="inline-flex items-center gap-1 system-xs-semibold-uppercase"><Indicator color="green" /><span className="text-util-colors-green-green-600">Success</span></div>@@ -112,7 +112,7 @@ const statusTdRender = (statusCount: StatusCount) => {}else if (statusCount.failed === 0) {return (- <div className="system-xs-semibold-uppercase inline-flex items-center gap-1">+ <div className="inline-flex items-center gap-1 system-xs-semibold-uppercase"><Indicator color="green" /><span className="text-util-colors-green-green-600">Partial Success</span></div>@@ -120,7 +120,7 @@ const statusTdRender = (statusCount: StatusCount) => {}else {return (- <div className="system-xs-semibold-uppercase inline-flex items-center gap-1">+ <div className="inline-flex items-center gap-1 system-xs-semibold-uppercase"><Indicator color="red" /><span className="text-util-colors-red-red-600">{statusCount.failed}@@ -562,9 +562,9 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {{/* Panel Header */}<div className="flex shrink-0 items-center gap-2 rounded-t-xl bg-components-panel-bg pb-2 pl-4 pr-3 pt-3"><div className="shrink-0">- <div className="system-xs-semibold-uppercase mb-0.5 text-text-primary">{isChatMode ? t('detail.conversationId', { ns: 'appLog' }) : t('detail.time', { ns: 'appLog' })}</div>+ <div className="mb-0.5 text-text-primary system-xs-semibold-uppercase">{isChatMode ? t('detail.conversationId', { ns: 'appLog' }) : t('detail.time', { ns: 'appLog' })}</div>{isChatMode && (- <div className="system-2xs-regular-uppercase flex items-center text-text-secondary">+ <div className="flex items-center text-text-secondary system-2xs-regular-uppercase"><TooltippopupContent={detail.id}>@@ -574,7 +574,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {</div>)}{!isChatMode && (- <div className="system-2xs-regular-uppercase text-text-secondary">{formatTime(detail.created_at, t('dateTimeFormat', { ns: 'appLog' }) as string)}</div>+ <div className="text-text-secondary system-2xs-regular-uppercase">{formatTime(detail.created_at, t('dateTimeFormat', { ns: 'appLog' }) as string)}</div>)}</div><div className="flex grow flex-wrap items-center justify-end gap-y-1">@@ -600,7 +600,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {? (<div className="px-6 py-4"><div className="flex h-[18px] items-center space-x-3">- <div className="system-xs-semibold-uppercase text-text-tertiary">{t('table.header.output', { ns: 'appLog' })}</div>+ <div className="text-text-tertiary system-xs-semibold-uppercase">{t('table.header.output', { ns: 'appLog' })}</div><divclassName="h-px grow"style={{@@ -692,7 +692,7 @@ function DetailPanel({ detail, onFeedback }: IDetailPanel) {</div>{hasMore && (<div className="py-3 text-center">- <div className="system-xs-regular text-text-tertiary">+ <div className="text-text-tertiary system-xs-regular">{t('detail.loading', { ns: 'appLog' })}...</div>@@ -950,7 +950,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh }))}popupClassName={(isHighlight && !isChatMode) ? '' : '!hidden'}>- <div className={cn(isEmptyStyle ? 'text-text-quaternary' : 'text-text-secondary', !isHighlight ? '' : 'bg-orange-100', 'system-sm-regular overflow-hidden text-ellipsis whitespace-nowrap')}>+ <div className={cn(isEmptyStyle ? 'text-text-quaternary' : 'text-text-secondary', !isHighlight ? '' : 'bg-orange-100', 'overflow-hidden text-ellipsis whitespace-nowrap system-sm-regular')}>{value || '-'}</div></Tooltip>@@ -963,7 +963,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })return (<div className="relative mt-2 grow overflow-x-auto"><table className={cn('w-full min-w-[440px] border-collapse border-0')}>- <thead className="system-xs-medium-uppercase text-text-tertiary">+ <thead className="text-text-tertiary system-xs-medium-uppercase"><tr><td className="w-5 whitespace-nowrap rounded-l-lg bg-background-section-burn pl-2 pr-1"></td><td className="whitespace-nowrap bg-background-section-burn py-1.5 pl-3">{isChatMode ? t('table.header.summary', { ns: 'appLog' }) : t('table.header.input', { ns: 'appLog' })}</td>@@ -976,7 +976,7 @@ const ConversationList: FC<IConversationList> = ({ logs, appDetail, onRefresh })<td className="whitespace-nowrap rounded-r-lg bg-background-section-burn py-1.5 pl-3">{t('table.header.time', { ns: 'appLog' })}</td></tr></thead>- <tbody className="system-sm-regular text-text-secondary">+ <tbody className="text-text-secondary system-sm-regular">{logs.data.map((log: any) => {const endUser = log.from_end_user_session_id || log.from_account_nameconst leftValue = get(log, isChatMode ? 'name' : 'message.inputs.query') || (!isChatMode ? (get(log, 'message.query') || get(log, 'message.inputs.default_input')) : '') || ''diff --git a/web/app/components/base/icons/assets/vender/line/financeAndECommerce/credits-coin.svg b/web/app/components/base/icons/assets/vender/line/financeAndECommerce/credits-coin.svgnew file mode 100644index 00000000000..bee018ba2fe--- /dev/null+++ b/web/app/components/base/icons/assets/vender/line/financeAndECommerce/credits-coin.svg@@ -0,0 +1,4 @@+<svg width="10" height="10" viewBox="0 0 10 10" fill="none" xmlns="http://www.w3.org/2000/svg">+<path d="M2 5C2 3.44487 2.58482 1.98537 3.54004 1.04932C2.17681 1.34034 1 2.90001 1 5C1 7.09996 2.17685 8.65912 3.54004 8.9502C2.58496 8.01413 2 6.55501 2 5ZM3 5C3 7.33338 4.4528 9 6 9C7.5472 9 9 7.33338 9 5C9 2.66664 7.5472 1 6 1C4.4528 1 3 2.66664 3 5ZM10 5C10 7.63722 8.3188 10 6 10H4C1.6812 10 0 7.63722 0 5C0 2.3628 1.6812 0 4 0H6C8.3188 0 10 2.3628 10 5Z" fill="#676F83"/>+<path d="M6.71519 4.09259L6.45385 3.18667C6.42141 3.07421 6.34037 3 6.25 3C6.15963 3 6.07859 3.07421 6.04615 3.18667L5.78481 4.09259C5.74675 4.22464 5.66849 4.32899 5.56945 4.37978L4.88999 4.7282C4.80565 4.77146 4.75 4.87951 4.75 5C4.75 5.12049 4.80565 5.22854 4.88999 5.2718L5.56945 5.62022C5.66849 5.67101 5.74675 5.77536 5.78481 5.90741L6.04615 6.81333C6.07859 6.92579 6.15963 7 6.25 7C6.34037 7 6.42141 6.92579 6.45385 6.81333L6.71519 5.90741C6.75325 5.77536 6.83151 5.67101 6.93055 5.62022L7.61001 5.2718C7.69435 5.22854 7.75 5.12049 7.75 5C7.75 4.87951 7.69435 4.77146 7.61001 4.7282L6.93055 4.37978C6.83151 4.32899 6.75325 4.22464 6.71519 4.09259Z" fill="#676F83"/>+</svg>diff --git a/web/app/components/base/icons/assets/vender/solid/general/arrow-down-round-fill.svg b/web/app/components/base/icons/assets/vender/solid/general/arrow-down-round-fill.svgindex 9566fcc0c3c..ac9908a85a2 100644--- a/web/app/components/base/icons/assets/vender/solid/general/arrow-down-round-fill.svg+++ b/web/app/components/base/icons/assets/vender/solid/general/arrow-down-round-fill.svg@@ -1,5 +1,5 @@<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="arrow-down-round-fill">-<path id="Vector" d="M6.02913 6.23572C5.08582 6.23572 4.56482 7.33027 5.15967 8.06239L7.13093 10.4885C7.57922 11.0403 8.42149 11.0403 8.86986 10.4885L10.8411 8.06239C11.4359 7.33027 10.9149 6.23572 9.97158 6.23572H6.02913Z" fill="#101828"/>+<path id="Vector" d="M6.02913 6.23572C5.08582 6.23572 4.56482 7.33027 5.15967 8.06239L7.13093 10.4885C7.57922 11.0403 8.42149 11.0403 8.86986 10.4885L10.8411 8.06239C11.4359 7.33027 10.9149 6.23572 9.97158 6.23572H6.02913Z" fill="currentColor"/></g></svg>diff --git a/web/app/components/base/icons/assets/vender/solid/general/x-circle.svg b/web/app/components/base/icons/assets/vender/solid/general/x-circle.svgindex 5acbe5f562c..fd4461dae24 100644--- a/web/app/components/base/icons/assets/vender/solid/general/x-circle.svg+++ b/web/app/components/base/icons/assets/vender/solid/general/x-circle.svg@@ -1,3 +1,3 @@<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">-<path id="Solid" fill-rule="evenodd" clip-rule="evenodd" d="M8.00008 0.666016C3.94999 0.666016 0.666748 3.94926 0.666748 7.99935C0.666748 12.0494 3.94999 15.3327 8.00008 15.3327C12.0502 15.3327 15.3334 12.0494 15.3334 7.99935C15.3334 3.94926 12.0502 0.666016 8.00008 0.666016ZM10.4715 5.52794C10.7318 5.78829 10.7318 6.2104 10.4715 6.47075L8.94289 7.99935L10.4715 9.52794C10.7318 9.78829 10.7318 10.2104 10.4715 10.4708C10.2111 10.7311 9.78903 10.7311 9.52868 10.4708L8.00008 8.94216L6.47149 10.4708C6.21114 10.7311 5.78903 10.7311 5.52868 10.4708C5.26833 10.2104 5.26833 9.78829 5.52868 9.52794L7.05727 7.99935L5.52868 6.47075C5.26833 6.2104 5.26833 5.78829 5.52868 5.52794C5.78903 5.26759 6.21114 5.26759 6.47149 5.52794L8.00008 7.05654L9.52868 5.52794C9.78903 5.26759 10.2111 5.26759 10.4715 5.52794Z" fill="#98A2B3"/>+<path id="Solid" fill-rule="evenodd" clip-rule="evenodd" d="M8.00008 0.666016C3.94999 0.666016 0.666748 3.94926 0.666748 7.99935C0.666748 12.0494 3.94999 15.3327 8.00008 15.3327C12.0502 15.3327 15.3334 12.0494 15.3334 7.99935C15.3334 3.94926 12.0502 0.666016 8.00008 0.666016ZM10.4715 5.52794C10.7318 5.78829 10.7318 6.2104 10.4715 6.47075L8.94289 7.99935L10.4715 9.52794C10.7318 9.78829 10.7318 10.2104 10.4715 10.4708C10.2111 10.7311 9.78903 10.7311 9.52868 10.4708L8.00008 8.94216L6.47149 10.4708C6.21114 10.7311 5.78903 10.7311 5.52868 10.4708C5.26833 10.2104 5.26833 9.78829 5.52868 9.52794L7.05727 7.99935L5.52868 6.47075C5.26833 6.2104 5.26833 5.78829 5.52868 5.52794C5.78903 5.26759 6.21114 5.26759 6.47149 5.52794L8.00008 7.05654L9.52868 5.52794C9.78903 5.26759 10.2111 5.26759 10.4715 5.52794Z" fill="currentColor"/></svg>diff --git a/web/app/components/base/icons/src/vender/line/financeAndECommerce/CreditsCoin.json b/web/app/components/base/icons/src/vender/line/financeAndECommerce/CreditsCoin.jsonnew file mode 100644index 00000000000..a199f15d361--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/financeAndECommerce/CreditsCoin.json@@ -0,0 +1,35 @@+{+ "icon": {+ "type": "element",+ "isRootNode": true,+ "name": "svg",+ "attributes": {+ "width": "10",+ "height": "10",+ "viewBox": "0 0 10 10",+ "fill": "none",+ "xmlns": "http://www.w3.org/2000/svg"+ },+ "children": [+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M2 5C2 3.44487 2.58482 1.98537 3.54004 1.04932C2.17681 1.34034 1 2.90001 1 5C1 7.09996 2.17685 8.65912 3.54004 8.9502C2.58496 8.01413 2 6.55501 2 5ZM3 5C3 7.33338 4.4528 9 6 9C7.5472 9 9 7.33338 9 5C9 2.66664 7.5472 1 6 1C4.4528 1 3 2.66664 3 5ZM10 5C10 7.63722 8.3188 10 6 10H4C1.6812 10 0 7.63722 0 5C0 2.3628 1.6812 0 4 0H6C8.3188 0 10 2.3628 10 5Z",+ "fill": "currentColor"+ },+ "children": []+ },+ {+ "type": "element",+ "name": "path",+ "attributes": {+ "d": "M6.71519 4.09259L6.45385 3.18667C6.42141 3.07421 6.34037 3 6.25 3C6.15963 3 6.07859 3.07421 6.04615 3.18667L5.78481 4.09259C5.74675 4.22464 5.66849 4.32899 5.56945 4.37978L4.88999 4.7282C4.80565 4.77146 4.75 4.87951 4.75 5C4.75 5.12049 4.80565 5.22854 4.88999 5.2718L5.56945 5.62022C5.66849 5.67101 5.74675 5.77536 5.78481 5.90741L6.04615 6.81333C6.07859 6.92579 6.15963 7 6.25 7C6.34037 7 6.42141 6.92579 6.45385 6.81333L6.71519 5.90741C6.75325 5.77536 6.83151 5.67101 6.93055 5.62022L7.61001 5.2718C7.69435 5.22854 7.75 5.12049 7.75 5C7.75 4.87951 7.69435 4.77146 7.61001 4.7282L6.93055 4.37978C6.83151 4.32899 6.75325 4.22464 6.71519 4.09259Z",+ "fill": "currentColor"+ },+ "children": []+ }+ ]+ },+ "name": "CreditsCoin"+}diff --git a/web/app/components/base/icons/src/vender/line/financeAndECommerce/CreditsCoin.tsx b/web/app/components/base/icons/src/vender/line/financeAndECommerce/CreditsCoin.tsxnew file mode 100644index 00000000000..77b44e78304--- /dev/null+++ b/web/app/components/base/icons/src/vender/line/financeAndECommerce/CreditsCoin.tsx@@ -0,0 +1,20 @@+// GENERATE BY script+// DON NOT EDIT IT MANUALLY++import type { IconData } from '@/app/components/base/icons/IconBase'+import * as React from 'react'+import IconBase from '@/app/components/base/icons/IconBase'+import data from './CreditsCoin.json'++const Icon = (+ {+ ref,+ ...props+ }: React.SVGProps<SVGSVGElement> & {+ ref?: React.RefObject<React.RefObject<HTMLOrSVGElement>>+ },+) => <IconBase {...props} ref={ref} data={data as IconData} />++Icon.displayName = 'CreditsCoin'++export default Icondiff --git a/web/app/components/base/icons/src/vender/line/financeAndECommerce/index.ts b/web/app/components/base/icons/src/vender/line/financeAndECommerce/index.tsindex 2223daa1d50..8a98a4612c3 100644--- a/web/app/components/base/icons/src/vender/line/financeAndECommerce/index.ts+++ b/web/app/components/base/icons/src/vender/line/financeAndECommerce/index.ts@@ -1,5 +1,6 @@export { default as Balance } from './Balance'export { default as CoinsStacked01 } from './CoinsStacked01'+export { default as CreditsCoin } from './CreditsCoin'export { default as GoldCoin } from './GoldCoin'export { default as ReceiptList } from './ReceiptList'export { default as Tag01 } from './Tag01'diff --git a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/variable-block.spec.tsx b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/variable-block.spec.tsxindex c08515d1942..c848d08c5c1 100644--- a/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/variable-block.spec.tsx+++ b/web/app/components/base/prompt-editor/plugins/hitl-input-block/__tests__/variable-block.spec.tsx@@ -53,7 +53,7 @@ const createSelectorWithTransientPrefix = (prefix: string, suffix: string): stri}const hasErrorIcon = (container: HTMLElement) => {- return container.querySelector('svg.text-text-destructive') !== null+ return container.querySelector('svg.text-text-warning') !== null}const renderVariableBlock = (props: {diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsxindex bdeb30d9b69..2b46d1a378b 100644--- a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx@@ -14,7 +14,7 @@ import {} from 'react'import { useTranslation } from 'react-i18next'import { useReactFlow, useStoreApi } from 'reactflow'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { isConversationVar, isENV, isGlobalVar, isRagVariableVar, isSystemVar } from '@/app/components/workflow/nodes/_base/components/variable/utils'import VarFullPathPanel from '@/app/components/workflow/nodes/_base/components/variable/var-full-path-panel'import {@@ -28,6 +28,7 @@ import {UPDATE_WORKFLOW_NODES_MAP,} from './index'import { WorkflowVariableBlockNode } from './node'+import { useLlmModelPluginInstalled } from './use-llm-model-plugin-installed'type WorkflowVariableBlockComponentProps = {nodeKey: string@@ -68,6 +69,8 @@ const WorkflowVariableBlockComponent = ({const node = localWorkflowNodesMap![variables[isRagVar ? 1 : 0]]const isException = isExceptionVariable(varName, node?.type)+ const sourceNodeId = variables[isRagVar ? 1 : 0]+ const isLlmModelInstalled = useLlmModelPluginInstalled(sourceNodeId, localWorkflowNodesMap)const variableValid = useMemo(() => {let variableValid = trueconst isEnv = isENV(variables)@@ -144,7 +147,13 @@ const WorkflowVariableBlockComponent = ({handleVariableJump()}}isExceptionVariable={isException}- errorMsg={!variableValid ? t('errorMsg.invalidVariable', { ns: 'workflow' }) : undefined}+ errorMsg={+ !variableValid+ ? t('errorMsg.invalidVariable', { ns: 'workflow' })+ : !isLlmModelInstalled+ ? t('errorMsg.modelPluginNotInstalled', { ns: 'workflow' })+ : undefined+ }isSelected={isSelected}ref={ref}notShowFullPath={isShowAPart}@@ -155,9 +164,9 @@ const WorkflowVariableBlockComponent = ({return Itemreturn (- <Tooltip- noDecoration- popupContent={(+ <Tooltip>+ <TooltipTrigger disabled={!isShowAPart} render={<div>{Item}</div>} />+ <TooltipContent variant="plain"><VarFullPathPanelnodeName={node.title}path={variables.slice(1)}@@ -169,10 +178,7 @@ const WorkflowVariableBlockComponent = ({: Type.string}nodeType={node?.type}/>- )}- disabled={!isShowAPart}- >- <div>{Item}</div>+ </TooltipContent></Tooltip>)}diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.spec.ts b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.spec.tsnew file mode 100644index 00000000000..f64865317f7--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.spec.ts@@ -0,0 +1,75 @@+import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types'+import { renderHook } from '@testing-library/react'+import { BlockEnum } from '@/app/components/workflow/types'+import { useLlmModelPluginInstalled } from './use-llm-model-plugin-installed'++let mockModelProviders: Array<{ provider: string }> = []++vi.mock('@/context/provider-context', () => ({+ useProviderContextSelector: <T>(selector: (state: { modelProviders: Array<{ provider: string }> }) => T): T =>+ selector({ modelProviders: mockModelProviders }),+}))++const createWorkflowNodesMap = (node: Record<string, unknown>): WorkflowNodesMap =>+ ({+ target: {+ title: 'Target',+ type: BlockEnum.Start,+ ...node,+ },+ } as unknown as WorkflowNodesMap)++describe('useLlmModelPluginInstalled', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockModelProviders = []+ })++ it('should return true when the node is missing', () => {+ const { result } = renderHook(() => useLlmModelPluginInstalled('target', undefined))++ expect(result.current).toBe(true)+ })++ it('should return true when the node is not an LLM node', () => {+ const workflowNodesMap = createWorkflowNodesMap({+ id: 'target',+ type: BlockEnum.Start,+ })++ const { result } = renderHook(() => useLlmModelPluginInstalled('target', workflowNodesMap))++ expect(result.current).toBe(true)+ })++ it('should return true when the matching model plugin is installed', () => {+ mockModelProviders = [+ { provider: 'langgenius/openai/openai' },+ { provider: 'langgenius/anthropic/claude' },+ ]+ const workflowNodesMap = createWorkflowNodesMap({+ id: 'target',+ type: BlockEnum.LLM,+ modelProvider: 'langgenius/openai/gpt-4.1',+ })++ const { result } = renderHook(() => useLlmModelPluginInstalled('target', workflowNodesMap))++ expect(result.current).toBe(true)+ })++ it('should return false when the matching model plugin is not installed', () => {+ mockModelProviders = [+ { provider: 'langgenius/anthropic/claude' },+ ]+ const workflowNodesMap = createWorkflowNodesMap({+ id: 'target',+ type: BlockEnum.LLM,+ modelProvider: 'langgenius/openai/gpt-4.1',+ })++ const { result } = renderHook(() => useLlmModelPluginInstalled('target', workflowNodesMap))++ expect(result.current).toBe(false)+ })+})diff --git a/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.ts b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.tsnew file mode 100644index 00000000000..0aa98881b3e--- /dev/null+++ b/web/app/components/base/prompt-editor/plugins/workflow-variable-block/use-llm-model-plugin-installed.ts@@ -0,0 +1,23 @@+import type { WorkflowNodesMap } from '@/app/components/base/prompt-editor/types'+import { BlockEnum } from '@/app/components/workflow/types'+import { extractPluginId } from '@/app/components/workflow/utils/plugin'+import { useProviderContextSelector } from '@/context/provider-context'++export function useLlmModelPluginInstalled(+ nodeId: string,+ workflowNodesMap: WorkflowNodesMap | undefined,+): boolean {+ const node = workflowNodesMap?.[nodeId]+ const modelProvider = node?.type === BlockEnum.LLM+ ? node.modelProvider+ : undefined+ const modelPluginId = modelProvider ? extractPluginId(modelProvider) : undefined++ return useProviderContextSelector((state) => {+ if (!modelPluginId)+ return true+ return state.modelProviders.some(p =>+ extractPluginId(p.provider) === modelPluginId,+ )+ })+}diff --git a/web/app/components/base/prompt-editor/types.ts b/web/app/components/base/prompt-editor/types.tsindex 99221ffebdb..93bbb2f8b7c 100644--- a/web/app/components/base/prompt-editor/types.ts+++ b/web/app/components/base/prompt-editor/types.ts@@ -73,7 +73,7 @@ export type GetVarType = (payload: {export type WorkflowVariableBlockType = {show?: booleanvariables?: NodeOutPutVar[]- workflowNodesMap?: Record<string, Pick<Node['data'], 'title' | 'type' | 'height' | 'width' | 'position'>>+ workflowNodesMap?: WorkflowNodesMaponInsert?: () => voidonDelete?: () => voidgetVarType?: GetVarType@@ -81,12 +81,14 @@ export type WorkflowVariableBlockType = {onManageInputField?: () => void}+export type WorkflowNodesMap = Record<string, Pick<Node['data'], 'title' | 'type' | 'height' | 'width' | 'position'> & { modelProvider?: string }>+export type HITLInputBlockType = {show?: booleannodeId: stringformInputs?: FormInputItem[]variables?: NodeOutPutVar[]- workflowNodesMap?: Record<string, Pick<Node['data'], 'title' | 'type' | 'height' | 'width' | 'position'>>+ workflowNodesMap?: WorkflowNodesMapgetVarType?: GetVarTypeonFormInputsChange?: (inputs: FormInputItem[]) => voidonFormInputItemRemove: (varName: string) => voiddiff --git a/web/app/components/base/tag-input/__tests__/interop.spec.tsx b/web/app/components/base/tag-input/__tests__/interop.spec.tsxnew file mode 100644index 00000000000..f6dd316645d--- /dev/null+++ b/web/app/components/base/tag-input/__tests__/interop.spec.tsx@@ -0,0 +1,57 @@+import type { ComponentType, InputHTMLAttributes } from 'react'+import { render, screen } from '@testing-library/react'++const mockNotify = vi.fn()++type AutosizeInputProps = InputHTMLAttributes<HTMLInputElement> & {+ inputClassName?: string+}++const MockAutosizeInput: ComponentType<AutosizeInputProps> = ({ inputClassName, ...props }) => (+ <input data-testid="autosize-input" className={inputClassName} {...props} />+)++describe('TagInput autosize interop', () => {+ afterEach(() => {+ vi.clearAllMocks()+ vi.resetModules()+ })++ it('should support a namespace-style default export from react-18-input-autosize', async () => {+ vi.doMock('@/app/components/base/toast/context', () => ({+ useToastContext: () => ({+ notify: mockNotify,+ }),+ }))+ vi.doMock('react-18-input-autosize', () => ({+ default: {+ default: MockAutosizeInput,+ },+ }))++ const { default: TagInput } = await import('../index')++ render(<TagInput items={[]} onChange={vi.fn()} />)++ expect(screen.getByTestId('autosize-input')).toBeInTheDocument()+ expect(screen.getByRole('textbox')).toBeInTheDocument()+ })++ it('should support a direct default export from react-18-input-autosize', async () => {+ vi.doMock('@/app/components/base/toast/context', () => ({+ useToastContext: () => ({+ notify: mockNotify,+ }),+ }))+ vi.doMock('react-18-input-autosize', () => ({+ default: MockAutosizeInput,+ }))++ const { default: TagInput } = await import('../index')++ render(<TagInput items={[]} onChange={vi.fn()} />)++ expect(screen.getByTestId('autosize-input')).toBeInTheDocument()+ expect(screen.getByRole('textbox')).toBeInTheDocument()+ })+})diff --git a/web/app/components/base/tag-input/index.tsx b/web/app/components/base/tag-input/index.tsxindex 377e68abe40..ab28b484d1e 100644--- a/web/app/components/base/tag-input/index.tsx+++ b/web/app/components/base/tag-input/index.tsx@@ -1,10 +1,14 @@import type { ChangeEvent, FC, KeyboardEvent } from 'react'import { useCallback, useState } from 'react'-import AutosizeInput from 'react-18-input-autosize'+import _AutosizeInput from 'react-18-input-autosize'import { useTranslation } from 'react-i18next'import { useToastContext } from '@/app/components/base/toast/context'import { cn } from '@/utils/classnames'+// CJS/ESM interop: Turbopack may resolve the module namespace object instead of the default export+// eslint-disable-next-line ts/no-explicit-any+const AutosizeInput = ('default' in (_AutosizeInput as any) ? (_AutosizeInput as any).default : _AutosizeInput) as typeof _AutosizeInput+type TagInputProps = {items: string[]onChange: (items: string[]) => voiddiff --git a/web/app/components/base/ui/dialog/index.tsx b/web/app/components/base/ui/dialog/index.tsxindex 92d4dd69463..961c039be25 100644--- a/web/app/components/base/ui/dialog/index.tsx+++ b/web/app/components/base/ui/dialog/index.tsx@@ -46,20 +46,24 @@ type DialogContentProps = {children: React.ReactNodeclassName?: stringoverlayClassName?: string+ backdropProps?: React.ComponentPropsWithoutRef<typeof BaseDialog.Backdrop>}export function DialogContent({children,className,overlayClassName,+ backdropProps,}: DialogContentProps) {return (<DialogPortal><BaseDialog.Backdrop+ {...backdropProps}className={cn('fixed inset-0 z-[1002] bg-background-overlay','transition-opacity duration-150 data-[ending-style]:opacity-0 data-[starting-style]:opacity-0 motion-reduce:transition-none',overlayClassName,+ backdropProps?.className,)}/><BaseDialog.Popupdiff --git a/web/app/components/billing/pricing/__tests__/dialog.spec.tsx b/web/app/components/billing/pricing/__tests__/dialog.spec.tsxnew file mode 100644index 00000000000..c832e52fb2b--- /dev/null+++ b/web/app/components/billing/pricing/__tests__/dialog.spec.tsx@@ -0,0 +1,93 @@+import type { ReactNode } from 'react'+import type { Mock } from 'vitest'+import type { UsagePlanInfo } from '../../type'+import { render } from '@testing-library/react'+import { useAppContext } from '@/context/app-context'+import { useGetPricingPageLanguage } from '@/context/i18n'+import { useProviderContext } from '@/context/provider-context'+import { Plan } from '../../type'+import Pricing from '../index'++type DialogProps = {+ children: ReactNode+ open?: boolean+ onOpenChange?: (open: boolean) => void+}++let latestOnOpenChange: DialogProps['onOpenChange']++vi.mock('@/app/components/base/ui/dialog', () => ({+ Dialog: ({ children, onOpenChange }: DialogProps) => {+ latestOnOpenChange = onOpenChange+ return <div data-testid="dialog">{children}</div>+ },+ DialogContent: ({ children, className }: { children: ReactNode, className?: string }) => (+ <div className={className}>{children}</div>+ ),+}))++vi.mock('../header', () => ({+ default: ({ onClose }: { onClose: () => void }) => (+ <button data-testid="pricing-header-close" onClick={onClose}>close</button>+ ),+}))++vi.mock('../plan-switcher', () => ({+ default: () => <div>plan-switcher</div>,+}))++vi.mock('../plans', () => ({+ default: () => <div>plans</div>,+}))++vi.mock('../footer', () => ({+ default: () => <div>footer</div>,+}))++vi.mock('@/context/app-context', () => ({+ useAppContext: vi.fn(),+}))++vi.mock('@/context/provider-context', () => ({+ useProviderContext: vi.fn(),+}))++vi.mock('@/context/i18n', () => ({+ useGetPricingPageLanguage: vi.fn(),+}))++const buildUsage = (): UsagePlanInfo => ({+ buildApps: 0,+ teamMembers: 0,+ annotatedResponse: 0,+ documentsUploadQuota: 0,+ apiRateLimit: 0,+ triggerEvents: 0,+ vectorSpace: 0,+})++describe('Pricing dialog lifecycle', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ latestOnOpenChange = undefined+ ;(useAppContext as Mock).mockReturnValue({ isCurrentWorkspaceManager: true })+ ;(useProviderContext as Mock).mockReturnValue({+ plan: {+ type: Plan.sandbox,+ usage: buildUsage(),+ total: buildUsage(),+ },+ })+ ;(useGetPricingPageLanguage as Mock).mockReturnValue('en')+ })++ it('should only call onCancel when the dialog requests closing', () => {+ const onCancel = vi.fn()+ render(<Pricing onCancel={onCancel} />)++ latestOnOpenChange?.(true)+ latestOnOpenChange?.(false)++ expect(onCancel).toHaveBeenCalledTimes(1)+ })+})diff --git a/web/app/components/billing/pricing/__tests__/footer.spec.tsx b/web/app/components/billing/pricing/__tests__/footer.spec.tsxindex 7ef78180de7..762d0ad2119 100644--- a/web/app/components/billing/pricing/__tests__/footer.spec.tsx+++ b/web/app/components/billing/pricing/__tests__/footer.spec.tsx@@ -1,7 +1,7 @@import { render, screen } from '@testing-library/react'import * as React from 'react'-import { CategoryEnum } from '..'import Footer from '../footer'+import { CategoryEnum } from '../types'vi.mock('next/link', () => ({default: ({ children, href, className, target }: { children: React.ReactNode, href: string, className?: string, target?: string }) => (diff --git a/web/app/components/billing/pricing/__tests__/header.spec.tsx b/web/app/components/billing/pricing/__tests__/header.spec.tsxindex e1cb18ca3f5..0aadc3b0ced 100644--- a/web/app/components/billing/pricing/__tests__/header.spec.tsx+++ b/web/app/components/billing/pricing/__tests__/header.spec.tsx@@ -1,7 +1,16 @@import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'+import { Dialog } from '@/app/components/base/ui/dialog'import Header from '../header'+function renderHeader(onClose: () => void) {+ return render(+ <Dialog open>+ <Header onClose={onClose} />+ </Dialog>,+ )+}+describe('Header', () => {beforeEach(() => {vi.clearAllMocks()@@ -11,7 +20,7 @@ describe('Header', () => {it('should render title and description translations', () => {const handleClose = vi.fn()- render(<Header onClose={handleClose} />)+ renderHeader(handleClose)expect(screen.getByText('billing.plansCommon.title.plans')).toBeInTheDocument()expect(screen.getByText('billing.plansCommon.title.description')).toBeInTheDocument()@@ -22,7 +31,7 @@ describe('Header', () => {describe('Props', () => {it('should invoke onClose when close button is clicked', () => {const handleClose = vi.fn()- render(<Header onClose={handleClose} />)+ renderHeader(handleClose)fireEvent.click(screen.getByRole('button'))@@ -32,7 +41,7 @@ describe('Header', () => {describe('Edge Cases', () => {it('should render structural elements with translation keys', () => {- const { container } = render(<Header onClose={vi.fn()} />)+ const { container } = renderHeader(vi.fn())expect(container.querySelector('span')).toBeInTheDocument()expect(container.querySelector('p')).toBeInTheDocument()diff --git a/web/app/components/billing/pricing/__tests__/index.spec.tsx b/web/app/components/billing/pricing/__tests__/index.spec.tsxindex 54813ae0d74..1be2234cf9c 100644--- a/web/app/components/billing/pricing/__tests__/index.spec.tsx+++ b/web/app/components/billing/pricing/__tests__/index.spec.tsx@@ -74,15 +74,11 @@ describe('Pricing', () => {})describe('Props', () => {- it('should allow switching categories and handle esc key', () => {- const handleCancel = vi.fn()- render(<Pricing onCancel={handleCancel} />)+ it('should allow switching categories', () => {+ render(<Pricing onCancel={vi.fn()} />)fireEvent.click(screen.getByText('billing.plansCommon.self'))expect(screen.queryByRole('switch')).not.toBeInTheDocument()-- fireEvent.keyDown(window, { key: 'Escape', keyCode: 27 })- expect(handleCancel).toHaveBeenCalled()})})diff --git a/web/app/components/billing/pricing/footer.tsx b/web/app/components/billing/pricing/footer.tsxindex 7569ccaa767..6a213eca00c 100644--- a/web/app/components/billing/pricing/footer.tsx+++ b/web/app/components/billing/pricing/footer.tsx@@ -1,10 +1,9 @@-import type { Category } from '.'-import { RiArrowRightUpLine } from '@remixicon/react'+import type { Category } from './types'import Link from 'next/link'import * as React from 'react'import { useTranslation } from 'react-i18next'import { cn } from '@/utils/classnames'-import { CategoryEnum } from '.'+import { CategoryEnum } from './types'type FooterProps = {pricingPageURL: string@@ -34,7 +33,7 @@ const Footer = ({>{t('plansCommon.comparePlanAndFeatures', { ns: 'billing' })}</Link>- <RiArrowRightUpLine className="size-4" />+ <span aria-hidden="true" className="i-ri-arrow-right-up-line size-4" /></span></div></div>diff --git a/web/app/components/billing/pricing/header.tsx b/web/app/components/billing/pricing/header.tsxindex 5844fcf2648..d0ffe100db9 100644--- a/web/app/components/billing/pricing/header.tsx+++ b/web/app/components/billing/pricing/header.tsx@@ -1,4 +1,3 @@-import { RiCloseLine } from '@remixicon/react'import * as React from 'react'import { useTranslation } from 'react-i18next'import { cn } from '@/utils/classnames'@@ -39,7 +38,7 @@ const Header = ({className="absolute bottom-[40.5px] right-[-18px] z-10 size-9 rounded-full p-2"onClick={onClose}>- <RiCloseLine className="size-5" />+ <span aria-hidden="true" className="i-ri-close-line size-5" /></Button></div></div>diff --git a/web/app/components/billing/pricing/index.tsx b/web/app/components/billing/pricing/index.tsxindex 2b581581460..21ca7d0a6f7 100644--- a/web/app/components/billing/pricing/index.tsx+++ b/web/app/components/billing/pricing/index.tsx@@ -1,9 +1,9 @@'use client'import type { FC } from 'react'-import { useKeyPress } from 'ahooks'+import type { Category } from './types'import * as React from 'react'import { useState } from 'react'-import { createPortal } from 'react-dom'+import { Dialog, DialogContent } from '@/app/components/base/ui/dialog'import { useAppContext } from '@/context/app-context'import { useGetPricingPageLanguage } from '@/context/i18n'import { useProviderContext } from '@/context/provider-context'@@ -13,13 +13,7 @@ import Header from './header'import PlanSwitcher from './plan-switcher'import { PlanRange } from './plan-switcher/plan-range-switcher'import Plans from './plans'--export enum CategoryEnum {- CLOUD = 'cloud',- SELF = 'self',-}--export type Category = CategoryEnum.CLOUD | CategoryEnum.SELF+import { CategoryEnum } from './types'type PricingProps = {onCancel: () => void@@ -33,42 +27,47 @@ const Pricing: FC<PricingProps> = ({const [planRange, setPlanRange] = React.useState<PlanRange>(PlanRange.monthly)const [currentCategory, setCurrentCategory] = useState<Category>(CategoryEnum.CLOUD)const canPay = isCurrentWorkspaceManager- useKeyPress(['esc'], onCancel)const pricingPageLanguage = useGetPricingPageLanguage()const pricingPageURL = pricingPageLanguage? `https://dify.ai/${pricingPageLanguage}/pricing#plans-and-features`: 'https://dify.ai/pricing#plans-and-features'- return createPortal(- <div- className="fixed inset-0 bottom-0 left-0 right-0 top-0 z-[1000] overflow-auto bg-saas-background"- onClick={e => e.stopPropagation()}+ return (+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open)+ onCancel()+ }}>- <div className="relative grid min-h-full min-w-[1200px] grid-rows-[1fr_auto_auto_1fr] overflow-hidden">- <div className="absolute -top-12 left-0 right-0 -z-10">- <NoiseTop />- </div>- <Header onClose={onCancel} />- <PlanSwitcher- currentCategory={currentCategory}- onChangeCategory={setCurrentCategory}- currentPlanRange={planRange}- onChangePlanRange={setPlanRange}- />- <Plans- plan={plan}- currentPlan={currentCategory}- planRange={planRange}- canPay={canPay}- />- <Footer pricingPageURL={pricingPageURL} currentCategory={currentCategory} />- <div className="absolute -bottom-12 left-0 right-0 -z-10">- <NoiseBottom />+ <DialogContent+ className="inset-0 h-full max-h-none w-full max-w-none translate-x-0 translate-y-0 overflow-auto rounded-none border-none bg-saas-background p-0 shadow-none"+ >+ <div className="relative grid min-h-full min-w-[1200px] grid-rows-[1fr_auto_auto_1fr] overflow-hidden">+ <div className="absolute -top-12 left-0 right-0 -z-10">+ <NoiseTop />+ </div>+ <Header onClose={onCancel} />+ <PlanSwitcher+ currentCategory={currentCategory}+ onChangeCategory={setCurrentCategory}+ currentPlanRange={planRange}+ onChangePlanRange={setPlanRange}+ />+ <Plans+ plan={plan}+ currentPlan={currentCategory}+ planRange={planRange}+ canPay={canPay}+ />+ <Footer pricingPageURL={pricingPageURL} currentCategory={currentCategory} />+ <div className="absolute -bottom-12 left-0 right-0 -z-10">+ <NoiseBottom />+ </div></div>- </div>- </div>,- document.body,+ </DialogContent>+ </Dialog>)}export default React.memo(Pricing)diff --git a/web/app/components/billing/pricing/plan-switcher/__tests__/index.spec.tsx b/web/app/components/billing/pricing/plan-switcher/__tests__/index.spec.tsxindex 51e074e3058..e6b8d8430f0 100644--- a/web/app/components/billing/pricing/plan-switcher/__tests__/index.spec.tsx+++ b/web/app/components/billing/pricing/plan-switcher/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import { fireEvent, render, screen } from '@testing-library/react'import * as React from 'react'-import { CategoryEnum } from '../../index'+import { CategoryEnum } from '../../types'import PlanSwitcher from '../index'import { PlanRange } from '../plan-range-switcher'diff --git a/web/app/components/billing/pricing/plan-switcher/index.tsx b/web/app/components/billing/pricing/plan-switcher/index.tsxindex 60e0bdf8de1..be0bd3e2b1d 100644--- a/web/app/components/billing/pricing/plan-switcher/index.tsx+++ b/web/app/components/billing/pricing/plan-switcher/index.tsx@@ -1,5 +1,5 @@import type { FC } from 'react'-import type { Category } from '../index'+import type { Category } from '../types'import type { PlanRange } from './plan-range-switcher'import * as React from 'react'import { useTranslation } from 'react-i18next'diff --git a/web/app/components/billing/pricing/types.ts b/web/app/components/billing/pricing/types.tsnew file mode 100644index 00000000000..843d98e6f55--- /dev/null+++ b/web/app/components/billing/pricing/types.ts@@ -0,0 +1,6 @@+export enum CategoryEnum {+ CLOUD = 'cloud',+ SELF = 'self',+}++export type Category = CategoryEnum.CLOUD | CategoryEnum.SELFdiff --git a/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx b/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsxindex 7df3881824c..c154c1a534f 100644--- a/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx+++ b/web/app/components/datasets/create/website/firecrawl/__tests__/index.spec.tsx@@ -1,5 +1,5 @@import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vitest'@@ -55,6 +55,21 @@ const createMockCrawlResultItem = (overrides: Partial<CrawlResultItem> = {}): Cr...overrides,})+const createDeferred = <T,>() => {+ let resolve!: (value: T | PromiseLike<T>) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((res, rej) => {+ resolve = res+ reject = rej+ })++ return {+ promise,+ resolve,+ reject,+ }+}+// FireCrawl Component Testsdescribe('FireCrawl', () => {@@ -217,7 +232,7 @@ describe('FireCrawl', () => {await user.click(runButton)await waitFor(() => {- expect(mockCreateFirecrawlTask).toHaveBeenCalled()+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])})})@@ -241,7 +256,7 @@ describe('FireCrawl', () => {await user.click(runButton)await waitFor(() => {- expect(mockCreateFirecrawlTask).toHaveBeenCalled()+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])})})})@@ -277,6 +292,10 @@ describe('FireCrawl', () => {}),})})++ await waitFor(() => {+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])+ })})it('should call onJobIdChange with job_id from API response', async () => {@@ -301,6 +320,10 @@ describe('FireCrawl', () => {await waitFor(() => {expect(mockOnJobIdChange).toHaveBeenCalledWith('my-job-123')})++ await waitFor(() => {+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])+ })})it('should remove empty max_depth from crawlOptions before sending to API', async () => {@@ -334,11 +357,23 @@ describe('FireCrawl', () => {}),})})++ await waitFor(() => {+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])+ })})it('should show loading state while running', async () => {const user = userEvent.setup()- mockCreateFirecrawlTask.mockImplementation(() => new Promise(() => {})) // Never resolves+ const createTaskDeferred = createDeferred<{ job_id: string }>()+ mockCreateFirecrawlTask.mockImplementation(() => createTaskDeferred.promise)+ mockCheckFirecrawlTaskStatus.mockResolvedValueOnce({+ status: 'completed',+ data: [],+ total: 0,+ current: 0,+ time_consuming: 1,+ })render(<FireCrawl {...defaultProps} />)@@ -352,6 +387,14 @@ describe('FireCrawl', () => {await waitFor(() => {expect(runButton).not.toHaveTextContent(/run/i)})++ await act(async () => {+ createTaskDeferred.resolve({ job_id: 'test-job-id' })+ })++ await waitFor(() => {+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])+ })})})@@ -656,7 +699,7 @@ describe('FireCrawl', () => {await waitFor(() => {// Total should be capped to limit (5)- expect(mockCheckFirecrawlTaskStatus).toHaveBeenCalled()+ expect(mockOnCheckedCrawlResultChange).toHaveBeenCalledWith([])})})})diff --git a/web/app/components/datasets/create/website/firecrawl/index.tsx b/web/app/components/datasets/create/website/firecrawl/index.tsxindex 3c5c453b510..09fdbb00c2b 100644--- a/web/app/components/datasets/create/website/firecrawl/index.tsx+++ b/web/app/components/datasets/create/website/firecrawl/index.tsx@@ -2,7 +2,7 @@import type { FC } from 'react'import type { CrawlOptions, CrawlResultItem } from '@/models/datasets'import * as React from 'react'-import { useCallback, useEffect, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import Toast from '@/app/components/base/toast'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'@@ -35,6 +35,22 @@ enum Step {finished = 'finished',}+type CrawlState = {+ current: number+ total: number+ data: CrawlResultItem[]+ time_consuming: number | string+}++type CrawlFinishedResult = {+ isCancelled?: boolean+ isError: boolean+ errorMessage?: string+ data: Partial<CrawlState> & {+ data: CrawlResultItem[]+ }+}+const FireCrawl: FC<Props> = ({onPreview,checkedCrawlResult,@@ -46,10 +62,16 @@ const FireCrawl: FC<Props> = ({const { t } = useTranslation()const [step, setStep] = useState<Step>(Step.init)const [controlFoldOptions, setControlFoldOptions] = useState<number>(0)+ const isMountedRef = useRef(true)useEffect(() => {if (step !== Step.init)setControlFoldOptions(Date.now())}, [step])+ useEffect(() => {+ return () => {+ isMountedRef.current = false+ }+ }, [])const setShowAccountSettingModal = useModalContextSelector(s => s.setShowAccountSettingModal)const handleSetting = useCallback(() => {setShowAccountSettingModal({@@ -85,16 +107,19 @@ const FireCrawl: FC<Props> = ({const isInit = step === Step.initconst isCrawlFinished = step === Step.finishedconst isRunning = step === Step.running- const [crawlResult, setCrawlResult] = useState<{- current: number- total: number- data: CrawlResultItem[]- time_consuming: number | string- } | undefined>(undefined)+ const [crawlResult, setCrawlResult] = useState<CrawlState | undefined>(undefined)const [crawlErrorMessage, setCrawlErrorMessage] = useState('')const showError = isCrawlFinished && crawlErrorMessage- const waitForCrawlFinished = useCallback(async (jobId: string) => {+ const waitForCrawlFinished = useCallback(async (jobId: string): Promise<CrawlFinishedResult> => {+ const cancelledResult: CrawlFinishedResult = {+ isCancelled: true,+ isError: false,+ data: {+ data: [],+ },+ }+try {const res = await checkFirecrawlTaskStatus(jobId) as anyif (res.status === 'completed') {@@ -104,7 +129,7 @@ const FireCrawl: FC<Props> = ({...res,total: Math.min(res.total, Number.parseFloat(crawlOptions.limit as string)),},- }+ } satisfies CrawlFinishedResult}if (res.status === 'error' || !res.status) {// can't get the error message from the firecrawl api@@ -114,12 +139,14 @@ const FireCrawl: FC<Props> = ({data: {data: [],},- }+ } satisfies CrawlFinishedResult}res.data = res.data.map((item: any) => ({...item,content: item.markdown,}))+ if (!isMountedRef.current)+ return cancelledResult// update the progresssetCrawlResult({...res,@@ -127,17 +154,21 @@ const FireCrawl: FC<Props> = ({})onCheckedCrawlResultChange(res.data || []) // default select the crawl resultawait sleep(2500)+ if (!isMountedRef.current)+ return cancelledResultreturn await waitForCrawlFinished(jobId)}catch (e: any) {- const errorBody = await e.json()+ if (!isMountedRef.current)+ return cancelledResult+ const errorBody = typeof e?.json === 'function' ? await e.json() : undefinedreturn {isError: true,- errorMessage: errorBody.message,+ errorMessage: errorBody?.message,data: {data: [],},- }+ } satisfies CrawlFinishedResult}}, [crawlOptions.limit, onCheckedCrawlResultChange])@@ -162,24 +193,31 @@ const FireCrawl: FC<Props> = ({url,options: passToServerCrawlOptions,}) as any+ if (!isMountedRef.current)+ returnconst jobId = res.job_idonJobIdChange(jobId)- const { isError, data, errorMessage } = await waitForCrawlFinished(jobId)+ const { isCancelled, isError, data, errorMessage } = await waitForCrawlFinished(jobId)+ if (isCancelled || !isMountedRef.current)+ returnif (isError) {setCrawlErrorMessage(errorMessage || t(`${I18N_PREFIX}.unknownError`, { ns: 'datasetCreation' }))}else {- setCrawlResult(data)+ setCrawlResult(data as CrawlState)onCheckedCrawlResultChange(data.data || []) // default select the crawl resultsetCrawlErrorMessage('')}}catch (e) {+ if (!isMountedRef.current)+ returnsetCrawlErrorMessage(t(`${I18N_PREFIX}.unknownError`, { ns: 'datasetCreation' })!)console.log(e)}finally {- setStep(Step.finished)+ if (isMountedRef.current)+ setStep(Step.finished)}}, [checkValid, crawlOptions, onJobIdChange, t, waitForCrawlFinished, onCheckedCrawlResultChange])diff --git a/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx b/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsxindex 63efc766b77..93992a1aba1 100644--- a/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx+++ b/web/app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx@@ -204,7 +204,7 @@ const CSVUploader: FC<Props> = ({/><div ref={dropRef}>{!file && (- <div className={cn('flex h-20 items-center rounded-xl border border-dashed border-components-panel-border bg-components-panel-bg-blur text-sm font-normal', dragging && 'border border-divider-subtle bg-components-panel-on-panel-item-bg-hover')}>+ <div className={cn('flex h-20 items-center rounded-xl border border-dashed border-components-panel-border bg-components-panel-bg-blur text-sm font-normal', dragging && 'border border-divider-subtle bg-components-panel-on-panel-item-bg-hover')}><div className="flex w-full items-center justify-center space-x-2"><CSVIcon className="shrink-0" /><div className="text-text-secondary">diff --git a/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx b/web/app/components/datasets/documents/detail/completed/new-child-segment.tsxindex 7a6ae4b306c..e28fb774fbc 100644--- a/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx+++ b/web/app/components/datasets/documents/detail/completed/new-child-segment.tsx@@ -58,7 +58,7 @@ const NewChildSegmentModal: FC<NewChildSegmentModalProps> = ({<Divider type="vertical" className="mx-1 h-3 bg-divider-regular" /><buttontype="button"- className="system-xs-semibold text-text-accent"+ className="text-text-accent system-xs-semibold"onClick={() => {clearTimeout(refreshTimer.current)viewNewlyAddedChildChunk?.()@@ -120,11 +120,11 @@ const NewChildSegmentModal: FC<NewChildSegmentModalProps> = ({<div className="flex h-full flex-col"><div className={cn('flex items-center justify-between', fullScreen ? 'border border-divider-subtle py-3 pl-6 pr-4' : 'pl-4 pr-3 pt-3')}><div className="flex flex-col">- <div className="system-xl-semibold text-text-primary">{t('segment.addChildChunk', { ns: 'datasetDocuments' })}</div>+ <div className="text-text-primary system-xl-semibold">{t('segment.addChildChunk', { ns: 'datasetDocuments' })}</div><div className="flex items-center gap-x-2"><SegmentIndexTag label={t('segment.newChildChunk', { ns: 'datasetDocuments' }) as string} /><Dot />- <span className="system-xs-medium text-text-tertiary">{wordCountText}</span>+ <span className="text-text-tertiary system-xs-medium">{wordCountText}</span></div></div><div className="flex items-center">diff --git a/web/app/components/datasets/documents/detail/new-segment.tsx b/web/app/components/datasets/documents/detail/new-segment.tsxindex f32c94bf70f..d2e27e99697 100644--- a/web/app/components/datasets/documents/detail/new-segment.tsx+++ b/web/app/components/datasets/documents/detail/new-segment.tsx@@ -61,7 +61,7 @@ const NewSegmentModal: FC<NewSegmentModalProps> = ({<Divider type="vertical" className="mx-1 h-3 bg-divider-regular" /><buttontype="button"- className="system-xs-semibold text-text-accent"+ className="text-text-accent system-xs-semibold"onClick={() => {clearTimeout(refreshTimer.current)viewNewlyAddedChunk()@@ -158,13 +158,13 @@ const NewSegmentModal: FC<NewSegmentModalProps> = ({className={cn('flex items-center justify-between', fullScreen ? 'border border-divider-subtle py-3 pl-6 pr-4' : 'pl-4 pr-3 pt-3')}><div className="flex flex-col">- <div className="system-xl-semibold text-text-primary">+ <div className="text-text-primary system-xl-semibold">{t('segment.addChunk', { ns: 'datasetDocuments' })}</div><div className="flex items-center gap-x-2"><SegmentIndexTag label={t('segment.newChunk', { ns: 'datasetDocuments' })!} /><Dot />- <span className="system-xs-medium text-text-tertiary">{wordCountText}</span>+ <span className="text-text-tertiary system-xs-medium">{wordCountText}</span></div></div><div className="flex items-center">diff --git a/web/app/components/datasets/documents/detail/settings/__tests__/document-settings.spec.tsx b/web/app/components/datasets/documents/detail/settings/__tests__/document-settings.spec.tsxindex e6109132a47..84534298c9f 100644--- a/web/app/components/datasets/documents/detail/settings/__tests__/document-settings.spec.tsx+++ b/web/app/components/datasets/documents/detail/settings/__tests__/document-settings.spec.tsx@@ -100,10 +100,10 @@ vi.mock('@/app/components/datasets/create/step-two', () => ({}))vi.mock('@/app/components/header/account-setting', () => ({- default: ({ activeTab, onCancel }: { activeTab?: string, onCancel?: () => void }) => (+ default: ({ activeTab, onCancelAction }: { activeTab?: string, onCancelAction?: () => void }) => (<div data-testid="account-setting"><span data-testid="active-tab">{activeTab}</span>- <button onClick={onCancel} data-testid="close-setting">Close</button>+ <button onClick={onCancelAction} data-testid="close-setting">Close</button></div>),}))diff --git a/web/app/components/datasets/documents/detail/settings/document-settings.tsx b/web/app/components/datasets/documents/detail/settings/document-settings.tsxindex 0d10f8a51e1..67773cb7d6a 100644--- a/web/app/components/datasets/documents/detail/settings/document-settings.tsx+++ b/web/app/components/datasets/documents/detail/settings/document-settings.tsx@@ -1,3 +1,4 @@+import type { AccountSettingTab } from '@/app/components/header/account-setting/constants'import type { DataSourceProvider, NotionPage } from '@/models/common'import type {CrawlOptions,@@ -19,6 +20,7 @@ import AppUnavailable from '@/app/components/base/app-unavailable'import Loading from '@/app/components/base/loading'import StepTwo from '@/app/components/datasets/create/step-two'import AccountSetting from '@/app/components/header/account-setting'+import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import { useDefaultModel } from '@/app/components/header/account-setting/model-provider-page/hooks'import DatasetDetailContext from '@/context/dataset-detail'@@ -33,8 +35,13 @@ const DocumentSettings = ({ datasetId, documentId }: DocumentSettingsProps) => {const { t } = useTranslation()const router = useRouter()const [isShowSetAPIKey, { setTrue: showSetAPIKey, setFalse: hideSetAPIkey }] = useBoolean()+ const [accountSettingTab, setAccountSettingTab] = React.useState<AccountSettingTab>(ACCOUNT_SETTING_TAB.PROVIDER)const { indexingTechnique, dataset } = useContext(DatasetDetailContext)const { data: embeddingsDefaultModel } = useDefaultModel(ModelTypeEnum.textEmbedding)+ const handleOpenAccountSetting = React.useCallback(() => {+ setAccountSettingTab(ACCOUNT_SETTING_TAB.PROVIDER)+ showSetAPIKey()+ }, [showSetAPIKey])const invalidDocumentList = useInvalidDocumentList(datasetId)const invalidDocumentDetail = useInvalidDocumentDetail()@@ -135,7 +142,7 @@ const DocumentSettings = ({ datasetId, documentId }: DocumentSettingsProps) => {{dataset && documentDetail && (<StepTwoisAPIKeySet={!!embeddingsDefaultModel}- onSetting={showSetAPIKey}+ onSetting={handleOpenAccountSetting}datasetId={datasetId}dataSourceType={documentDetail.data_source_type as DataSourceType}notionPages={currentPage ? [currentPage as unknown as NotionPage] : []}@@ -155,8 +162,9 @@ const DocumentSettings = ({ datasetId, documentId }: DocumentSettingsProps) => {</div>{isShowSetAPIKey && (<AccountSetting- activeTab="provider"- onCancel={async () => {+ activeTab={accountSettingTab}+ onTabChangeAction={setAccountSettingTab}+ onCancelAction={async () => {hideSetAPIkey()}}/>diff --git a/web/app/components/datasets/external-api/external-api-modal/index.tsx b/web/app/components/datasets/external-api/external-api-modal/index.tsxindex a82d9abc430..809cd432a9e 100644--- a/web/app/components/datasets/external-api/external-api-modal/index.tsx+++ b/web/app/components/datasets/external-api/external-api-modal/index.tsx@@ -125,13 +125,13 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCan<div className="fixed inset-0 flex items-center justify-center bg-black/[.25]"><div className="shadows-shadow-xl relative flex w-[480px] flex-col items-start rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg"><div className="flex flex-col items-start gap-2 self-stretch pb-3 pl-6 pr-14 pt-6">- <div className="title-2xl-semi-bold grow self-stretch text-text-primary">+ <div className="grow self-stretch text-text-primary title-2xl-semi-bold">{isEditMode ? t('editExternalAPIFormTitle', { ns: 'dataset' }) : t('createExternalAPI', { ns: 'dataset' })}</div>{isEditMode && (datasetBindings?.length ?? 0) > 0 && (- <div className="system-xs-regular flex items-center text-text-tertiary">+ <div className="flex items-center text-text-tertiary system-xs-regular">{t('editExternalAPIFormWarning.front', { ns: 'dataset' })}<span className="flex cursor-pointer items-center text-text-accent"> @@ -144,12 +144,12 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCanpopupContent={(<div className="p-1"><div className="flex items-start self-stretch pb-0.5 pl-2 pr-3 pt-1">- <div className="system-xs-medium-uppercase text-text-tertiary">{`${datasetBindings?.length} ${t('editExternalAPITooltipTitle', { ns: 'dataset' })}`}</div>+ <div className="text-text-tertiary system-xs-medium-uppercase">{`${datasetBindings?.length} ${t('editExternalAPITooltipTitle', { ns: 'dataset' })}`}</div></div>{datasetBindings?.map(binding => (<div key={binding.id} className="flex items-center gap-1 self-stretch px-2 py-1"><RiBook2Line className="h-4 w-4 text-text-secondary" />- <div className="system-sm-medium text-text-secondary">{binding.name}</div>+ <div className="text-text-secondary system-sm-medium">{binding.name}</div></div>))}</div>@@ -193,8 +193,8 @@ const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({ data, onSave, onCan{t('externalAPIForm.save', { ns: 'dataset' })}</Button></div>- <div className="system-xs-regular flex items-center justify-center gap-1 self-stretch rounded-b-2xl border-t-[0.5px]- border-divider-subtle bg-background-soft px-2 py-3 text-text-tertiary"+ <div className="flex items-center justify-center gap-1 self-stretch rounded-b-2xl border-t-[0.5px] border-divider-subtle+ bg-background-soft px-2 py-3 text-text-tertiary system-xs-regular"><RiLock2Fill className="h-3 w-3 text-text-quaternary" />{t('externalAPIForm.encrypted.front', { ns: 'dataset' })}diff --git a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx b/web/app/components/datasets/settings/form/__tests__/index.spec.tsxindex b2a2e3c9d8c..9eeb62b8e81 100644--- a/web/app/components/datasets/settings/form/__tests__/index.spec.tsx+++ b/web/app/components/datasets/settings/form/__tests__/index.spec.tsx@@ -127,6 +127,14 @@ vi.mock('@/service/use-common', () => ({],},}),+ useCurrentWorkspace: () => ({+ data: {+ trial_credits: 1000,+ trial_credits_used: 100,+ next_credit_reset_date: undefined,+ },+ isPending: false,+ }),}))vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({@@ -191,6 +199,42 @@ vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,}))+vi.mock('../components/indexing-section', () => ({+ default: ({+ currentDataset,+ indexMethod,+ }: {+ currentDataset?: DataSet+ indexMethod?: IndexingType+ }) => (+ <div data-testid="indexing-section">+ {!!currentDataset?.doc_form && (+ <>+ <div>form.chunkStructure.title</div>+ <a href="https://docs.dify.ai/use-dify/knowledge/create-knowledge/chunking-and-cleaning-text">+ form.chunkStructure.learnMore+ </a>+ </>+ )}+ {!!(currentDataset+ && currentDataset.doc_form !== ChunkingMode.parentChild+ && currentDataset.indexing_technique+ && indexMethod) && (+ <div>form.indexMethod</div>+ )}+ {indexMethod === IndexingType.QUALIFIED && <div>form.embeddingModel</div>}+ {currentDataset?.provider !== 'external' && indexMethod && (+ <>+ <div>form.retrievalSetting.title</div>+ <a href="https://docs.dify.ai/use-dify/knowledge/create-knowledge/setting-indexing-methods">+ form.retrievalSetting.learnMore+ </a>+ </>+ )}+ </div>+ ),+}))+describe('Form', () => {beforeEach(() => {vi.clearAllMocks()diff --git a/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx b/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsxindex f49bdbc5763..6afc0e8b681 100644--- a/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx+++ b/web/app/components/datasets/settings/form/components/__tests__/indexing-section.spec.tsx@@ -8,75 +8,149 @@ import { RETRIEVE_METHOD } from '@/types/app'import { IndexingType } from '../../../../create/step-two'import IndexingSection from '../indexing-section'-// Mock i18n doc link+vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}))+vi.mock('@/context/i18n', () => ({useDocLink: () => (path: string) => `https://docs.dify.ai${path}`,}))-// Mock app-context for child components-vi.mock('@/context/app-context', () => ({- useSelector: (selector: (state: unknown) => unknown) => {- const state = {- isCurrentWorkspaceDatasetOperator: false,- userProfile: {- id: 'user-1',- name: 'Current User',- email: '[email protected]',- avatar_url: '',- role: 'owner',- },- }- return selector(state)- },+vi.mock('@/app/components/base/divider', () => ({+ default: ({ className }: { className?: string }) => (+ <div data-testid="divider" className={className} />+ ),}))-// Mock model-provider-page hooks-vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({- useModelList: () => ({ data: [], mutate: vi.fn(), isLoading: false }),- useCurrentProviderAndModel: () => ({ currentProvider: undefined, currentModel: undefined }),- useDefaultModel: () => ({ data: undefined, mutate: vi.fn(), isLoading: false }),- useModelListAndDefaultModel: () => ({ modelList: [], defaultModel: undefined }),- useModelListAndDefaultModelAndCurrentProviderAndModel: () => ({- modelList: [],- defaultModel: undefined,- currentProvider: undefined,- currentModel: undefined,- }),- useUpdateModelList: () => vi.fn(),- useUpdateModelProviders: () => vi.fn(),- useLanguage: () => 'en_US',- useSystemDefaultModelAndModelList: () => [undefined, vi.fn()],- useProviderCredentialsAndLoadBalancing: () => ({- credentials: undefined,- loadBalancing: undefined,- mutate: vi.fn(),- isLoading: false,- }),- useAnthropicBuyQuota: () => vi.fn(),- useMarketplaceAllPlugins: () => ({ plugins: [], isLoading: false }),- useRefreshModel: () => ({ handleRefreshModel: vi.fn() }),- useModelModalHandler: () => vi.fn(),+vi.mock('@/app/components/datasets/settings/chunk-structure', () => ({+ default: ({ chunkStructure }: { chunkStructure: string }) => (+ <div data-testid="chunk-structure" data-mode={chunkStructure}>+ {chunkStructure}+ </div>+ ),}))-// Mock provider-context-vi.mock('@/context/provider-context', () => ({- useProviderContext: () => ({- textGenerationModelList: [],- embeddingsModelList: [],- rerankModelList: [],- agentThoughtModelList: [],- modelProviders: [],- textEmbeddingModelList: [],- speech2textModelList: [],- ttsModelList: [],- moderationModelList: [],- hasSettedApiKey: true,- plan: { type: 'free' },- enableBilling: false,- onPlanInfoChanged: vi.fn(),- isCurrentWorkspaceDatasetOperator: false,- supportRetrievalMethods: ['semantic_search', 'full_text_search', 'hybrid_search'],- }),+vi.mock('@/app/components/datasets/settings/index-method', () => ({+ default: ({+ value,+ disabled,+ keywordNumber,+ onChange,+ onKeywordNumberChange,+ }: {+ value: string+ disabled?: boolean+ keywordNumber: number+ onChange: (value: IndexingType) => void+ onKeywordNumberChange: (value: number) => void+ }) => (+ <div+ data-testid="index-method"+ data-disabled={disabled ? 'true' : 'false'}+ data-keyword-number={String(keywordNumber)}+ data-value={value}+ >+ <button type="button" onClick={() => onChange(IndexingType.QUALIFIED)}>+ stepTwo.qualified+ </button>+ <button type="button" onClick={() => onChange(IndexingType.ECONOMICAL)}>+ form.indexMethodEconomy+ </button>+ <button type="button" onClick={() => onKeywordNumberChange(keywordNumber + 1)}>+ keyword-number-increment+ </button>+ </div>+ ),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({+ default: ({+ defaultModel,+ onSelect,+ }: {+ defaultModel?: DefaultModel+ onSelect?: (value: DefaultModel) => void+ }) => (+ <div+ data-testid="model-selector"+ data-model={defaultModel?.model ?? ''}+ data-provider={defaultModel?.provider ?? ''}+ >+ <button+ type="button"+ onClick={() => onSelect?.({ provider: 'cohere', model: 'embed-english-v3.0' })}+ >+ select-model+ </button>+ </div>+ ),+}))++vi.mock('@/app/components/datasets/settings/summary-index-setting', () => ({+ default: ({+ summaryIndexSetting,+ onSummaryIndexSettingChange,+ }: {+ summaryIndexSetting?: SummaryIndexSetting+ onSummaryIndexSettingChange?: (payload: SummaryIndexSetting) => void+ }) => (+ <div data-testid="summary-index-setting" data-enabled={summaryIndexSetting?.enable ? 'true' : 'false'}>+ <button type="button" onClick={() => onSummaryIndexSettingChange?.({ enable: true })}>+ summary-enable+ </button>+ </div>+ ),+}))++vi.mock('@/app/components/datasets/common/retrieval-method-config', () => ({+ default: ({+ showMultiModalTip,+ onChange,+ value,+ }: {+ showMultiModalTip?: boolean+ onChange: (value: RetrievalConfig) => void+ value: RetrievalConfig+ }) => (+ <div data-testid="retrieval-method-config">+ {showMultiModalTip && <span>show-multimodal-tip</span>}+ <button+ type="button"+ onClick={() =>+ onChange({+ ...value,+ top_k: 6,+ })}+ >+ update-retrieval+ </button>+ </div>+ ),+}))++vi.mock('@/app/components/datasets/common/economical-retrieval-method-config', () => ({+ default: ({+ onChange,+ value,+ }: {+ onChange: (value: RetrievalConfig) => void+ value: RetrievalConfig+ }) => (+ <div data-testid="economical-retrieval-method-config">+ <button+ type="button"+ onClick={() =>+ onChange({+ ...value,+ search_method: RETRIEVE_METHOD.keywordSearch,+ })}+ >+ update-economy-retrieval+ </button>+ </div>+ ),}))describe('IndexingSection', () => {@@ -187,315 +261,281 @@ describe('IndexingSection', () => {showMultiModalTip: false,}+ const renderComponent = (props: Partial<typeof defaultProps> = {}) => {+ return render(<IndexingSection {...defaultProps} {...props} />)+ }+beforeEach(() => {vi.clearAllMocks()})describe('Rendering', () => {- it('should render without crashing', () => {- render(<IndexingSection {...defaultProps} />)- expect(screen.getByText(/form\.chunkStructure\.title/i)).toBeInTheDocument()- })+ it('should render the chunk structure, index method, and retrieval sections for a standard dataset', () => {+ renderComponent()- it('should render chunk structure section when doc_form is set', () => {- render(<IndexingSection {...defaultProps} />)- expect(screen.getByText(/form\.chunkStructure\.title/i)).toBeInTheDocument()+ expect(screen.getByText('form.chunkStructure.title')).toBeInTheDocument()+ expect(screen.getByTestId('chunk-structure')).toHaveAttribute('data-mode', ChunkingMode.text)+ expect(screen.getByText('form.indexMethod')).toBeInTheDocument()+ expect(screen.getByTestId('index-method')).toBeInTheDocument()+ expect(screen.getByText('form.retrievalSetting.title')).toBeInTheDocument()})- it('should render index method section when conditions are met', () => {- render(<IndexingSection {...defaultProps} />)- // May match multiple elements (label and descriptions)- expect(screen.getAllByText(/form\.indexMethod/i).length).toBeGreaterThan(0)- })-- it('should render embedding model section when indexMethod is high_quality', () => {- render(<IndexingSection {...defaultProps} indexMethod={IndexingType.QUALIFIED} />)- expect(screen.getByText(/form\.embeddingModel/i)).toBeInTheDocument()- })+ it('should render the embedding model selector when the index method is high quality', () => {+ renderComponent()- it('should render retrieval settings section', () => {- render(<IndexingSection {...defaultProps} />)- expect(screen.getByText(/form\.retrievalSetting\.title/i)).toBeInTheDocument()+ expect(screen.getByText('form.embeddingModel')).toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toHaveAttribute('data-model', 'text-embedding-ada-002')})})describe('Chunk Structure Section', () => {- it('should not render chunk structure when doc_form is not set', () => {- const datasetWithoutDocForm = { ...mockDataset, doc_form: undefined as unknown as ChunkingMode }- render(<IndexingSection {...defaultProps} currentDataset={datasetWithoutDocForm} />)+ it('should hide the chunk structure section when the dataset has no doc form', () => {+ renderComponent({+ currentDataset: {+ ...mockDataset,+ doc_form: undefined as unknown as ChunkingMode,+ },+ })- expect(screen.queryByText(/form\.chunkStructure\.title/i)).not.toBeInTheDocument()+ expect(screen.queryByText('form.chunkStructure.title')).not.toBeInTheDocument()+ expect(screen.queryByTestId('chunk-structure')).not.toBeInTheDocument()})- it('should render learn more link for chunk structure', () => {- render(<IndexingSection {...defaultProps} />)+ it('should render the chunk structure learn more link and description', () => {+ renderComponent()- const learnMoreLink = screen.getByText(/form\.chunkStructure\.learnMore/i)- expect(learnMoreLink).toBeInTheDocument()+ const learnMoreLink = screen.getByRole('link', { name: 'form.chunkStructure.learnMore' })expect(learnMoreLink).toHaveAttribute('href', expect.stringContaining('chunking-and-cleaning-text'))- })-- it('should render chunk structure description', () => {- render(<IndexingSection {...defaultProps} />)-- expect(screen.getByText(/form\.chunkStructure\.description/i)).toBeInTheDocument()+ expect(screen.getByText('form.chunkStructure.description')).toBeInTheDocument()})})describe('Index Method Section', () => {- it('should not render index method for parentChild chunking mode', () => {- const parentChildDataset = { ...mockDataset, doc_form: ChunkingMode.parentChild }- render(<IndexingSection {...defaultProps} currentDataset={parentChildDataset} />)+ it('should hide the index method section for parent-child chunking', () => {+ renderComponent({+ currentDataset: {+ ...mockDataset,+ doc_form: ChunkingMode.parentChild,+ },+ })- expect(screen.queryByText(/form\.indexMethod/i)).not.toBeInTheDocument()+ expect(screen.queryByText('form.indexMethod')).not.toBeInTheDocument()+ expect(screen.queryByTestId('index-method')).not.toBeInTheDocument()})- it('should render high quality option', () => {- render(<IndexingSection {...defaultProps} />)+ it('should render both index method options', () => {+ renderComponent()- expect(screen.getByText(/stepTwo\.qualified/i)).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'stepTwo.qualified' })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'form.indexMethodEconomy' })).toBeInTheDocument()})- it('should render economy option', () => {- render(<IndexingSection {...defaultProps} />)+ it('should call setIndexMethod when the user selects a new index method', () => {+ const setIndexMethod = vi.fn()+ renderComponent({ setIndexMethod })- // May match multiple elements (title and tip)- expect(screen.getAllByText(/form\.indexMethodEconomy/i).length).toBeGreaterThan(0)- })+ fireEvent.click(screen.getByRole('button', { name: 'form.indexMethodEconomy' }))- it('should call setIndexMethod when index method changes', () => {- const setIndexMethod = vi.fn()- const { container } = render(<IndexingSection {...defaultProps} setIndexMethod={setIndexMethod} />)-- // Find the economy option card by looking for clickable elements containing the economy text- const economyOptions = screen.getAllByText(/form\.indexMethodEconomy/i)- if (economyOptions.length > 0) {- const economyCard = economyOptions[0].closest('[class*="cursor-pointer"]')- if (economyCard) {- fireEvent.click(economyCard)- }- }-- // The handler should be properly passed - verify component renders without crashing- expect(container).toBeInTheDocument()+ expect(setIndexMethod).toHaveBeenCalledWith(IndexingType.ECONOMICAL)})- it('should show upgrade warning when switching from economy to high quality', () => {- const economyDataset = { ...mockDataset, indexing_technique: IndexingType.ECONOMICAL }- render(- <IndexingSection- {...defaultProps}- currentDataset={economyDataset}- indexMethod={IndexingType.QUALIFIED}- />,- )+ it('should show an upgrade warning when moving from economy to high quality', () => {+ renderComponent({+ currentDataset: {+ ...mockDataset,+ indexing_technique: IndexingType.ECONOMICAL,+ },+ })- expect(screen.getByText(/form\.upgradeHighQualityTip/i)).toBeInTheDocument()+ expect(screen.getByText('form.upgradeHighQualityTip')).toBeInTheDocument()})- it('should not show upgrade warning when already on high quality', () => {- render(- <IndexingSection- {...defaultProps}- indexMethod={IndexingType.QUALIFIED}- />,- )+ it('should pass disabled state to the index method when embeddings are unavailable', () => {+ renderComponent({+ currentDataset: {+ ...mockDataset,+ embedding_available: false,+ },+ })- expect(screen.queryByText(/form\.upgradeHighQualityTip/i)).not.toBeInTheDocument()+ expect(screen.getByTestId('index-method')).toHaveAttribute('data-disabled', 'true')})- it('should disable index method when embedding is not available', () => {- const datasetWithoutEmbedding = { ...mockDataset, embedding_available: false }- render(<IndexingSection {...defaultProps} currentDataset={datasetWithoutEmbedding} />)+ it('should pass the keyword number and update handler through the index method mock', () => {+ const setKeywordNumber = vi.fn()+ renderComponent({+ keywordNumber: 15,+ setKeywordNumber,+ })- // Index method options should be disabled- // The exact implementation depends on the IndexMethod component- })- })+ expect(screen.getByTestId('index-method')).toHaveAttribute('data-keyword-number', '15')- describe('Embedding Model Section', () => {- it('should render embedding model when indexMethod is high_quality', () => {- render(<IndexingSection {...defaultProps} indexMethod={IndexingType.QUALIFIED} />)+ fireEvent.click(screen.getByRole('button', { name: 'keyword-number-increment' }))- expect(screen.getByText(/form\.embeddingModel/i)).toBeInTheDocument()+ expect(setKeywordNumber).toHaveBeenCalledWith(16)})+ })- it('should not render embedding model when indexMethod is economy', () => {- render(<IndexingSection {...defaultProps} indexMethod={IndexingType.ECONOMICAL} />)+ describe('Embedding Model Section', () => {+ it('should hide the embedding model selector for economy indexing', () => {+ renderComponent({ indexMethod: IndexingType.ECONOMICAL })- expect(screen.queryByText(/form\.embeddingModel/i)).not.toBeInTheDocument()+ expect(screen.queryByText('form.embeddingModel')).not.toBeInTheDocument()+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()})- it('should call setEmbeddingModel when model changes', () => {+ it('should call setEmbeddingModel when the user selects a model', () => {const setEmbeddingModel = vi.fn()- render(- <IndexingSection- {...defaultProps}- setEmbeddingModel={setEmbeddingModel}- indexMethod={IndexingType.QUALIFIED}- />,- )+ renderComponent({ setEmbeddingModel })++ fireEvent.click(screen.getByRole('button', { name: 'select-model' }))- // The embedding model selector should be rendered- expect(screen.getByText(/form\.embeddingModel/i)).toBeInTheDocument()+ expect(setEmbeddingModel).toHaveBeenCalledWith({+ provider: 'cohere',+ model: 'embed-english-v3.0',+ })})})describe('Summary Index Setting Section', () => {- it('should render summary index setting for high quality with text chunking', () => {- render(- <IndexingSection- {...defaultProps}- indexMethod={IndexingType.QUALIFIED}- />,- )-- // Summary index setting should be rendered based on conditions- // The exact rendering depends on the SummaryIndexSetting component- })-- it('should not render summary index setting for economy indexing', () => {- render(- <IndexingSection- {...defaultProps}- indexMethod={IndexingType.ECONOMICAL}- />,- )+ it('should render the summary index setting only for high quality text chunking', () => {+ renderComponent()+ expect(screen.getByTestId('summary-index-setting')).toBeInTheDocument()- // Summary index setting should not be rendered for economy+ renderComponent({+ indexMethod: IndexingType.ECONOMICAL,+ })+ expect(screen.getAllByTestId('summary-index-setting')).toHaveLength(1)})- it('should call handleSummaryIndexSettingChange when setting changes', () => {+ it('should call handleSummaryIndexSettingChange when the summary setting changes', () => {const handleSummaryIndexSettingChange = vi.fn()- render(- <IndexingSection- {...defaultProps}- handleSummaryIndexSettingChange={handleSummaryIndexSettingChange}- indexMethod={IndexingType.QUALIFIED}- />,- )+ renderComponent({ handleSummaryIndexSettingChange })++ fireEvent.click(screen.getByRole('button', { name: 'summary-enable' }))- // The handler should be properly passed+ expect(handleSummaryIndexSettingChange).toHaveBeenCalledWith({ enable: true })})})describe('Retrieval Settings Section', () => {- it('should render retrieval settings', () => {- render(<IndexingSection {...defaultProps} />)+ it('should render the retrieval learn more link', () => {+ renderComponent()- expect(screen.getByText(/form\.retrievalSetting\.title/i)).toBeInTheDocument()+ const learnMoreLink = screen.getByRole('link', { name: 'form.retrievalSetting.learnMore' })+ expect(learnMoreLink).toHaveAttribute('href', expect.stringContaining('setting-indexing-methods'))+ expect(screen.getByText('form.retrievalSetting.description')).toBeInTheDocument()})- it('should render learn more link for retrieval settings', () => {- render(<IndexingSection {...defaultProps} />)-- const learnMoreLinks = screen.getAllByText(/learnMore/i)- const retrievalLearnMore = learnMoreLinks.find(link =>- link.closest('a')?.href?.includes('setting-indexing-methods'),- )- expect(retrievalLearnMore).toBeInTheDocument()- })-- it('should render RetrievalMethodConfig for high quality indexing', () => {- render(<IndexingSection {...defaultProps} indexMethod={IndexingType.QUALIFIED} />)+ it('should render the high-quality retrieval config and propagate changes', () => {+ const setRetrievalConfig = vi.fn()+ renderComponent({ setRetrievalConfig })- // RetrievalMethodConfig should be rendered- expect(screen.getByText(/form\.retrievalSetting\.title/i)).toBeInTheDocument()- })+ expect(screen.getByTestId('retrieval-method-config')).toBeInTheDocument()- it('should render EconomicalRetrievalMethodConfig for economy indexing', () => {- render(<IndexingSection {...defaultProps} indexMethod={IndexingType.ECONOMICAL} />)+ fireEvent.click(screen.getByRole('button', { name: 'update-retrieval' }))- // EconomicalRetrievalMethodConfig should be rendered- expect(screen.getByText(/form\.retrievalSetting\.title/i)).toBeInTheDocument()+ expect(setRetrievalConfig).toHaveBeenCalledWith({+ ...mockRetrievalConfig,+ top_k: 6,+ })})- it('should call setRetrievalConfig when config changes', () => {+ it('should render the economical retrieval config for economy indexing', () => {const setRetrievalConfig = vi.fn()- render(<IndexingSection {...defaultProps} setRetrievalConfig={setRetrievalConfig} />)+ renderComponent({+ indexMethod: IndexingType.ECONOMICAL,+ setRetrievalConfig,+ })- // The handler should be properly passed- })+ expect(screen.getByTestId('economical-retrieval-method-config')).toBeInTheDocument()- it('should pass showMultiModalTip to RetrievalMethodConfig', () => {- render(<IndexingSection {...defaultProps} showMultiModalTip={true} />)+ fireEvent.click(screen.getByRole('button', { name: 'update-economy-retrieval' }))- // The tip should be passed to the config component+ expect(setRetrievalConfig).toHaveBeenCalledWith({+ ...mockRetrievalConfig,+ search_method: RETRIEVE_METHOD.keywordSearch,+ })})- })- describe('External Provider', () => {- it('should not render retrieval config for external provider', () => {- const externalDataset = { ...mockDataset, provider: 'external' }- render(<IndexingSection {...defaultProps} currentDataset={externalDataset} />)+ it('should pass the multimodal tip flag to the retrieval config', () => {+ renderComponent({ showMultiModalTip: true })- // Retrieval config should not be rendered for external provider- // This is handled by the parent component, but we verify the condition+ expect(screen.getByText('show-multimodal-tip')).toBeInTheDocument()})- })-- describe('Conditional Rendering', () => {- it('should show divider between sections', () => {- const { container } = render(<IndexingSection {...defaultProps} />)- // Dividers should be present- const dividers = container.querySelectorAll('.bg-divider-subtle')- expect(dividers.length).toBeGreaterThan(0)- })-- it('should not render index method when indexing_technique is not set', () => {- const datasetWithoutTechnique = { ...mockDataset, indexing_technique: undefined as unknown as IndexingType }- render(<IndexingSection {...defaultProps} currentDataset={datasetWithoutTechnique} indexMethod={undefined} />)+ it('should hide retrieval configuration for external datasets', () => {+ renderComponent({+ currentDataset: {+ ...mockDataset,+ provider: 'external',+ },+ })- expect(screen.queryByText(/form\.indexMethod/i)).not.toBeInTheDocument()+ expect(screen.queryByText('form.retrievalSetting.title')).not.toBeInTheDocument()+ expect(screen.queryByTestId('retrieval-method-config')).not.toBeInTheDocument()+ expect(screen.queryByTestId('economical-retrieval-method-config')).not.toBeInTheDocument()})})- describe('Keyword Number', () => {- it('should pass keywordNumber to IndexMethod', () => {- render(<IndexingSection {...defaultProps} keywordNumber={15} />)+ describe('Conditional Rendering', () => {+ it('should render dividers between visible sections', () => {+ renderComponent()- // The keyword number should be displayed in the economy option description- // The exact rendering depends on the IndexMethod component+ expect(screen.getAllByTestId('divider').length).toBeGreaterThan(0)})- it('should call setKeywordNumber when keyword number changes', () => {- const setKeywordNumber = vi.fn()- render(<IndexingSection {...defaultProps} setKeywordNumber={setKeywordNumber} />)+ it('should hide the index method section when the dataset lacks an indexing technique', () => {+ renderComponent({+ currentDataset: {+ ...mockDataset,+ indexing_technique: undefined as unknown as IndexingType,+ },+ indexMethod: undefined,+ })- // The handler should be properly passed+ expect(screen.queryByText('form.indexMethod')).not.toBeInTheDocument()+ expect(screen.queryByTestId('index-method')).not.toBeInTheDocument()})})describe('Props Updates', () => {- it('should update when indexMethod changes', () => {- const { rerender } = render(<IndexingSection {...defaultProps} indexMethod={IndexingType.QUALIFIED} />)+ it('should update the embedding model section when indexMethod changes', () => {+ const { rerender } = renderComponent()- expect(screen.getByText(/form\.embeddingModel/i)).toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toBeInTheDocument()rerender(<IndexingSection {...defaultProps} indexMethod={IndexingType.ECONOMICAL} />)- expect(screen.queryByText(/form\.embeddingModel/i)).not.toBeInTheDocument()+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()})- it('should update when currentDataset changes', () => {- const { rerender } = render(<IndexingSection {...defaultProps} />)+ it('should update the chunk structure section when currentDataset changes', () => {+ const { rerender } = renderComponent()- expect(screen.getByText(/form\.chunkStructure\.title/i)).toBeInTheDocument()+ expect(screen.getByTestId('chunk-structure')).toBeInTheDocument()- const datasetWithoutDocForm = { ...mockDataset, doc_form: undefined as unknown as ChunkingMode }- rerender(<IndexingSection {...defaultProps} currentDataset={datasetWithoutDocForm} />)+ rerender(+ <IndexingSection+ {...defaultProps}+ currentDataset={{+ ...mockDataset,+ doc_form: undefined as unknown as ChunkingMode,+ }}+ />,+ )- expect(screen.queryByText(/form\.chunkStructure\.title/i)).not.toBeInTheDocument()+ expect(screen.queryByTestId('chunk-structure')).not.toBeInTheDocument()})})describe('Undefined Dataset', () => {- it('should handle undefined currentDataset gracefully', () => {- render(<IndexingSection {...defaultProps} currentDataset={undefined} />)+ it('should render safely when currentDataset is undefined', () => {+ renderComponent({ currentDataset: undefined })- // Should not crash and should handle undefined gracefully- // Most sections should not render without a dataset+ expect(screen.queryByTestId('chunk-structure')).not.toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toBeInTheDocument()+ expect(screen.getByTestId('retrieval-method-config')).toBeInTheDocument()})})})diff --git a/web/app/components/datasets/settings/summary-index-setting.tsx b/web/app/components/datasets/settings/summary-index-setting.tsxindex a6b99e8dabb..8ddae1d1fcd 100644--- a/web/app/components/datasets/settings/summary-index-setting.tsx+++ b/web/app/components/datasets/settings/summary-index-setting.tsx@@ -63,7 +63,7 @@ const SummaryIndexSetting = ({return (<div><div className="flex h-6 items-center justify-between">- <div className="system-sm-semibold-uppercase flex items-center text-text-secondary">+ <div className="flex items-center text-text-secondary system-sm-semibold-uppercase">{t('form.summaryAutoGen', { ns: 'datasetSettings' })}<TooltiptriggerClassName="ml-1 h-4 w-4 shrink-0"@@ -80,7 +80,7 @@ const SummaryIndexSetting = ({{summaryIndexSetting?.enable && (<div>- <div className="system-xs-medium-uppercase mb-1.5 mt-2 flex h-6 items-center text-text-tertiary">+ <div className="mb-1.5 mt-2 flex h-6 items-center text-text-tertiary system-xs-medium-uppercase">{t('form.summaryModel', { ns: 'datasetSettings' })}</div><ModelSelector@@ -90,7 +90,7 @@ const SummaryIndexSetting = ({readonly={readonly}showDeprecatedWarnIcon/>- <div className="system-xs-medium-uppercase mt-3 flex h-6 items-center text-text-tertiary">+ <div className="mt-3 flex h-6 items-center text-text-tertiary system-xs-medium-uppercase">{t('form.summaryInstructions', { ns: 'datasetSettings' })}</div><Textarea@@ -111,12 +111,12 @@ const SummaryIndexSetting = ({<div className="space-y-4"><div className="flex gap-x-1"><div className="flex h-7 w-[180px] shrink-0 items-center pt-1">- <div className="system-sm-semibold text-text-secondary">+ <div className="text-text-secondary system-sm-semibold">{t('form.summaryAutoGen', { ns: 'datasetSettings' })}</div></div><div className="py-1.5">- <div className="system-sm-semibold flex items-center text-text-secondary">+ <div className="flex items-center text-text-secondary system-sm-semibold"><SwitchclassName="mr-2"value={summaryIndexSetting?.enable ?? false}@@ -127,7 +127,7 @@ const SummaryIndexSetting = ({summaryIndexSetting?.enable ? t('list.status.enabled', { ns: 'datasetDocuments' }) : t('list.status.disabled', { ns: 'datasetDocuments' })}</div>- <div className="system-sm-regular mt-2 text-text-tertiary">+ <div className="mt-2 text-text-tertiary system-sm-regular">{summaryIndexSetting?.enable && t('form.summaryAutoGenTip', { ns: 'datasetSettings' })}@@ -142,7 +142,7 @@ const SummaryIndexSetting = ({<><div className="flex gap-x-1"><div className="flex h-7 w-[180px] shrink-0 items-center pt-1">- <div className="system-sm-medium text-text-tertiary">+ <div className="text-text-tertiary system-sm-medium">{t('form.summaryModel', { ns: 'datasetSettings' })}</div></div>@@ -159,7 +159,7 @@ const SummaryIndexSetting = ({</div><div className="flex"><div className="flex h-7 w-[180px] shrink-0 items-center pt-1">- <div className="system-sm-medium text-text-tertiary">+ <div className="text-text-tertiary system-sm-medium">{t('form.summaryInstructions', { ns: 'datasetSettings' })}</div></div>@@ -188,7 +188,7 @@ const SummaryIndexSetting = ({onChange={handleSummaryIndexEnableChange}size="md"/>- <div className="system-sm-semibold text-text-secondary">+ <div className="text-text-secondary system-sm-semibold">{t('form.summaryAutoGen', { ns: 'datasetSettings' })}</div></div>@@ -196,7 +196,7 @@ const SummaryIndexSetting = ({summaryIndexSetting?.enable && (<><div>- <div className="system-sm-medium mb-1.5 flex h-6 items-center text-text-secondary">+ <div className="mb-1.5 flex h-6 items-center text-text-secondary system-sm-medium">{t('form.summaryModel', { ns: 'datasetSettings' })}</div><ModelSelector@@ -209,7 +209,7 @@ const SummaryIndexSetting = ({/></div><div>- <div className="system-sm-medium mb-1.5 flex h-6 items-center text-text-secondary">+ <div className="mb-1.5 flex h-6 items-center text-text-secondary system-sm-medium">{t('form.summaryInstructions', { ns: 'datasetSettings' })}</div><Textareadiff --git a/web/app/components/header/account-dropdown/workplace-selector/index.tsx b/web/app/components/header/account-dropdown/workplace-selector/index.tsxindex 528686a26aa..abaad6d8a1a 100644--- a/web/app/components/header/account-dropdown/workplace-selector/index.tsx+++ b/web/app/components/header/account-dropdown/workplace-selector/index.tsx@@ -46,7 +46,7 @@ const WorkplaceSelector = () => {<span className="h-6 bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text align-middle font-semibold uppercase leading-6 text-shadow-shadow-1 opacity-90">{currentWorkspace?.name[0]?.toLocaleUpperCase()}</span></div><div className="flex min-w-0 items-center">- <div className="system-sm-medium min-w-0 max-w-[149px] truncate text-text-secondary max-[800px]:hidden">{currentWorkspace?.name}</div>+ <div className="min-w-0 max-w-[149px] truncate text-text-secondary system-sm-medium max-[800px]:hidden">{currentWorkspace?.name}</div><RiArrowDownSLine className="h-4 w-4 shrink-0 text-text-secondary" /></div></MenuButton>@@ -68,9 +68,9 @@ const WorkplaceSelector = () => {`,)}>- <div className="flex w-full flex-col items-start self-stretch rounded-xl border-[0.5px] border-components-panel-border p-1 pb-2 shadow-lg ">+ <div className="flex w-full flex-col items-start self-stretch rounded-xl border-[0.5px] border-components-panel-border p-1 pb-2 shadow-lg"><div className="flex items-start self-stretch px-3 pb-0.5 pt-1">- <span className="system-xs-medium-uppercase flex-1 text-text-tertiary">{t('userProfile.workspace', { ns: 'common' })}</span>+ <span className="flex-1 text-text-tertiary system-xs-medium-uppercase">{t('userProfile.workspace', { ns: 'common' })}</span></div>{workspaces.map(workspace => (@@ -78,7 +78,7 @@ const WorkplaceSelector = () => {<div className="flex h-6 w-6 shrink-0 items-center justify-center rounded-md bg-components-icon-bg-blue-solid text-[13px]"><span className="h-6 bg-gradient-to-r from-components-avatar-shape-fill-stop-0 to-components-avatar-shape-fill-stop-100 bg-clip-text align-middle font-semibold uppercase leading-6 text-shadow-shadow-1 opacity-90">{workspace?.name[0]?.toLocaleUpperCase()}</span></div>- <div className="system-md-regular line-clamp-1 grow cursor-pointer overflow-hidden text-ellipsis text-text-secondary">{workspace.name}</div>+ <div className="line-clamp-1 grow cursor-pointer overflow-hidden text-ellipsis text-text-secondary system-md-regular">{workspace.name}</div><PlanBadge plan={workspace.plan as Plan} /></div>))diff --git a/web/app/components/header/account-setting/__tests__/index.spec.tsx b/web/app/components/header/account-setting/__tests__/index.spec.tsxindex f5a8dd5c01d..38cbb58a1b5 100644--- a/web/app/components/header/account-setting/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/index.spec.tsx@@ -1,15 +1,16 @@-import type { ComponentProps, ReactNode } from 'react'+import type { AccountSettingTab } from '../constants'import type { AppContextValue } from '@/context/app-context'import { QueryClient, QueryClientProvider } from '@tanstack/react-query'-import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'-import userEvent from '@testing-library/user-event'-import { useEffect } from 'react'+import { fireEvent, render, screen } from '@testing-library/react'+import { useState } from 'react'import { useAppContext } from '@/context/app-context'import { baseProviderContextValue, useProviderContext } from '@/context/provider-context'import useBreakpoints, { MediaType } from '@/hooks/use-breakpoints'import { ACCOUNT_SETTING_TAB } from '../constants'import AccountSetting from '../index'+const mockResetModelProviderListExpanded = vi.fn()+vi.mock('@/context/provider-context', async (importOriginal) => {const actual = await importOriginal<typeof import('@/context/provider-context')>()return {@@ -46,65 +47,27 @@ vi.mock('@/hooks/use-breakpoints', () => ({default: vi.fn(),}))-vi.mock('@/app/components/billing/billing-page', () => ({- default: () => <div data-testid="billing-page">Billing Page</div>,-}))--vi.mock('@/app/components/custom/custom-page', () => ({- default: () => <div data-testid="custom-page">Custom Page</div>,+vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useDefaultModel: vi.fn(() => ({ data: null, isLoading: false })),+ useUpdateDefaultModel: vi.fn(() => ({ trigger: vi.fn() })),+ useUpdateModelList: vi.fn(() => vi.fn()),+ useInvalidateDefaultModel: vi.fn(() => vi.fn()),+ useModelList: vi.fn(() => ({ data: [], isLoading: false })),+ useSystemDefaultModelAndModelList: vi.fn(() => [null, vi.fn()]),}))-vi.mock('@/app/components/header/account-setting/api-based-extension-page', () => ({- default: () => <div data-testid="api-based-extension-page">API Based Extension Page</div>,+vi.mock('@/app/components/header/account-setting/model-provider-page/atoms', () => ({+ useResetModelProviderListExpanded: () => mockResetModelProviderListExpanded,}))-vi.mock('@/app/components/header/account-setting/data-source-page-new', () => ({- default: () => <div data-testid="data-source-page">Data Source Page</div>,+vi.mock('@/service/use-datasource', () => ({+ useGetDataSourceListAuth: vi.fn(() => ({ data: { result: [] } })),}))-vi.mock('@/app/components/header/account-setting/language-page', () => ({- default: () => <div data-testid="language-page">Language Page</div>,-}))--vi.mock('@/app/components/header/account-setting/members-page', () => ({- default: () => <div data-testid="members-page">Members Page</div>,-}))--vi.mock('@/app/components/header/account-setting/model-provider-page', () => ({- default: ({ searchText }: { searchText: string }) => (- <div data-testid="provider-page">- {`provider-search:${searchText}`}- </div>- ),-}))--vi.mock('@/app/components/header/account-setting/menu-dialog', () => ({- default: function MockMenuDialog({- children,- onClose,- show,- }: {- children: ReactNode- onClose: () => void- show?: boolean- }) {- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key === 'Escape')- onClose()- }-- document.addEventListener('keydown', handleKeyDown)- return () => {- document.removeEventListener('keydown', handleKeyDown)- }- }, [onClose])-- if (!show)- return null-- return <div role="dialog">{children}</div>- },+vi.mock('@/service/use-common', () => ({+ useApiBasedExtensions: vi.fn(() => ({ data: [], isPending: false })),+ useMembers: vi.fn(() => ({ data: { accounts: [] }, refetch: vi.fn() })),+ useProviderContext: vi.fn(),}))const baseAppContextValue: AppContextValue = {@@ -151,30 +114,37 @@ const baseAppContextValue: AppContextValue = {describe('AccountSetting', () => {const mockOnCancel = vi.fn()const mockOnTabChange = vi.fn()-- const renderAccountSetting = (props: Partial<ComponentProps<typeof AccountSetting>> = {}) => {- const queryClient = new QueryClient()- const mergedProps: ComponentProps<typeof AccountSetting> = {- onCancel: mockOnCancel,- ...props,+ const renderAccountSetting = (props?: {+ initialTab?: AccountSettingTab+ onCancel?: () => void+ onTabChange?: (tab: AccountSettingTab) => void+ }) => {+ const {+ initialTab = ACCOUNT_SETTING_TAB.MEMBERS,+ onCancel = mockOnCancel,+ onTabChange = mockOnTabChange,+ } = props ?? {}++ const StatefulAccountSetting = () => {+ const [activeTab, setActiveTab] = useState<AccountSettingTab>(initialTab)++ return (+ <AccountSetting+ onCancelAction={onCancel}+ activeTab={activeTab}+ onTabChangeAction={(tab) => {+ setActiveTab(tab)+ onTabChange(tab)+ }}+ />+ )}- const view = render(- <QueryClientProvider client={queryClient}>- <AccountSetting {...mergedProps} />+ return render(+ <QueryClientProvider client={new QueryClient()}>+ <StatefulAccountSetting /></QueryClientProvider>,)-- return {- ...view,- rerenderAccountSetting(nextProps: Partial<ComponentProps<typeof AccountSetting>>) {- view.rerender(- <QueryClientProvider client={queryClient}>- <AccountSetting {...mergedProps} {...nextProps} />- </QueryClientProvider>,- )- },- }}beforeEach(() => {@@ -190,155 +160,171 @@ describe('AccountSetting', () => {describe('Rendering', () => {it('should render the sidebar with correct menu items', () => {+ // ActrenderAccountSetting()+ // Assertexpect(screen.getByText('common.userProfile.settings')).toBeInTheDocument()- expect(screen.getByTitle('common.settings.provider')).toBeInTheDocument()- expect(screen.getByTitle('common.settings.members')).toBeInTheDocument()- expect(screen.getByTitle('common.settings.billing')).toBeInTheDocument()- expect(screen.getByTitle('common.settings.dataSource')).toBeInTheDocument()- expect(screen.getByTitle('common.settings.apiBasedExtension')).toBeInTheDocument()- expect(screen.getByTitle('custom.custom')).toBeInTheDocument()- expect(screen.getByTitle('common.settings.language')).toBeInTheDocument()- expect(screen.getByTestId('members-page')).toBeInTheDocument()- })-- it('should respect the activeTab prop', () => {- renderAccountSetting({ activeTab: ACCOUNT_SETTING_TAB.DATA_SOURCE })-- expect(screen.getByTestId('data-source-page')).toBeInTheDocument()+ expect(screen.getByText('common.settings.provider')).toBeInTheDocument()+ expect(screen.getAllByText('common.settings.members').length).toBeGreaterThan(0)+ expect(screen.getByText('common.settings.billing')).toBeInTheDocument()+ expect(screen.getByText('common.settings.dataSource')).toBeInTheDocument()+ expect(screen.getByText('common.settings.apiBasedExtension')).toBeInTheDocument()+ expect(screen.getByText('custom.custom')).toBeInTheDocument()+ expect(screen.getAllByText('common.settings.language').length).toBeGreaterThan(0)})- it('should sync the rendered page when activeTab changes', async () => {- const { rerenderAccountSetting } = renderAccountSetting({- activeTab: ACCOUNT_SETTING_TAB.DATA_SOURCE,- })-- expect(screen.getByTestId('data-source-page')).toBeInTheDocument()-- rerenderAccountSetting({- activeTab: ACCOUNT_SETTING_TAB.CUSTOM,- })+ it('should respect the initial tab', () => {+ // Act+ renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.DATA_SOURCE })- await waitFor(() => {- expect(screen.getByTestId('custom-page')).toBeInTheDocument()- })+ // Assert+ // Check that the active item title is Data Source+ const titles = screen.getAllByText('common.settings.dataSource')+ // One in sidebar, one in header.+ expect(titles.length).toBeGreaterThan(1)})it('should hide sidebar labels on mobile', () => {+ // Arrangevi.mocked(useBreakpoints).mockReturnValue(MediaType.mobile)+ // ActrenderAccountSetting()+ // Assert+ // On mobile, the labels should not be rendered as per the implementationexpect(screen.queryByText('common.settings.provider')).not.toBeInTheDocument()})it('should filter items for dataset operator', () => {+ // Arrangevi.mocked(useAppContext).mockReturnValue({...baseAppContextValue,isCurrentWorkspaceDatasetOperator: true,})+ // ActrenderAccountSetting()- expect(screen.queryByTitle('common.settings.provider')).not.toBeInTheDocument()- expect(screen.queryByTitle('common.settings.members')).not.toBeInTheDocument()- expect(screen.getByTitle('common.settings.language')).toBeInTheDocument()+ // Assert+ expect(screen.queryByText('common.settings.provider')).not.toBeInTheDocument()+ expect(screen.queryByText('common.settings.members')).not.toBeInTheDocument()+ expect(screen.getByText('common.settings.language')).toBeInTheDocument()})it('should hide billing and custom tabs when disabled', () => {+ // Arrangevi.mocked(useProviderContext).mockReturnValue({...baseProviderContextValue,enableBilling: false,enableReplaceWebAppLogo: false,})+ // ActrenderAccountSetting()- expect(screen.queryByTitle('common.settings.billing')).not.toBeInTheDocument()- expect(screen.queryByTitle('custom.custom')).not.toBeInTheDocument()+ // Assert+ expect(screen.queryByText('common.settings.billing')).not.toBeInTheDocument()+ expect(screen.queryByText('custom.custom')).not.toBeInTheDocument()})})describe('Tab Navigation', () => {- it('should change active tab when clicking on a menu item', async () => {- const user = userEvent.setup()-+ it('should change active tab when clicking on menu item', () => {+ // ArrangerenderAccountSetting({ onTabChange: mockOnTabChange })- await user.click(screen.getByTitle('common.settings.provider'))+ // Act+ fireEvent.click(screen.getByText('common.settings.provider'))+ // Assertexpect(mockOnTabChange).toHaveBeenCalledWith(ACCOUNT_SETTING_TAB.PROVIDER)- expect(screen.getByTestId('provider-page')).toBeInTheDocument()+ // Check for content from ModelProviderPage+ expect(screen.getByText('common.modelProvider.models')).toBeInTheDocument()})- it.each([- ['common.settings.billing', 'billing-page'],- ['common.settings.dataSource', 'data-source-page'],- ['common.settings.apiBasedExtension', 'api-based-extension-page'],- ['custom.custom', 'custom-page'],- ['common.settings.language', 'language-page'],- ['common.settings.members', 'members-page'],- ])('should render the "%s" page when its sidebar item is selected', async (menuTitle, pageTestId) => {- const user = userEvent.setup()-+ it('should navigate through various tabs and show correct details', () => {+ // Act & AssertrenderAccountSetting()- await user.click(screen.getByTitle(menuTitle))+ // Billing+ fireEvent.click(screen.getByText('common.settings.billing'))+ // Billing Page renders plansCommon.plan if data is loaded, or generic text.+ // Checking for title in header which is always there+ expect(screen.getAllByText('common.settings.billing').length).toBeGreaterThan(1)- expect(screen.getByTestId(pageTestId)).toBeInTheDocument()- })- })+ // Data Source+ fireEvent.click(screen.getByText('common.settings.dataSource'))+ expect(screen.getAllByText('common.settings.dataSource').length).toBeGreaterThan(1)- describe('Interactions', () => {- it('should call onCancel when clicking the close button', async () => {- const user = userEvent.setup()+ // API Based Extension+ fireEvent.click(screen.getByText('common.settings.apiBasedExtension'))+ expect(screen.getAllByText('common.settings.apiBasedExtension').length).toBeGreaterThan(1)- renderAccountSetting()+ // Custom+ fireEvent.click(screen.getByText('custom.custom'))+ // Custom Page uses 'custom.custom' key as well.+ expect(screen.getAllByText('custom.custom').length).toBeGreaterThan(1)- const closeControls = screen.getByText('ESC').parentElement+ // Language+ fireEvent.click(screen.getAllByText('common.settings.language')[0])+ expect(screen.getAllByText('common.settings.language').length).toBeGreaterThan(1)- expect(closeControls).not.toBeNull()- if (!closeControls)- throw new Error('Close controls are missing')+ // Members+ fireEvent.click(screen.getAllByText('common.settings.members')[0])+ expect(screen.getAllByText('common.settings.members').length).toBeGreaterThan(1)+ })+ })- await user.click(within(closeControls).getByRole('button'))+ describe('Interactions', () => {+ it('should call onCancel when clicking close button', () => {+ // Act+ renderAccountSetting()+ const closeIcon = document.querySelector('.i-ri-close-line')+ const closeButton = closeIcon?.closest('button')+ expect(closeButton).not.toBeNull()+ fireEvent.click(closeButton!)+ // Assertexpect(mockOnCancel).toHaveBeenCalled()})it('should call onCancel when pressing Escape key', () => {+ // ActrenderAccountSetting()-fireEvent.keyDown(document, { key: 'Escape' })+ // Assertexpect(mockOnCancel).toHaveBeenCalled()})- it('should update search value in the provider tab', async () => {- const user = userEvent.setup()-- renderAccountSetting()-- await user.click(screen.getByTitle('common.settings.provider'))+ it('should update search value in provider tab', () => {+ // Arrange+ renderAccountSetting({ initialTab: ACCOUNT_SETTING_TAB.PROVIDER })+ // Actconst input = screen.getByRole('textbox')- await user.type(input, 'test-search')+ fireEvent.change(input, { target: { value: 'test-search' } })+ // Assertexpect(input).toHaveValue('test-search')- expect(screen.getByText('provider-search:test-search')).toBeInTheDocument()+ expect(screen.getByText('common.modelProvider.models')).toBeInTheDocument()})it('should handle scroll event in panel', () => {+ // ActrenderAccountSetting()-const scrollContainer = screen.getByRole('dialog').querySelector('.overflow-y-auto')+ // Assertexpect(scrollContainer).toBeInTheDocument()if (scrollContainer) {+ // Scroll downfireEvent.scroll(scrollContainer, { target: { scrollTop: 100 } })expect(scrollContainer).toHaveClass('overflow-y-auto')+ // Scroll back upfireEvent.scroll(scrollContainer, { target: { scrollTop: 0 } })}})diff --git a/web/app/components/header/account-setting/__tests__/menu-dialog.spec.tsx b/web/app/components/header/account-setting/__tests__/menu-dialog.spec.tsxindex 212f978cbf4..b69b9e89b2c 100644--- a/web/app/components/header/account-setting/__tests__/menu-dialog.spec.tsx+++ b/web/app/components/header/account-setting/__tests__/menu-dialog.spec.tsx@@ -40,8 +40,7 @@ describe('MenuDialog', () => {)// Assert- const panel = screen.getByRole('dialog').querySelector('.custom-class')- expect(panel).toBeInTheDocument()+ expect(screen.getByRole('dialog')).toHaveClass('custom-class')})})diff --git a/web/app/components/header/account-setting/index.tsx b/web/app/components/header/account-setting/index.tsxindex 45d8dde8a6b..7e77af2e5f5 100644--- a/web/app/components/header/account-setting/index.tsx+++ b/web/app/components/header/account-setting/index.tsx@@ -1,6 +1,6 @@'use client'import type { AccountSettingTab } from '@/app/components/header/account-setting/constants'-import { useEffect, useRef, useState } from 'react'+import { useCallback, useEffect, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import SearchInput from '@/app/components/base/search-input'import BillingPage from '@/app/components/billing/billing-page'@@ -20,15 +20,16 @@ import DataSourcePage from './data-source-page-new'import LanguagePage from './language-page'import MembersPage from './members-page'import ModelProviderPage from './model-provider-page'+import { useResetModelProviderListExpanded } from './model-provider-page/atoms'const iconClassName = `w-5 h-5 mr-2`type IAccountSettingProps = {- onCancel: () => void- activeTab?: AccountSettingTab- onTabChange?: (tab: AccountSettingTab) => void+ onCancelAction: () => void+ activeTab: AccountSettingTab+ onTabChangeAction: (tab: AccountSettingTab) => void}type GroupItem = {@@ -40,14 +41,12 @@ type GroupItem = {}export default function AccountSetting({- onCancel,- activeTab = ACCOUNT_SETTING_TAB.MEMBERS,- onTabChange,+ onCancelAction,+ activeTab,+ onTabChangeAction,}: IAccountSettingProps) {- const [activeMenu, setActiveMenu] = useState<AccountSettingTab>(activeTab)- useEffect(() => {- setActiveMenu(activeTab)- }, [activeTab])+ const resetModelProviderListExpanded = useResetModelProviderListExpanded()+ const activeMenu = activeTabconst { t } = useTranslation()const { enableBilling, enableReplaceWebAppLogo } = useProviderContext()const { isCurrentWorkspaceDatasetOperator } = useAppContext()@@ -148,10 +147,22 @@ export default function AccountSetting({const [searchValue, setSearchValue] = useState<string>('')+ const handleTabChange = useCallback((tab: AccountSettingTab) => {+ if (tab === ACCOUNT_SETTING_TAB.PROVIDER)+ resetModelProviderListExpanded()++ onTabChangeAction(tab)+ }, [onTabChangeAction, resetModelProviderListExpanded])++ const handleClose = useCallback(() => {+ resetModelProviderListExpanded()+ onCancelAction()+ }, [onCancelAction, resetModelProviderListExpanded])+return (<MenuDialogshow- onClose={onCancel}+ onClose={handleClose}><div className="mx-auto flex h-[100vh] max-w-[1048px]"><div className="flex w-[44px] flex-col border-r border-divider-burn pl-4 pr-6 sm:w-[224px]">@@ -166,21 +177,22 @@ export default function AccountSetting({<div>{menuItem.items.map(item => (- <div+ <button+ type="button"key={item.key}className={cn(- 'mb-0.5 flex h-[37px] cursor-pointer items-center rounded-lg p-1 pl-3 text-sm',+ 'mb-0.5 flex h-[37px] w-full items-center rounded-lg p-1 pl-3 text-left text-sm',activeMenu === item.key ? 'bg-state-base-active text-components-menu-item-text-active system-sm-semibold' : 'text-components-menu-item-text system-sm-medium',)}+ aria-label={item.name}title={item.name}onClick={() => {- setActiveMenu(item.key)- onTabChange?.(item.key)+ handleTabChange(item.key)}}>{activeMenu === item.key ? item.activeIcon : item.icon}{!isMobile && <div className="truncate">{item.name}</div>}- </div>+ </button>))}</div>@@ -195,7 +207,8 @@ export default function AccountSetting({variant="tertiary"size="large"className="px-2"- onClick={onCancel}+ aria-label={t('operation.close', { ns: 'common' })}+ onClick={handleClose}><span className="i-ri-close-line h-5 w-5" /></Button>diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsxindex 794aad9e0ea..bd076abf11f 100644--- a/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/members-page/edit-workspace-modal/__tests__/index.spec.tsx@@ -1,6 +1,6 @@import type { AppContextValue } from '@/context/app-context'import type { ICurrentWorkspace } from '@/models/common'-import { render, screen, waitFor } from '@testing-library/react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { vi } from 'vitest'import { ToastContext } from '@/app/components/base/toast/context'@@ -40,33 +40,22 @@ describe('EditWorkspaceModal', () => {expect(await screen.findByDisplayValue('Test Workspace')).toBeInTheDocument()})- it('should let user edit workspace name', async () => {- const user = userEvent.setup()-+ it('should render on the base/ui overlay layer', async () => {renderModal()- const input = screen.getByPlaceholderText(/account\.workspaceNamePlaceholder/i)- await user.clear(input)- await user.type(input, 'New Workspace Name')-- expect(input).toHaveValue('New Workspace Name')+ expect(await screen.findByRole('dialog')).toHaveClass('z-[1002]')})- it('should reset name to current workspace name when cleared', async () => {+ it('should let user edit workspace name', async () => {const user = userEvent.setup()renderModal()- const input = screen.getByPlaceholderText(/account\.workspaceNamePlaceholder/i)+ const input = screen.getByLabelText(/account\.workspaceName/i)await user.clear(input)await user.type(input, 'New Workspace Name')- expect(input).toHaveValue('New Workspace Name')-- // Click the clear button (Input component clear button)- const clearBtn = screen.getByTestId('input-clear')- await user.click(clearBtn)- expect(input).toHaveValue('Test Workspace')+ expect(input).toHaveValue('New Workspace Name')})it('should submit update when confirming as owner', async () => {@@ -77,10 +66,10 @@ describe('EditWorkspaceModal', () => {renderModal()- const input = screen.getByPlaceholderText(/account\.workspaceNamePlaceholder/i)+ const input = screen.getByLabelText(/account\.workspaceName/i)await user.clear(input)await user.type(input, 'Renamed Workspace')- await user.click(screen.getByTestId('edit-workspace-confirm'))+ await user.click(screen.getByTestId('edit-workspace-save'))await waitFor(() => {expect(updateWorkspaceInfo).toHaveBeenCalledWith({@@ -89,6 +78,8 @@ describe('EditWorkspaceModal', () => {})expect(mockAssign).toHaveBeenCalledWith('http://localhost')})++ expect(mockOnCancel).not.toHaveBeenCalled()})it('should show error toast when update fails', async () => {@@ -98,7 +89,10 @@ describe('EditWorkspaceModal', () => {renderModal()- await user.click(screen.getByTestId('edit-workspace-confirm'))+ const input = screen.getByLabelText(/account\.workspaceName/i)+ await user.clear(input)+ await user.type(input, 'Broken Workspace')+ await user.click(screen.getByTestId('edit-workspace-save'))await waitFor(() => {expect(mockNotify).toHaveBeenCalledWith(expect.objectContaining({@@ -107,6 +101,40 @@ describe('EditWorkspaceModal', () => {})})+ it('should disable save button when there are no changes', async () => {+ renderModal()++ expect(screen.getByTestId('edit-workspace-save')).toBeDisabled()+ })++ it('should disable save button and show error when the name is empty', async () => {+ const user = userEvent.setup()++ renderModal()++ const input = screen.getByLabelText(/account\.workspaceName/i)+ await user.clear(input)++ expect(screen.getByTestId('edit-workspace-save')).toBeDisabled()+ expect(input).toHaveAttribute('aria-invalid', 'true')+ expect(screen.getByTestId('edit-workspace-error')).toBeInTheDocument()+ })++ it('should not submit when the form is submitted while save is disabled', async () => {+ renderModal()++ const saveButton = screen.getByTestId('edit-workspace-save')+ const form = saveButton.closest('form')++ expect(saveButton).toBeDisabled()+ expect(form).not.toBeNull()++ fireEvent.submit(form!)++ expect(updateWorkspaceInfo).not.toHaveBeenCalled()+ expect(mockNotify).not.toHaveBeenCalled()+ })+it('should disable confirm button for non-owners', async () => {vi.mocked(useAppContext).mockReturnValue({currentWorkspace: { name: 'Test Workspace' } as ICurrentWorkspace,@@ -115,7 +143,7 @@ describe('EditWorkspaceModal', () => {renderModal()- expect(screen.getByTestId('edit-workspace-confirm')).toBeDisabled()+ expect(screen.getByTestId('edit-workspace-save')).toBeDisabled()})it('should call onCancel when close icon is clicked', async () => {@@ -133,4 +161,14 @@ describe('EditWorkspaceModal', () => {await user.click(screen.getByTestId('edit-workspace-cancel'))expect(mockOnCancel).toHaveBeenCalled()})++ it('should call onCancel when Escape key is pressed', async () => {+ renderModal()++ fireEvent.keyDown(document, { key: 'Escape' })++ await waitFor(() => {+ expect(mockOnCancel).toHaveBeenCalled()+ })+ })})diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/dialog.spec.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-modal/dialog.spec.tsxnew file mode 100644index 00000000000..f489d649128--- /dev/null+++ b/web/app/components/header/account-setting/members-page/edit-workspace-modal/dialog.spec.tsx@@ -0,0 +1,57 @@+import type { ReactNode } from 'react'+import { render } from '@testing-library/react'+import { ToastContext } from '@/app/components/base/toast/context'+import { useAppContext } from '@/context/app-context'+import EditWorkspaceModal from './index'++type DialogProps = {+ children: ReactNode+ open?: boolean+ onOpenChange?: (open: boolean) => void+}++let latestOnOpenChange: DialogProps['onOpenChange']++vi.mock('@/app/components/base/ui/dialog', () => ({+ Dialog: ({ children, onOpenChange }: DialogProps) => {+ latestOnOpenChange = onOpenChange+ return <div data-testid="dialog">{children}</div>+ },+ DialogCloseButton: ({ ...props }: Record<string, unknown>) => <button {...props} />,+ DialogContent: ({ children, className }: { children: ReactNode, className?: string }) => (+ <div className={className}>{children}</div>+ ),+ DialogTitle: ({ children, className }: { children: ReactNode, className?: string }) => (+ <div className={className}>{children}</div>+ ),+}))++vi.mock('@/context/app-context', () => ({+ useAppContext: vi.fn(),+}))++describe('EditWorkspaceModal dialog lifecycle', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ latestOnOpenChange = undefined+ vi.mocked(useAppContext).mockReturnValue({+ currentWorkspace: { name: 'Test Workspace' },+ isCurrentWorkspaceOwner: true,+ } as never)+ })++ it('should only call onCancel when the dialog requests closing', () => {+ const onCancel = vi.fn()++ render(+ <ToastContext.Provider value={{ notify: vi.fn(), close: vi.fn() }}>+ <EditWorkspaceModal onCancel={onCancel} />+ </ToastContext.Provider>,+ )++ latestOnOpenChange?.(true)+ latestOnOpenChange?.(false)++ expect(onCancel).toHaveBeenCalledTimes(1)+ })+})diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.module.css b/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.module.cssdeleted file mode 100644index e69de29bb2d..00000000000diff --git a/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx b/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsxindex 1c3984b0b59..1707a010ae9 100644--- a/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx+++ b/web/app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx@@ -1,20 +1,19 @@'use client'-import { noop } from 'es-toolkit/function'-import { useState } from 'react'+import { useId, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import { useContext } from 'use-context-selector'import Button from '@/app/components/base/button'import Input from '@/app/components/base/input'-import Modal from '@/app/components/base/modal'import { ToastContext } from '@/app/components/base/toast/context'+import { Dialog, DialogCloseButton, DialogContent, DialogTitle } from '@/app/components/base/ui/dialog'import { useAppContext } from '@/context/app-context'import { updateWorkspaceInfo } from '@/service/common'import { cn } from '@/utils/classnames'-import s from './index.module.css'type IEditWorkspaceModalProps = {onCancel: () => void}+const EditWorkspaceModal = ({onCancel,}: IEditWorkspaceModalProps) => {@@ -22,13 +21,33 @@ const EditWorkspaceModal = ({const { notify } = useContext(ToastContext)const { currentWorkspace, isCurrentWorkspaceOwner } = useAppContext()const [name, setName] = useState<string>(currentWorkspace.name)+ const [isSubmitting, setIsSubmitting] = useState(false)+ const inputId = useId()+ const errorId = useId()+ const normalizedName = name.trim()+ const hasChanges = normalizedName !== currentWorkspace.name+ const hasError = normalizedName.length === 0+ const isSaveDisabled = !isCurrentWorkspaceOwner || !hasChanges || hasError || isSubmitting+ const nameErrorMessage = useMemo(() => {+ if (!hasError)+ return ''++ return t('errorMsg.fieldRequired', {+ ns: 'common',+ field: t('account.workspaceName', { ns: 'common' }),+ })+ }, [hasError, t])++ const changeWorkspaceInfo = async () => {+ if (isSaveDisabled)+ return- const changeWorkspaceInfo = async (name: string) => {+ setIsSubmitting(true)try {await updateWorkspaceInfo({url: '/workspaces/info',body: {- name,+ name: normalizedName,},})notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })@@ -37,33 +56,74 @@ const EditWorkspaceModal = ({catch {notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })}+ finally {+ setIsSubmitting(false)+ }}return (- <div className={cn(s.wrap)}>- <Modal overflowVisible isShow onClose={noop} className={cn(s.modal)}>- <div className="mb-2 flex justify-between">- <div className="text-xl font-semibold text-text-primary" data-testid="edit-workspace-title">{t('account.editWorkspaceInfo', { ns: 'common' })}</div>- <div className="i-ri-close-line h-4 w-4 cursor-pointer text-text-tertiary" data-testid="edit-workspace-close" onClick={onCancel} />- </div>- <div>- <div className="mb-2 text-sm font-medium text-text-primary">{t('account.workspaceName', { ns: 'common' })}</div>- <Input- className="mb-2"- value={name}- placeholder={t('account.workspaceNamePlaceholder', { ns: 'common' })}- onChange={(e) => {- setName(e.target.value)- }}- onClear={() => {- setName(currentWorkspace.name)- }}- showClearIcon- />+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open)+ onCancel()+ }}+ >+ <DialogContent+ backdropProps={{ forceRender: true }}+ className="overflow-visible"+ >+ <DialogCloseButton data-testid="edit-workspace-close" />++ <form+ className="flex flex-col"+ onSubmit={(e) => {+ e.preventDefault()+ void changeWorkspaceInfo()+ }}+ >+ <div className="mb-4 pr-8">+ <DialogTitle className="text-xl font-semibold text-text-primary" data-testid="edit-workspace-title">+ {t('account.editWorkspaceInfo', { ns: 'common' })}+ </DialogTitle>+ </div>++ <div className="space-y-2">+ <label htmlFor={inputId} className="block text-sm font-medium text-text-primary">+ {t('account.workspaceName', { ns: 'common' })}+ </label>+ <Input+ id={inputId}+ autoFocus+ value={name}+ placeholder={t('account.workspaceNamePlaceholder', { ns: 'common' })}+ onChange={(e) => {+ setName(e.target.value)+ }}+ aria-invalid={hasError}+ aria-describedby={hasError ? errorId : undefined}+ className={cn(+ hasError && 'border-components-input-border-destructive bg-components-input-bg-destructive hover:border-components-input-border-destructive hover:bg-components-input-bg-destructive focus:border-components-input-border-destructive focus:bg-components-input-bg-destructive',+ )}+ />+ <div className="min-h-6">+ {hasError && (+ <p+ id={errorId}+ data-testid="edit-workspace-error"+ className="text-text-destructive system-xs-regular"+ role="alert"+ >+ {nameErrorMessage}+ </p>+ )}+ </div>+ </div><div className="sticky bottom-0 -mx-2 mt-2 flex flex-wrap items-center justify-end gap-x-2 bg-components-panel-bg px-2 pt-4"><Buttonsize="large"+ type="button"data-testid="edit-workspace-cancel"onClick={onCancel}>@@ -71,21 +131,22 @@ const EditWorkspaceModal = ({</Button><Buttonsize="large"+ type="submit"variant="primary"- data-testid="edit-workspace-confirm"- onClick={() => {- changeWorkspaceInfo(name)- onCancel()- }}- disabled={!isCurrentWorkspaceOwner}+ data-testid="edit-workspace-save"+ disabled={isSaveDisabled}+ loading={isSubmitting}>- {t('operation.confirm', { ns: 'common' })}+ {t(+ isSubmitting ? 'operation.saving' : 'operation.save',+ { ns: 'common' },+ )}</Button></div>-- </div>- </Modal>- </div>+ </form>+ </DialogContent>+ </Dialog>)}+export default EditWorkspaceModaldiff --git a/web/app/components/header/account-setting/members-page/index.tsx b/web/app/components/header/account-setting/members-page/index.tsxindex fb81e83d6df..97f5d10b1bc 100644--- a/web/app/components/header/account-setting/members-page/index.tsx+++ b/web/app/components/header/account-setting/members-page/index.tsx@@ -3,7 +3,7 @@ import type { InvitationResult } from '@/models/common'import { useState } from 'react'import { useTranslation } from 'react-i18next'import { Avatar } from '@/app/components/base/avatar'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { NUM_INFINITE } from '@/app/components/billing/config'import { Plan } from '@/app/components/billing/type'import UpgradeBtn from '@/app/components/billing/upgrade-btn'@@ -59,20 +59,25 @@ const MembersPage = () => {<span>{currentWorkspace?.name}</span>{isCurrentWorkspaceOwner && (<span>- <Tooltip- popupContent={t('account.editWorkspaceInfo', { ns: 'common' })}- >- <div- className="cursor-pointer rounded-md p-1 hover:bg-black/5"- onClick={() => {- setEditWorkspaceModalVisible(true)- }}- >- <div- data-testid="edit-workspace-pencil"- className="i-ri-pencil-line h-4 w-4 text-text-tertiary"- />- </div>+ <Tooltip>+ <TooltipTrigger+ render={(+ <div+ className="cursor-pointer rounded-md p-1 hover:bg-black/5"+ onClick={() => {+ setEditWorkspaceModalVisible(true)+ }}+ >+ <div+ data-testid="edit-workspace-pencil"+ className="i-ri-pencil-line h-4 w-4 text-text-tertiary"+ />+ </div>+ )}+ />+ <TooltipContent>+ {t('account.editWorkspaceInfo', { ns: 'common' })}+ </TooltipContent></Tooltip></span>)}diff --git a/web/app/components/header/account-setting/members-page/operation/index.tsx b/web/app/components/header/account-setting/members-page/operation/index.tsxindex 306a67a093e..35c4676d5fc 100644--- a/web/app/components/header/account-setting/members-page/operation/index.tsx+++ b/web/app/components/header/account-setting/members-page/operation/index.tsx@@ -97,7 +97,7 @@ const Operation = ({offset={{ mainAxis: 4 }}><PortalToFollowElemTrigger asChild onClick={() => setOpen(prev => !prev)}>- <div className={cn('system-sm-regular group flex h-full w-full cursor-pointer items-center justify-between px-3 text-text-secondary hover:bg-state-base-hover', open && 'bg-state-base-hover')}>+ <div className={cn('group flex h-full w-full cursor-pointer items-center justify-between px-3 text-text-secondary system-sm-regular hover:bg-state-base-hover', open && 'bg-state-base-hover')}>{RoleMap[member.role] || RoleMap.normal}<ChevronDownIcon className={cn('h-4 w-4 shrink-0 group-hover:block', open ? 'block' : 'hidden')} /></div>@@ -114,8 +114,8 @@ const Operation = ({: <div className="mr-1 mt-[2px] h-4 w-4 text-text-accent" />}<div>- <div className="system-sm-semibold whitespace-nowrap text-text-secondary">{t(roleI18nKeyMap[role].label, { ns: 'common' })}</div>- <div className="system-xs-regular whitespace-nowrap text-text-tertiary">{t(roleI18nKeyMap[role].tip, { ns: 'common' })}</div>+ <div className="whitespace-nowrap text-text-secondary system-sm-semibold">{t(roleI18nKeyMap[role].label, { ns: 'common' })}</div>+ <div className="whitespace-nowrap text-text-tertiary system-xs-regular">{t(roleI18nKeyMap[role].tip, { ns: 'common' })}</div></div></div>))@@ -125,8 +125,8 @@ const Operation = ({<div className="flex cursor-pointer rounded-lg px-3 py-2 hover:bg-state-base-hover" onClick={handleDeleteMemberOrCancelInvitation}><div className="mr-1 mt-[2px] h-4 w-4 text-text-accent" /><div>- <div className="system-sm-semibold whitespace-nowrap text-text-secondary">{t('members.removeFromTeam', { ns: 'common' })}</div>- <div className="system-xs-regular whitespace-nowrap text-text-tertiary">{t('members.removeFromTeamTip', { ns: 'common' })}</div>+ <div className="whitespace-nowrap text-text-secondary system-sm-semibold">{t('members.removeFromTeam', { ns: 'common' })}</div>+ <div className="whitespace-nowrap text-text-tertiary system-xs-regular">{t('members.removeFromTeamTip', { ns: 'common' })}</div></div></div></div>diff --git a/web/app/components/header/account-setting/menu-dialog.dialog.spec.tsx b/web/app/components/header/account-setting/menu-dialog.dialog.spec.tsxnew file mode 100644index 00000000000..627b764eb28--- /dev/null+++ b/web/app/components/header/account-setting/menu-dialog.dialog.spec.tsx@@ -0,0 +1,42 @@+import type { ReactNode } from 'react'+import { render } from '@testing-library/react'+import MenuDialog from './menu-dialog'++type DialogProps = {+ children: ReactNode+ open?: boolean+ onOpenChange?: (open: boolean) => void+}++let latestOnOpenChange: DialogProps['onOpenChange']++vi.mock('@/app/components/base/ui/dialog', () => ({+ Dialog: ({ children, onOpenChange }: DialogProps) => {+ latestOnOpenChange = onOpenChange+ return <div data-testid="dialog">{children}</div>+ },+ DialogContent: ({ children, className }: { children: ReactNode, className?: string }) => (+ <div className={className}>{children}</div>+ ),+}))++describe('MenuDialog dialog lifecycle', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ latestOnOpenChange = undefined+ })++ it('should only call onClose when the dialog requests closing', () => {+ const onClose = vi.fn()+ render(+ <MenuDialog show={true} onClose={onClose}>+ <div>Content</div>+ </MenuDialog>,+ )++ latestOnOpenChange?.(true)+ latestOnOpenChange?.(false)++ expect(onClose).toHaveBeenCalledTimes(1)+ })+})diff --git a/web/app/components/header/account-setting/menu-dialog.tsx b/web/app/components/header/account-setting/menu-dialog.tsxindex 847634ed83e..354e57650c7 100644--- a/web/app/components/header/account-setting/menu-dialog.tsx+++ b/web/app/components/header/account-setting/menu-dialog.tsx@@ -1,7 +1,6 @@import type { ReactNode } from 'react'-import { Dialog, DialogPanel, Transition, TransitionChild } from '@headlessui/react'-import { noop } from 'es-toolkit/function'-import { Fragment, useCallback, useEffect } from 'react'+import { useCallback } from 'react'+import { Dialog, DialogContent } from '@/app/components/base/ui/dialog'import { cn } from '@/utils/classnames'type DialogProps = {@@ -19,42 +18,25 @@ const MenuDialog = ({}: DialogProps) => {const close = useCallback(() => onClose?.(), [onClose])- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key === 'Escape') {- event.preventDefault()- close()- }- }-- document.addEventListener('keydown', handleKeyDown)- return () => {- document.removeEventListener('keydown', handleKeyDown)- }- }, [close])-return (- <Transition appear show={show} as={Fragment}>- <Dialog as="div" className="relative z-[60]" onClose={noop}>- <div className="fixed inset-0">- <div className="flex min-h-full flex-col items-center justify-center">- <TransitionChild>- <DialogPanel className={cn(- 'relative h-full w-full grow overflow-hidden bg-background-sidenav-bg p-0 text-left align-middle backdrop-blur-md transition-all',- 'duration-300 ease-in data-[closed]:scale-95 data-[closed]:opacity-0',- 'data-[enter]:scale-100 data-[enter]:opacity-100',- 'data-[enter]:scale-95 data-[leave]:opacity-0',- className,- )}- >- <div className="absolute right-0 top-0 h-full w-1/2 bg-components-panel-bg" />- {children}- </DialogPanel>- </TransitionChild>- </div>- </div>- </Dialog>- </Transition>+ <Dialog+ open={show}+ onOpenChange={(open) => {+ if (!open)+ close()+ }}+ >+ <DialogContent+ overlayClassName="bg-transparent"+ className={cn(+ 'left-0 top-0 h-full max-h-none w-full max-w-none translate-x-0 translate-y-0 overflow-hidden rounded-none border-none bg-background-sidenav-bg p-0 shadow-none backdrop-blur-md',+ className,+ )}+ >+ <div className="absolute right-0 top-0 h-full w-1/2 bg-components-panel-bg" />+ {children}+ </DialogContent>+ </Dialog>)}diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts b/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.tsindex 0fe48ad3254..1d50ee43b03 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/hooks.spec.ts@@ -9,6 +9,7 @@ import type {} from '../declarations'import { act, renderHook, waitFor } from '@testing-library/react'import { useLocale } from '@/context/i18n'+import { consoleQuery } from '@/service/client'import { fetchDefaultModal, fetchModelList, fetchModelProviderCredentials } from '@/service/common'import {ConfigurationMethodEnum,@@ -23,6 +24,7 @@ import {useAnthropicBuyQuota,useCurrentProviderAndModel,useDefaultModel,+ useInvalidateDefaultModel,useLanguage,useMarketplaceAllPlugins,useModelList,@@ -36,7 +38,6 @@ import {useUpdateModelList,useUpdateModelProviders,} from '../hooks'-import { UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST } from '../provider-added-card'// Mock dependenciesvi.mock('@tanstack/react-query', () => ({@@ -78,14 +79,6 @@ vi.mock('@/context/modal-context', () => ({}),}))-vi.mock('@/context/event-emitter', () => ({- useEventEmitterContextContext: vi.fn(() => ({- eventEmitter: {- emit: vi.fn(),- },- })),-}))-vi.mock('@/app/components/plugins/marketplace/hooks', () => ({useMarketplacePlugins: vi.fn(() => ({plugins: [],@@ -99,12 +92,16 @@ vi.mock('@/app/components/plugins/marketplace/hooks', () => ({})),}))+vi.mock('../atoms', () => ({+ useExpandModelProviderList: vi.fn(() => vi.fn()),+}))+const { useQuery, useQueryClient } = await import('@tanstack/react-query')const { getPayUrl } = await import('@/service/common')const { useProviderContext } = await import('@/context/provider-context')const { useModalContextSelector } = await import('@/context/modal-context')-const { useEventEmitterContextContext } = await import('@/context/event-emitter')const { useMarketplacePlugins, useMarketplacePluginsByCollectionId } = await import('@/app/components/plugins/marketplace/hooks')+const { useExpandModelProviderList } = await import('../atoms')describe('hooks', () => {beforeEach(() => {@@ -913,6 +910,38 @@ describe('hooks', () => {})})+ describe('useInvalidateDefaultModel', () => {+ it('should invalidate default model queries', () => {+ const invalidateQueries = vi.fn()+ ; (useQueryClient as Mock).mockReturnValue({ invalidateQueries })++ const { result } = renderHook(() => useInvalidateDefaultModel())++ act(() => {+ result.current(ModelTypeEnum.textGeneration)+ })++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: ['default-model', ModelTypeEnum.textGeneration],+ })+ })++ it('should handle multiple model types', () => {+ const invalidateQueries = vi.fn()+ ; (useQueryClient as Mock).mockReturnValue({ invalidateQueries })++ const { result } = renderHook(() => useInvalidateDefaultModel())++ act(() => {+ result.current(ModelTypeEnum.textGeneration)+ result.current(ModelTypeEnum.textEmbedding)+ result.current(ModelTypeEnum.rerank)+ })++ expect(invalidateQueries).toHaveBeenCalledTimes(3)+ })+ })+describe('useAnthropicBuyQuota', () => {beforeEach(() => {Object.defineProperty(window, 'location', {@@ -1275,39 +1304,52 @@ describe('hooks', () => {it('should refresh providers and model lists', () => {const invalidateQueries = vi.fn()- const emit = vi.fn(); (useQueryClient as Mock).mockReturnValue({ invalidateQueries })- ; (useEventEmitterContextContext as Mock).mockReturnValue({- eventEmitter: { emit },- })const provider = createMockProvider()+ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: provider.provider,+ },+ },+ })const { result } = renderHook(() => useRefreshModel())act(() => {result.current.handleRefreshModel(provider)})+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'none',+ })expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['model-providers'] })expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['model-list', ModelTypeEnum.textGeneration] })expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['model-list', ModelTypeEnum.textEmbedding] })})- it('should emit event when refreshModelList is true and custom config is active', () => {+ it('should expand target provider list when refreshModelList is true and custom config is active', () => {const invalidateQueries = vi.fn()- const emit = vi.fn()+ const expandModelProviderList = vi.fn(); (useQueryClient as Mock).mockReturnValue({ invalidateQueries })- ; (useEventEmitterContextContext as Mock).mockReturnValue({- eventEmitter: { emit },- })+ ; (useExpandModelProviderList as Mock).mockReturnValue(expandModelProviderList)const provider = createMockProvider()const customFields: CustomConfigurationModelFixedFields = {__model_name: 'gpt-4',__model_type: ModelTypeEnum.textGeneration,}+ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: provider.provider,+ },+ },+ })const { result } = renderHook(() => useRefreshModel())@@ -1315,23 +1357,30 @@ describe('hooks', () => {result.current.handleRefreshModel(provider, customFields, true)})- expect(emit).toHaveBeenCalledWith({- type: UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST,- payload: 'openai',+ expect(expandModelProviderList).toHaveBeenCalledWith('openai')+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'active',})expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ['model-list', ModelTypeEnum.textGeneration] })})- it('should not emit event when custom config is not active', () => {+ it('should not expand provider list when custom config is not active', () => {const invalidateQueries = vi.fn()- const emit = vi.fn()+ const expandModelProviderList = vi.fn(); (useQueryClient as Mock).mockReturnValue({ invalidateQueries })- ; (useEventEmitterContextContext as Mock).mockReturnValue({- eventEmitter: { emit },- })+ ; (useExpandModelProviderList as Mock).mockReturnValue(expandModelProviderList)const provider = { ...createMockProvider(), custom_configuration: { status: CustomConfigurationStatusEnum.noConfigure } }+ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: provider.provider,+ },+ },+ })const { result } = renderHook(() => useRefreshModel())@@ -1339,17 +1388,43 @@ describe('hooks', () => {result.current.handleRefreshModel(provider, undefined, true)})- expect(emit).not.toHaveBeenCalled()+ expect(expandModelProviderList).not.toHaveBeenCalled()+ expect(invalidateQueries).not.toHaveBeenCalledWith({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'active',+ })})- it('should emit event and invalidate all supported model types when __model_type is undefined', () => {+ it('should refetch active model provider list when custom refresh callback is absent', () => {const invalidateQueries = vi.fn()- const emit = vi.fn()+ ; (useQueryClient as Mock).mockReturnValue({ invalidateQueries })- ; (useQueryClient as Mock).mockReturnValue({ invalidateQueries })- ; (useEventEmitterContextContext as Mock).mockReturnValue({- eventEmitter: { emit },+ const provider = createMockProvider()+ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: provider.provider,+ },+ },+ })+ const { result } = renderHook(() => useRefreshModel())++ act(() => {+ result.current.handleRefreshModel(provider, undefined, true)+ })++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'active',})+ })++ it('should invalidate all supported model types when __model_type is undefined', () => {+ const invalidateQueries = vi.fn()++ ; (useQueryClient as Mock).mockReturnValue({ invalidateQueries })const provider = createMockProvider()const customFields = { __model_name: 'my-model', __model_type: undefined } as unknown as CustomConfigurationModelFixedFields@@ -1360,11 +1435,7 @@ describe('hooks', () => {result.current.handleRefreshModel(provider, customFields, true)})- expect(emit).toHaveBeenCalledWith({- type: UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST,- payload: 'openai',- })- // When __model_type is undefined, all supported model types are invalidated+ // When __model_type is undefined, all supported model types are invalidated.const modelListCalls = invalidateQueries.mock.calls.filter(call => call[0]?.queryKey?.[0] === 'model-list',)@@ -1375,9 +1446,6 @@ describe('hooks', () => {const invalidateQueries = vi.fn(); (useQueryClient as Mock).mockReturnValue({ invalidateQueries })- ; (useEventEmitterContextContext as Mock).mockReturnValue({- eventEmitter: { emit: vi.fn() },- })const provider = {...createMockProvider(),diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsxindex 832bd77ec22..8d6c59bbf29 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/index.spec.tsx@@ -7,16 +7,7 @@ import {} from '../declarations'import ModelProviderPage from '../index'-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- mutateCurrentWorkspace: vi.fn(),- isValidatingCurrentWorkspace: false,- }),-}))--const mockGlobalState = {- systemFeatures: { enable_marketplace: true },-}+let mockEnableMarketplace = trueconst mockQuotaConfig = {quota_type: CurrentSystemQuotaTypeEnum.free,@@ -28,7 +19,11 @@ const mockQuotaConfig = {}vi.mock('@/context/global-public-context', () => ({- useGlobalPublicStore: (selector: (s: { systemFeatures: { enable_marketplace: boolean } }) => unknown) => selector(mockGlobalState),+ useSystemFeaturesQuery: () => ({+ data: {+ enable_marketplace: mockEnableMarketplace,+ },+ }),}))const mockProviders = [@@ -60,21 +55,16 @@ vi.mock('@/context/provider-context', () => ({}),}))-type MockDefaultModelData = {- model: string- provider?: { provider: string }-} | null--const mockDefaultModelState: {- data: MockDefaultModelData- isLoading: boolean-} = {- data: null,- isLoading: false,+const mockDefaultModels: Record<string, { data: unknown, isLoading: boolean }> = {+ 'llm': { data: null, isLoading: false },+ 'text-embedding': { data: null, isLoading: false },+ 'rerank': { data: null, isLoading: false },+ 'speech2text': { data: null, isLoading: false },+ 'tts': { data: null, isLoading: false },}vi.mock('../hooks', () => ({- useDefaultModel: () => mockDefaultModelState,+ useDefaultModel: (type: string) => mockDefaultModels[type] ?? { data: null, isLoading: false },}))vi.mock('../install-from-marketplace', () => ({@@ -93,13 +83,31 @@ vi.mock('../system-model-selector', () => ({default: () => <div data-testid="system-model-selector" />,}))+vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQuery: () => ({ data: undefined }),+ }+})++vi.mock('@/service/client', () => ({+ consoleQuery: {+ plugins: {+ checkInstalled: { queryOptions: () => ({}) },+ latestVersions: { queryOptions: () => ({}) },+ },+ },+}))+describe('ModelProviderPage', () => {beforeEach(() => {vi.useFakeTimers()vi.clearAllMocks()- mockGlobalState.systemFeatures.enable_marketplace = true- mockDefaultModelState.data = null- mockDefaultModelState.isLoading = false+ mockEnableMarketplace = true+ Object.keys(mockDefaultModels).forEach((key) => {+ mockDefaultModels[key] = { data: null, isLoading: false }+ })mockProviders.splice(0, mockProviders.length, {provider: 'openai',label: { en_US: 'OpenAI' },@@ -157,13 +165,76 @@ describe('ModelProviderPage', () => {})it('should hide marketplace section when marketplace feature is disabled', () => {- mockGlobalState.systemFeatures.enable_marketplace = false+ mockEnableMarketplace = falserender(<ModelProviderPage searchText="" />)expect(screen.queryByTestId('install-from-marketplace')).not.toBeInTheDocument()})+ describe('system model config status', () => {+ it('should not show top warning when no configured providers exist (empty state card handles it)', () => {+ mockProviders.splice(0, mockProviders.length, {+ provider: 'anthropic',+ label: { en_US: 'Anthropic' },+ custom_configuration: { status: CustomConfigurationStatusEnum.noConfigure },+ system_configuration: {+ enabled: false,+ current_quota_type: CurrentSystemQuotaTypeEnum.free,+ quota_configurations: [mockQuotaConfig],+ },+ })++ render(<ModelProviderPage searchText="" />)+ expect(screen.queryByText('common.modelProvider.noneConfigured')).not.toBeInTheDocument()+ expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()+ expect(screen.getByText('common.modelProvider.emptyProviderTitle')).toBeInTheDocument()+ })++ it('should show none-configured warning when providers exist but no default models set', () => {+ render(<ModelProviderPage searchText="" />)+ expect(screen.getByText('common.modelProvider.noneConfigured')).toBeInTheDocument()+ })++ it('should show partially-configured warning when some default models are set', () => {+ mockDefaultModels.llm = {+ data: { model: 'gpt-4', model_type: 'llm', provider: { provider: 'openai', icon_small: { en_US: '' } } },+ isLoading: false,+ }++ render(<ModelProviderPage searchText="" />)+ expect(screen.getByText('common.modelProvider.notConfigured')).toBeInTheDocument()+ })++ it('should not show warning when all default models are configured', () => {+ const makeModel = (model: string, type: string) => ({+ data: { model, model_type: type, provider: { provider: 'openai', icon_small: { en_US: '' } } },+ isLoading: false,+ })+ mockDefaultModels.llm = makeModel('gpt-4', 'llm')+ mockDefaultModels['text-embedding'] = makeModel('text-embedding-3', 'text-embedding')+ mockDefaultModels.rerank = makeModel('rerank-v3', 'rerank')+ mockDefaultModels.speech2text = makeModel('whisper-1', 'speech2text')+ mockDefaultModels.tts = makeModel('tts-1', 'tts')++ render(<ModelProviderPage searchText="" />)+ expect(screen.queryByText('common.modelProvider.noProviderInstalled')).not.toBeInTheDocument()+ expect(screen.queryByText('common.modelProvider.noneConfigured')).not.toBeInTheDocument()+ expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()+ })++ it('should not show warning while loading', () => {+ Object.keys(mockDefaultModels).forEach((key) => {+ mockDefaultModels[key] = { data: null, isLoading: true }+ })++ render(<ModelProviderPage searchText="" />)+ expect(screen.queryByText('common.modelProvider.noProviderInstalled')).not.toBeInTheDocument()+ expect(screen.queryByText('common.modelProvider.noneConfigured')).not.toBeInTheDocument()+ expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()+ })+ })+it('should prioritize fixed providers in visible order', () => {mockProviders.splice(0, mockProviders.length, {provider: 'zeta-provider',@@ -204,129 +275,4 @@ describe('ModelProviderPage', () => {])expect(screen.queryByText('common.modelProvider.toBeConfigured')).not.toBeInTheDocument()})-- it('should show not configured alert when all default models are absent', () => {- mockDefaultModelState.data = null- mockDefaultModelState.isLoading = false-- render(<ModelProviderPage searchText="" />)-- expect(screen.getByText('common.modelProvider.notConfigured')).toBeInTheDocument()- })-- it('should not show not configured alert when default model is loading', () => {- mockDefaultModelState.data = null- mockDefaultModelState.isLoading = true-- render(<ModelProviderPage searchText="" />)-- expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()- })-- it('should filter providers by label text', () => {- render(<ModelProviderPage searchText="OpenAI" />)- act(() => {- vi.advanceTimersByTime(600)- })- expect(screen.getByText('openai')).toBeInTheDocument()- expect(screen.queryByText('anthropic')).not.toBeInTheDocument()- })-- it('should classify system-enabled providers with matching quota as configured', () => {- mockProviders.splice(0, mockProviders.length, {- provider: 'sys-provider',- label: { en_US: 'System Provider' },- custom_configuration: { status: CustomConfigurationStatusEnum.noConfigure },- system_configuration: {- enabled: true,- current_quota_type: CurrentSystemQuotaTypeEnum.free,- quota_configurations: [mockQuotaConfig],- },- })-- render(<ModelProviderPage searchText="" />)-- expect(screen.getByText('sys-provider')).toBeInTheDocument()- expect(screen.queryByText('common.modelProvider.toBeConfigured')).not.toBeInTheDocument()- })-- it('should classify system-enabled provider with no matching quota as not configured', () => {- mockProviders.splice(0, mockProviders.length, {- provider: 'sys-no-quota',- label: { en_US: 'System No Quota' },- custom_configuration: { status: CustomConfigurationStatusEnum.noConfigure },- system_configuration: {- enabled: true,- current_quota_type: CurrentSystemQuotaTypeEnum.free,- quota_configurations: [],- },- })-- render(<ModelProviderPage searchText="" />)-- expect(screen.getByText('sys-no-quota')).toBeInTheDocument()- expect(screen.getByText('common.modelProvider.toBeConfigured')).toBeInTheDocument()- })-- it('should preserve order of two non-fixed providers (sort returns 0)', () => {- mockProviders.splice(0, mockProviders.length, {- provider: 'alpha-provider',- label: { en_US: 'Alpha Provider' },- custom_configuration: { status: CustomConfigurationStatusEnum.active },- system_configuration: {- enabled: false,- current_quota_type: CurrentSystemQuotaTypeEnum.free,- quota_configurations: [mockQuotaConfig],- },- }, {- provider: 'beta-provider',- label: { en_US: 'Beta Provider' },- custom_configuration: { status: CustomConfigurationStatusEnum.active },- system_configuration: {- enabled: false,- current_quota_type: CurrentSystemQuotaTypeEnum.free,- quota_configurations: [mockQuotaConfig],- },- })-- render(<ModelProviderPage searchText="" />)-- const renderedProviders = screen.getAllByTestId('provider-card').map(item => item.textContent)- expect(renderedProviders).toEqual(['alpha-provider', 'beta-provider'])- })-- it('should not show not configured alert when shared default model mock has data', () => {- mockDefaultModelState.data = { model: 'embed-model' }-- render(<ModelProviderPage searchText="" />)-- expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()- })-- it('should not show not configured alert when rerankDefaultModel has data', () => {- mockDefaultModelState.data = { model: 'rerank-model', provider: { provider: 'cohere' } }- mockDefaultModelState.isLoading = false-- render(<ModelProviderPage searchText="" />)-- expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()- })-- it('should not show not configured alert when ttsDefaultModel has data', () => {- mockDefaultModelState.data = { model: 'tts-model', provider: { provider: 'openai' } }- mockDefaultModelState.isLoading = false-- render(<ModelProviderPage searchText="" />)-- expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()- })-- it('should not show not configured alert when speech2textDefaultModel has data', () => {- mockDefaultModelState.data = { model: 'whisper', provider: { provider: 'openai' } }- mockDefaultModelState.isLoading = false-- render(<ModelProviderPage searchText="" />)-- expect(screen.queryByText('common.modelProvider.notConfigured')).not.toBeInTheDocument()- })})diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx b/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsxindex 8a732f4e913..452068e61c7 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/install-from-marketplace.spec.tsx@@ -61,8 +61,15 @@ describe('InstallFromMarketplace', () => {it('should collapse when clicked', () => {render(<InstallFromMarketplace providers={mockProviders} searchText="" />)- fireEvent.click(screen.getByText('common.modelProvider.installProvider'))+ const toggle = screen.getByRole('button', { name: /common\.modelProvider\.installProvider/ })++ fireEvent.click(toggle)expect(screen.queryByTestId('plugin-list')).not.toBeInTheDocument()+ expect(toggle).toHaveAttribute('aria-expanded', 'false')++ fireEvent.click(toggle)+ expect(toggle).toHaveAttribute('aria-expanded', 'true')+ expect(screen.getByTestId('plugin-list')).toBeInTheDocument()})it('should show loading state', () => {diff --git a/web/app/components/header/account-setting/model-provider-page/__tests__/utils.spec.ts b/web/app/components/header/account-setting/model-provider-page/__tests__/utils.spec.tsindex 63e9d4b21e9..d49343e0c61 100644--- a/web/app/components/header/account-setting/model-provider-page/__tests__/utils.spec.ts+++ b/web/app/components/header/account-setting/model-provider-page/__tests__/utils.spec.ts@@ -16,6 +16,7 @@ import {genModelNameFormSchema,genModelTypeFormSchema,modelTypeFormat,+ providerToPluginId,removeCredentials,saveCredentials,savePredefinedLoadBalancingConfig,@@ -47,6 +48,16 @@ describe('utils', () => {})})+ describe('providerToPluginId', () => {+ it('should return the plugin id prefix when the provider key contains a provider segment', () => {+ expect(providerToPluginId('langgenius/openai/openai')).toBe('langgenius/openai')+ })++ it('should return an empty string when the provider key has no plugin prefix', () => {+ expect(providerToPluginId('openai')).toBe('')+ })+ })+describe('modelTypeFormat', () => {it('should format text embedding type', () => {expect(modelTypeFormat(ModelTypeEnum.textEmbedding)).toBe('TEXT EMBEDDING')diff --git a/web/app/components/header/account-setting/model-provider-page/atoms.spec.tsx b/web/app/components/header/account-setting/model-provider-page/atoms.spec.tsxnew file mode 100644index 00000000000..1ef33d10932--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/atoms.spec.tsx@@ -0,0 +1,399 @@+import type { ReactNode } from 'react'+import { act, renderHook } from '@testing-library/react'+import { Provider } from 'jotai'+import { beforeEach, describe, expect, it } from 'vitest'+import {+ useExpandModelProviderList,+ useModelProviderListExpanded,+ useResetModelProviderListExpanded,+ useSetModelProviderListExpanded,+} from './atoms'++const createWrapper = () => {+ return ({ children }: { children: ReactNode }) => (+ <Provider>{children}</Provider>+ )+}++describe('atoms', () => {+ let wrapper: ReturnType<typeof createWrapper>++ beforeEach(() => {+ wrapper = createWrapper()+ })++ // Read hook: returns whether a specific provider is expanded+ describe('useModelProviderListExpanded', () => {+ it('should return false when provider has not been expanded', () => {+ const { result } = renderHook(+ () => useModelProviderListExpanded('openai'),+ { wrapper },+ )++ expect(result.current).toBe(false)+ })++ it('should return false for any unknown provider name', () => {+ const { result } = renderHook(+ () => useModelProviderListExpanded('nonexistent-provider'),+ { wrapper },+ )++ expect(result.current).toBe(false)+ })++ it('should return true when provider has been expanded via setter', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ setExpanded: useSetModelProviderListExpanded('openai'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setExpanded(true)+ })++ expect(result.current.expanded).toBe(true)+ })+ })++ // Setter hook: toggles expanded state for a specific provider+ describe('useSetModelProviderListExpanded', () => {+ it('should expand a provider when called with true', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('anthropic'),+ setExpanded: useSetModelProviderListExpanded('anthropic'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setExpanded(true)+ })++ expect(result.current.expanded).toBe(true)+ })++ it('should collapse a provider when called with false', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('anthropic'),+ setExpanded: useSetModelProviderListExpanded('anthropic'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setExpanded(true)+ })+ act(() => {+ result.current.setExpanded(false)+ })++ expect(result.current.expanded).toBe(false)+ })++ it('should not affect other providers when setting one', () => {+ const { result } = renderHook(+ () => ({+ openaiExpanded: useModelProviderListExpanded('openai'),+ anthropicExpanded: useModelProviderListExpanded('anthropic'),+ setOpenai: useSetModelProviderListExpanded('openai'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setOpenai(true)+ })++ expect(result.current.openaiExpanded).toBe(true)+ expect(result.current.anthropicExpanded).toBe(false)+ })+ })++ // Expand hook: expands any provider by name+ describe('useExpandModelProviderList', () => {+ it('should expand the specified provider', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('google'),+ expand: useExpandModelProviderList(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('google')+ })++ expect(result.current.expanded).toBe(true)+ })++ it('should expand multiple providers independently', () => {+ const { result } = renderHook(+ () => ({+ openaiExpanded: useModelProviderListExpanded('openai'),+ anthropicExpanded: useModelProviderListExpanded('anthropic'),+ expand: useExpandModelProviderList(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('openai')+ })+ act(() => {+ result.current.expand('anthropic')+ })++ expect(result.current.openaiExpanded).toBe(true)+ expect(result.current.anthropicExpanded).toBe(true)+ })++ it('should not collapse already expanded providers when expanding another', () => {+ const { result } = renderHook(+ () => ({+ openaiExpanded: useModelProviderListExpanded('openai'),+ anthropicExpanded: useModelProviderListExpanded('anthropic'),+ expand: useExpandModelProviderList(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('openai')+ })+ act(() => {+ result.current.expand('anthropic')+ })++ expect(result.current.openaiExpanded).toBe(true)+ })+ })++ // Reset hook: clears all expanded state back to empty+ describe('useResetModelProviderListExpanded', () => {+ it('should reset all expanded providers to false', () => {+ const { result } = renderHook(+ () => ({+ openaiExpanded: useModelProviderListExpanded('openai'),+ anthropicExpanded: useModelProviderListExpanded('anthropic'),+ expand: useExpandModelProviderList(),+ reset: useResetModelProviderListExpanded(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('openai')+ })+ act(() => {+ result.current.expand('anthropic')+ })+ act(() => {+ result.current.reset()+ })++ expect(result.current.openaiExpanded).toBe(false)+ expect(result.current.anthropicExpanded).toBe(false)+ })++ it('should be safe to call when no providers are expanded', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ reset: useResetModelProviderListExpanded(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.reset()+ })++ expect(result.current.expanded).toBe(false)+ })++ it('should allow re-expanding providers after reset', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ expand: useExpandModelProviderList(),+ reset: useResetModelProviderListExpanded(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('openai')+ })+ act(() => {+ result.current.reset()+ })+ act(() => {+ result.current.expand('openai')+ })++ expect(result.current.expanded).toBe(true)+ })+ })++ // Cross-hook interaction: verify hooks cooperate through the shared atom+ describe('Cross-hook interaction', () => {+ it('should reflect state set by useSetModelProviderListExpanded in useModelProviderListExpanded', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ setExpanded: useSetModelProviderListExpanded('openai'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setExpanded(true)+ })++ expect(result.current.expanded).toBe(true)+ })++ it('should reflect state set by useExpandModelProviderList in useModelProviderListExpanded', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('anthropic'),+ expand: useExpandModelProviderList(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('anthropic')+ })++ expect(result.current.expanded).toBe(true)+ })++ it('should allow useSetModelProviderListExpanded to collapse a provider expanded by useExpandModelProviderList', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ expand: useExpandModelProviderList(),+ setExpanded: useSetModelProviderListExpanded('openai'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.expand('openai')+ })+ expect(result.current.expanded).toBe(true)++ act(() => {+ result.current.setExpanded(false)+ })+ expect(result.current.expanded).toBe(false)+ })++ it('should reset state set by useSetModelProviderListExpanded via useResetModelProviderListExpanded', () => {+ const { result } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ setExpanded: useSetModelProviderListExpanded('openai'),+ reset: useResetModelProviderListExpanded(),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setExpanded(true)+ })+ act(() => {+ result.current.reset()+ })++ expect(result.current.expanded).toBe(false)+ })+ })++ // selectAtom granularity: changing one provider should not affect unrelated reads+ describe('selectAtom granularity', () => {+ it('should not cause unrelated provider reads to change when one provider is toggled', () => {+ const { result } = renderHook(+ () => ({+ openai: useModelProviderListExpanded('openai'),+ anthropic: useModelProviderListExpanded('anthropic'),+ google: useModelProviderListExpanded('google'),+ setOpenai: useSetModelProviderListExpanded('openai'),+ }),+ { wrapper },+ )++ const anthropicBefore = result.current.anthropic+ const googleBefore = result.current.google++ act(() => {+ result.current.setOpenai(true)+ })++ expect(result.current.openai).toBe(true)+ expect(result.current.anthropic).toBe(anthropicBefore)+ expect(result.current.google).toBe(googleBefore)+ })++ it('should keep individual provider states independent across multiple expansions and collapses', () => {+ const { result } = renderHook(+ () => ({+ openai: useModelProviderListExpanded('openai'),+ anthropic: useModelProviderListExpanded('anthropic'),+ setOpenai: useSetModelProviderListExpanded('openai'),+ setAnthropic: useSetModelProviderListExpanded('anthropic'),+ }),+ { wrapper },+ )++ act(() => {+ result.current.setOpenai(true)+ })+ act(() => {+ result.current.setAnthropic(true)+ })+ act(() => {+ result.current.setOpenai(false)+ })++ expect(result.current.openai).toBe(false)+ expect(result.current.anthropic).toBe(true)+ })+ })++ // Isolation: separate Provider instances have independent state+ describe('Provider isolation', () => {+ it('should have independent state across different Provider instances', () => {+ const wrapper1 = createWrapper()+ const wrapper2 = createWrapper()++ const { result: result1 } = renderHook(+ () => ({+ expanded: useModelProviderListExpanded('openai'),+ setExpanded: useSetModelProviderListExpanded('openai'),+ }),+ { wrapper: wrapper1 },+ )++ const { result: result2 } = renderHook(+ () => useModelProviderListExpanded('openai'),+ { wrapper: wrapper2 },+ )++ act(() => {+ result1.current.setExpanded(true)+ })++ expect(result1.current.expanded).toBe(true)+ expect(result2.current).toBe(false)+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/atoms.ts b/web/app/components/header/account-setting/model-provider-page/atoms.tsnew file mode 100644index 00000000000..66737c5eb28--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/atoms.ts@@ -0,0 +1,35 @@+import { atom, useAtomValue, useSetAtom } from 'jotai'+import { selectAtom } from 'jotai/utils'+import { useCallback, useMemo } from 'react'++const expandedAtom = atom<Record<string, boolean>>({})++export function useModelProviderListExpanded(providerName: string) {+ return useAtomValue(+ useMemo(+ () => selectAtom(expandedAtom, s => !!s[providerName]),+ [providerName],+ ),+ )+}++export function useSetModelProviderListExpanded(providerName: string) {+ const set = useSetAtom(expandedAtom)+ return useCallback(+ (expanded: boolean) => set(prev => ({ ...prev, [providerName]: expanded })),+ [providerName, set],+ )+}++export function useExpandModelProviderList() {+ const set = useSetAtom(expandedAtom)+ return useCallback(+ (providerName: string) => set(prev => ({ ...prev, [providerName]: true })),+ [set],+ )+}++export function useResetModelProviderListExpanded() {+ const set = useSetAtom(expandedAtom)+ return useCallback(() => set({}), [set])+}diff --git a/web/app/components/header/account-setting/model-provider-page/derive-model-status.spec.ts b/web/app/components/header/account-setting/model-provider-page/derive-model-status.spec.tsnew file mode 100644index 00000000000..1b248e98f2e--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/derive-model-status.spec.ts@@ -0,0 +1,160 @@+import type { Model, ModelItem, ModelProvider } from './declarations'+import type { CredentialPanelState } from './provider-added-card/use-credential-panel-state'+import {+ ConfigurationMethodEnum,+ ModelStatusEnum,+ ModelTypeEnum,+} from './declarations'+import { deriveModelStatus } from './derive-model-status'++const createCredentialState = (overrides: Partial<CredentialPanelState> = {}): CredentialPanelState => ({+ variant: 'credits-active',+ priority: 'credits',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: false,+ isCreditsExhausted: false,+ credentialName: undefined,+ credits: 100,+ ...overrides,+})++const createModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({+ model: 'text-embedding-3-large',+ label: { en_US: 'Text Embedding 3 Large', zh_Hans: 'Text Embedding 3 Large' },+ model_type: ModelTypeEnum.textEmbedding,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status: ModelStatusEnum.active,+ model_properties: {},+ load_balancing_enabled: false,+ ...overrides,+})++const createModelProvider = (): ModelProvider =>+ ({ provider: 'openai' } as ModelProvider)++const createModel = (overrides: Partial<Model> = {}): Model => ({+ provider: 'openai',+ icon_small: { en_US: '', zh_Hans: '' },+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [createModelItem()],+ status: ModelStatusEnum.active,+ ...overrides,+})++describe('deriveModelStatus', () => {+ it('should return empty when model id or provider name is missing', () => {+ expect(+ deriveModelStatus('', 'openai', createModelProvider(), createModelItem(), createCredentialState()),+ ).toBe('empty')+ expect(+ deriveModelStatus('text-embedding-3-large', '', createModelProvider(), createModelItem(), createCredentialState()),+ ).toBe('empty')+ })++ it('should return incompatible when provider plugin is missing', () => {+ expect(+ deriveModelStatus('text-embedding-3-large', 'openai', undefined, createModelItem(), createCredentialState()),+ ).toBe('incompatible')+ })++ it('should return incompatible when model is missing from the provider list', () => {+ expect(+ deriveModelStatus('text-embedding-3-large', 'openai', createModel(), undefined, createCredentialState()),+ ).toBe('incompatible')+ })++ it('should return credits-exhausted when model is missing and AI credits are exhausted without api key', () => {+ expect(+ deriveModelStatus(+ 'text-embedding-3-large',+ 'openai',+ createModelProvider(),+ undefined,+ createCredentialState({+ priority: 'apiKey',+ hasCredentials: false,+ isCreditsExhausted: true,+ }),+ ),+ ).toBe('credits-exhausted')+ })++ it('should return configure-required when the model status is no-configure', () => {+ expect(+ deriveModelStatus('text-embedding-3-large', 'openai', createModelProvider(), createModelItem({ status: ModelStatusEnum.noConfigure }), createCredentialState()),+ ).toBe('configure-required')+ })++ it('should return disabled when the model status is disabled', () => {+ expect(+ deriveModelStatus('text-embedding-3-large', 'openai', createModelProvider(), createModelItem({ status: ModelStatusEnum.disabled }), createCredentialState()),+ ).toBe('disabled')+ })++ it('should return credits-exhausted when credential state takes priority', () => {+ expect(+ deriveModelStatus(+ 'text-embedding-3-large',+ 'openai',+ createModelProvider(),+ createModelItem(),+ createCredentialState({ isCreditsExhausted: true }),+ ),+ ).toBe('credits-exhausted')+ })++ it('should return api-key-unavailable when credential state is api-unavailable', () => {+ expect(+ deriveModelStatus(+ 'text-embedding-3-large',+ 'openai',+ createModelProvider(),+ createModelItem(),+ createCredentialState({ variant: 'api-unavailable', priority: 'apiKey' }),+ ),+ ).toBe('api-key-unavailable')+ })++ it('should return credits-exhausted when model status is quota exceeded', () => {+ expect(+ deriveModelStatus(+ 'text-embedding-3-large',+ 'openai',+ createModelProvider(),+ createModelItem({ status: ModelStatusEnum.quotaExceeded }),+ createCredentialState({ priority: 'apiKey' }),+ ),+ ).toBe('credits-exhausted')+ })++ it('should return api-key-unavailable when model status is credential removed', () => {+ expect(+ deriveModelStatus(+ 'text-embedding-3-large',+ 'openai',+ createModelProvider(),+ createModelItem({ status: ModelStatusEnum.credentialRemoved }),+ createCredentialState({ priority: 'apiKey' }),+ ),+ ).toBe('api-key-unavailable')+ })++ it('should return incompatible when model status is no-permission', () => {+ expect(+ deriveModelStatus(+ 'text-embedding-3-large',+ 'openai',+ createModelProvider(),+ createModelItem({ status: ModelStatusEnum.noPermission }),+ createCredentialState({ priority: 'apiKey' }),+ ),+ ).toBe('incompatible')+ })++ it('should return active when model and credential state are available', () => {+ expect(+ deriveModelStatus('text-embedding-3-large', 'openai', createModelProvider(), createModelItem(), createCredentialState()),+ ).toBe('active')+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/derive-model-status.ts b/web/app/components/header/account-setting/model-provider-page/derive-model-status.tsnew file mode 100644index 00000000000..f9eb93536e1--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/derive-model-status.ts@@ -0,0 +1,72 @@+import type { Model, ModelItem, ModelProvider } from './declarations'+import type { CredentialPanelState } from './provider-added-card/use-credential-panel-state'+import { ModelStatusEnum } from './declarations'++export type DerivedModelStatus+ = | 'empty'+ | 'active'+ | 'configure-required'+ | 'credits-exhausted'+ | 'api-key-unavailable'+ | 'disabled'+ | 'incompatible'++export const DERIVED_MODEL_STATUS_BADGE_I18N = {+ 'configure-required': 'modelProvider.selector.configureRequired',+ 'credits-exhausted': 'modelProvider.selector.creditsExhausted',+ 'api-key-unavailable': 'modelProvider.selector.apiKeyUnavailable',+ 'disabled': 'modelProvider.selector.disabled',+ 'incompatible': 'modelProvider.selector.incompatible',+} as const satisfies Partial<Record<DerivedModelStatus, string>>++export const DERIVED_MODEL_STATUS_TOOLTIP_I18N = {+ 'credits-exhausted': 'modelProvider.selector.creditsExhaustedTip',+ 'api-key-unavailable': 'modelProvider.selector.apiKeyUnavailableTip',+ 'incompatible': 'modelProvider.selector.incompatibleTip',+} as const satisfies Partial<Record<DerivedModelStatus, string>>++export const deriveModelStatus = (+ modelId: string | undefined,+ providerName: string | undefined,+ currentModelProvider: ModelProvider | Model | undefined,+ currentModel: ModelItem | undefined,+ credentialState: CredentialPanelState,+): DerivedModelStatus => {+ if (!modelId || !providerName)+ return 'empty'++ if (!currentModelProvider)+ return 'incompatible'++ const isCreditsExhaustedWithoutApiKey = credentialState.supportsCredits+ && credentialState.isCreditsExhausted+ && !credentialState.hasCredentials+ const isCreditsPriorityExhausted = credentialState.priority === 'credits'+ && credentialState.supportsCredits+ && credentialState.isCreditsExhausted++ if (isCreditsPriorityExhausted || isCreditsExhaustedWithoutApiKey)+ return 'credits-exhausted'++ if (!currentModel)+ return 'incompatible'++ if (credentialState.variant === 'api-unavailable')+ return 'api-key-unavailable'++ switch (currentModel.status) {+ case ModelStatusEnum.active:+ return 'active'+ case ModelStatusEnum.noConfigure:+ return 'configure-required'+ case ModelStatusEnum.quotaExceeded:+ return 'credits-exhausted'+ case ModelStatusEnum.credentialRemoved:+ return 'api-key-unavailable'+ case ModelStatusEnum.disabled:+ return 'disabled'+ case ModelStatusEnum.noPermission:+ default:+ return 'incompatible'+ }+}diff --git a/web/app/components/header/account-setting/model-provider-page/hooks.ts b/web/app/components/header/account-setting/model-provider-page/hooks.tsindex 8db964cc276..791a42deb5b 100644--- a/web/app/components/header/account-setting/model-provider-page/hooks.ts+++ b/web/app/components/header/account-setting/model-provider-page/hooks.ts@@ -21,10 +21,10 @@ import {useMarketplacePluginsByCollectionId,} from '@/app/components/plugins/marketplace/hooks'import { PluginCategoryEnum } from '@/app/components/plugins/types'-import { useEventEmitterContextContext } from '@/context/event-emitter'import { useLocale } from '@/context/i18n'import { useModalContextSelector } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'+import { consoleQuery } from '@/service/client'import {fetchDefaultModal,fetchModelList,@@ -32,12 +32,12 @@ import {getPayUrl,} from '@/service/common'import { commonQueryKeys } from '@/service/use-common'+import { useExpandModelProviderList } from './atoms'import {ConfigurationMethodEnum,CustomConfigurationStatusEnum,ModelStatusEnum,} from './declarations'-import { UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST } from './provider-added-card'type UseDefaultModelAndModelList = (defaultModel: DefaultModelResponse | undefined,@@ -57,15 +57,21 @@ export const useSystemDefaultModelAndModelList: UseDefaultModelAndModelList = (return currentDefaultModel}, [defaultModel, modelList])+ const currentDefaultModelKey = currentDefaultModel+ ? `${currentDefaultModel.provider}:${currentDefaultModel.model}`+ : ''const [defaultModelState, setDefaultModelState] = useState<DefaultModel | undefined>(currentDefaultModel)+ const [defaultModelSourceKey, setDefaultModelSourceKey] = useState(currentDefaultModelKey)+ const selectedDefaultModel = defaultModelSourceKey === currentDefaultModelKey+ ? defaultModelState+ : currentDefaultModel+const handleDefaultModelChange = useCallback((model: DefaultModel) => {+ setDefaultModelSourceKey(currentDefaultModelKey)setDefaultModelState(model)- }, [])- useEffect(() => {- setDefaultModelState(currentDefaultModel)- }, [currentDefaultModel])+ }, [currentDefaultModelKey])- return [defaultModelState, handleDefaultModelChange]+ return [selectedDefaultModel, handleDefaultModelChange]}export const useLanguage = () => {@@ -116,7 +122,7 @@ export const useProviderCredentialsAndLoadBalancing = (predefinedFormSchemasValue?.credentials,])- const mutate = useMemo(() => () => {+ const mutate = useCallback(() => {if (predefinedEnabled)queryClient.invalidateQueries({ queryKey: ['model-providers', 'credentials', provider, credentialId] })if (customEnabled)@@ -222,6 +228,14 @@ export const useUpdateModelList = () => {return updateModelList}+export const useInvalidateDefaultModel = () => {+ const queryClient = useQueryClient()++ return useCallback((type: ModelTypeEnum) => {+ queryClient.invalidateQueries({ queryKey: commonQueryKeys.defaultModel(type) })+ }, [queryClient])+}+export const useAnthropicBuyQuota = () => {const [loading, setLoading] = useState(false)@@ -314,7 +328,8 @@ export const useMarketplaceAllPlugins = (providers: ModelProvider[], searchText:}export const useRefreshModel = () => {- const { eventEmitter } = useEventEmitterContextContext()+ const expandModelProviderList = useExpandModelProviderList()+ const queryClient = useQueryClient()const updateModelProviders = useUpdateModelProviders()const updateModelList = useUpdateModelList()const handleRefreshModel = useCallback((@@ -322,6 +337,19 @@ export const useRefreshModel = () => {CustomConfigurationModelFixedFields?: CustomConfigurationModelFixedFields,refreshModelList?: boolean,) => {+ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: provider.provider,+ },+ },+ })+ queryClient.invalidateQueries({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'none',+ })+updateModelProviders()provider.supported_model_types.forEach((type) => {@@ -329,15 +357,17 @@ export const useRefreshModel = () => {})if (refreshModelList && provider.custom_configuration.status === CustomConfigurationStatusEnum.active) {- eventEmitter?.emit({- type: UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST,- payload: provider.provider,- } as any)+ expandModelProviderList(provider.provider)+ queryClient.invalidateQueries({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'active',+ })if (CustomConfigurationModelFixedFields?.__model_type)updateModelList(CustomConfigurationModelFixedFields.__model_type)}- }, [eventEmitter, updateModelList, updateModelProviders])+ }, [expandModelProviderList, queryClient, updateModelList, updateModelProviders])return {handleRefreshModel,diff --git a/web/app/components/header/account-setting/model-provider-page/index.non-cloud.spec.tsx b/web/app/components/header/account-setting/model-provider-page/index.non-cloud.spec.tsxnew file mode 100644index 00000000000..c543c744724--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/index.non-cloud.spec.tsx@@ -0,0 +1,89 @@+import { render, screen } from '@testing-library/react'+import {+ CurrentSystemQuotaTypeEnum,+ CustomConfigurationStatusEnum,+ QuotaUnitEnum,+} from './declarations'+import ModelProviderPage from './index'++const mockQuotaConfig = {+ quota_type: CurrentSystemQuotaTypeEnum.free,+ quota_unit: QuotaUnitEnum.times,+ quota_limit: 100,+ quota_used: 1,+ last_used: 0,+ is_valid: true,+}++vi.mock('@/config', () => ({+ IS_CLOUD_EDITION: false,+}))++vi.mock('@/context/global-public-context', () => ({+ useSystemFeaturesQuery: () => ({+ data: {+ enable_marketplace: false,+ },+ }),+}))++vi.mock('@/context/provider-context', () => ({+ useProviderContext: () => ({+ modelProviders: [{+ provider: 'openai',+ label: { en_US: 'OpenAI' },+ custom_configuration: { status: CustomConfigurationStatusEnum.active },+ system_configuration: {+ enabled: false,+ current_quota_type: CurrentSystemQuotaTypeEnum.free,+ quota_configurations: [mockQuotaConfig],+ },+ }],+ }),+}))++vi.mock('./hooks', () => ({+ useDefaultModel: () => ({ data: null, isLoading: false }),+}))++vi.mock('./provider-added-card', () => ({+ default: () => <div data-testid="provider-card" />,+}))++vi.mock('./provider-added-card/quota-panel', () => ({+ default: () => <div data-testid="quota-panel" />,+}))++vi.mock('./system-model-selector', () => ({+ default: () => <div data-testid="system-model-selector" />,+}))++vi.mock('./install-from-marketplace', () => ({+ default: () => <div data-testid="install-from-marketplace" />,+}))++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQuery: () => ({ data: undefined }),+ }+})++vi.mock('@/service/client', () => ({+ consoleQuery: {+ plugins: {+ checkInstalled: { queryOptions: () => ({}) },+ latestVersions: { queryOptions: () => ({}) },+ },+ },+}))++describe('ModelProviderPage non-cloud branch', () => {+ it('should skip the quota panel when cloud edition is disabled', () => {+ render(<ModelProviderPage searchText="" />)++ expect(screen.getByTestId('system-model-selector')).toBeInTheDocument()+ expect(screen.queryByTestId('quota-panel')).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/index.tsx b/web/app/components/header/account-setting/model-provider-page/index.tsxindex 4fb1b770e18..58b4b61fc02 100644--- a/web/app/components/header/account-setting/model-provider-page/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/index.tsx@@ -1,17 +1,16 @@import type {ModelProvider,} from './declarations'-import {- RiAlertFill,- RiBrainLine,-} from '@remixicon/react'+import type { PluginDetail } from '@/app/components/plugins/types'+import { useQuery } from '@tanstack/react-query'import { useDebounce } from 'ahooks'-import { useEffect, useMemo } from 'react'+import { useMemo } from 'react'import { useTranslation } from 'react-i18next'+import { usePluginsWithLatestVersion } from '@/app/components/plugins/hooks'import { IS_CLOUD_EDITION } from '@/config'-import { useAppContext } from '@/context/app-context'-import { useGlobalPublicStore } from '@/context/global-public-context'+import { useSystemFeaturesQuery } from '@/context/global-public-context'import { useProviderContext } from '@/context/provider-context'+import { consoleQuery } from '@/service/client'import { cn } from '@/utils/classnames'import {CustomConfigurationStatusEnum,@@ -24,6 +23,9 @@ import InstallFromMarketplace from './install-from-marketplace'import ProviderAddedCard from './provider-added-card'import QuotaPanel from './provider-added-card/quota-panel'import SystemModelSelector from './system-model-selector'+import { providerToPluginId } from './utils'++type SystemModelConfigStatus = 'no-provider' | 'none-configured' | 'partially-configured' | 'fully-configured'type Props = {searchText: string@@ -34,20 +36,35 @@ const FixedModelProvider = ['langgenius/openai/openai', 'langgenius/anthropic/anconst ModelProviderPage = ({ searchText }: Props) => {const debouncedSearchText = useDebounce(searchText, { wait: 500 })const { t } = useTranslation()- const { mutateCurrentWorkspace, isValidatingCurrentWorkspace } = useAppContext()const { data: textGenerationDefaultModel, isLoading: isTextGenerationDefaultModelLoading } = useDefaultModel(ModelTypeEnum.textGeneration)const { data: embeddingsDefaultModel, isLoading: isEmbeddingsDefaultModelLoading } = useDefaultModel(ModelTypeEnum.textEmbedding)const { data: rerankDefaultModel, isLoading: isRerankDefaultModelLoading } = useDefaultModel(ModelTypeEnum.rerank)const { data: speech2textDefaultModel, isLoading: isSpeech2textDefaultModelLoading } = useDefaultModel(ModelTypeEnum.speech2text)const { data: ttsDefaultModel, isLoading: isTTSDefaultModelLoading } = useDefaultModel(ModelTypeEnum.tts)const { modelProviders: providers } = useProviderContext()- const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)+ const { data: systemFeatures } = useSystemFeaturesQuery()++ const allPluginIds = useMemo(() => {+ return [...new Set(providers.map(p => providerToPluginId(p.provider)).filter(Boolean))]+ }, [providers])+ const { data: installedPlugins } = useQuery(consoleQuery.plugins.checkInstalled.queryOptions({+ input: { body: { plugin_ids: allPluginIds } },+ enabled: allPluginIds.length > 0,+ staleTime: 0,+ }))+ const enrichedPlugins = usePluginsWithLatestVersion(installedPlugins?.plugins)+ const pluginDetailMap = useMemo(() => {+ const map = new Map<string, PluginDetail>()+ for (const plugin of enrichedPlugins)+ map.set(plugin.plugin_id, plugin)+ return map+ }, [enrichedPlugins])+ const enableMarketplace = systemFeatures?.enable_marketplace ?? falseconst isDefaultModelLoading = isTextGenerationDefaultModelLoading|| isEmbeddingsDefaultModelLoading|| isRerankDefaultModelLoading|| isSpeech2textDefaultModelLoading|| isTTSDefaultModelLoading- const defaultModelNotConfigured = !isDefaultModelLoading && !textGenerationDefaultModel && !embeddingsDefaultModel && !speech2textDefaultModel && !rerankDefaultModel && !ttsDefaultModelconst [configuredProviders, notConfiguredProviders] = useMemo(() => {const configuredProviders: ModelProvider[] = []const notConfiguredProviders: ModelProvider[] = []@@ -57,7 +74,7 @@ const ModelProviderPage = ({ searchText }: Props) => {provider.custom_configuration.status === CustomConfigurationStatusEnum.active|| (provider.system_configuration.enabled === true- && provider.system_configuration.quota_configurations.find(item => item.quota_type === provider.system_configuration.current_quota_type)+ && provider.system_configuration.quota_configurations.some(item => item.quota_type === provider.system_configuration.current_quota_type))) {configuredProviders.push(provider)@@ -79,6 +96,26 @@ const ModelProviderPage = ({ searchText }: Props) => {return [configuredProviders, notConfiguredProviders]}, [providers])++ const systemModelConfigStatus: SystemModelConfigStatus = useMemo(() => {+ const defaultModels = [textGenerationDefaultModel, embeddingsDefaultModel, rerankDefaultModel, speech2textDefaultModel, ttsDefaultModel]+ const configuredCount = defaultModels.filter(Boolean).length+ if (configuredCount === 0 && configuredProviders.length === 0)+ return 'no-provider'+ if (configuredCount === 0)+ return 'none-configured'+ if (configuredCount < defaultModels.length)+ return 'partially-configured'+ return 'fully-configured'+ }, [configuredProviders, textGenerationDefaultModel, embeddingsDefaultModel, rerankDefaultModel, speech2textDefaultModel, ttsDefaultModel])+ const warningTextKey+ = systemModelConfigStatus === 'none-configured'+ ? 'modelProvider.noneConfigured'+ : systemModelConfigStatus === 'partially-configured'+ ? 'modelProvider.notConfigured'+ : null+ const showWarning = !isDefaultModelLoading && !!warningTextKey+const [filteredConfiguredProviders, filteredNotConfiguredProviders] = useMemo(() => {const filteredConfiguredProviders = configuredProviders.filter(provider => provider.provider.toLowerCase().includes(debouncedSearchText.toLowerCase())@@ -92,28 +129,24 @@ const ModelProviderPage = ({ searchText }: Props) => {return [filteredConfiguredProviders, filteredNotConfiguredProviders]}, [configuredProviders, debouncedSearchText, notConfiguredProviders])- useEffect(() => {- mutateCurrentWorkspace()- }, [mutateCurrentWorkspace])-return (<div className="relative -mt-2 pt-1"><div className={cn('mb-2 flex items-center')}><div className="grow text-text-primary system-md-semibold">{t('modelProvider.models', { ns: 'common' })}</div><div className={cn('relative flex shrink-0 items-center justify-end gap-2 rounded-lg border border-transparent p-px',- defaultModelNotConfigured && 'border-components-panel-border bg-components-panel-bg-blur pl-2 shadow-xs',+ showWarning && 'border-components-panel-border bg-components-panel-bg-blur pl-2 shadow-xs',)}>- {defaultModelNotConfigured && <div className="absolute bottom-0 left-0 right-0 top-0 opacity-40" style={{ background: 'linear-gradient(92deg, rgba(247, 144, 9, 0.25) 0%, rgba(255, 255, 255, 0.00) 100%)' }} />}- {defaultModelNotConfigured && (+ {showWarning && <div className="absolute bottom-0 left-0 right-0 top-0 opacity-40" style={{ background: 'linear-gradient(92deg, rgba(247, 144, 9, 0.25) 0%, rgba(255, 255, 255, 0.00) 100%)' }} />}+ {showWarning && (<div className="flex items-center gap-1 text-text-primary system-xs-medium">- <RiAlertFill className="h-4 w-4 text-text-warning-secondary" />- <span className="max-w-[460px] truncate" title={t('modelProvider.notConfigured', { ns: 'common' })}>{t('modelProvider.notConfigured', { ns: 'common' })}</span>+ <span className="i-ri-alert-fill h-4 w-4 text-text-warning-secondary" />+ <span className="max-w-[460px] truncate" title={t(warningTextKey, { ns: 'common' })}>{t(warningTextKey, { ns: 'common' })}</span></div>)}<SystemModelSelector- notConfigured={defaultModelNotConfigured}+ notConfigured={showWarning}textGenerationDefaultModel={textGenerationDefaultModel}embeddingsDefaultModel={embeddingsDefaultModel}rerankDefaultModel={rerankDefaultModel}@@ -123,11 +156,11 @@ const ModelProviderPage = ({ searchText }: Props) => {/></div></div>- {IS_CLOUD_EDITION && <QuotaPanel providers={providers} isLoading={isValidatingCurrentWorkspace} />}+ {IS_CLOUD_EDITION && <QuotaPanel providers={providers} />}{!filteredConfiguredProviders?.length && (<div className="mb-2 rounded-[10px] bg-workflow-process-bg p-4"><div className="flex h-10 w-10 items-center justify-center rounded-[10px] border-[0.5px] border-components-card-border bg-components-card-bg shadow-lg backdrop-blur">- <RiBrainLine className="h-5 w-5 text-text-primary" />+ <span className="i-ri-brain-line h-5 w-5 text-text-primary" /></div><div className="mt-2 text-text-secondary system-sm-medium">{t('modelProvider.emptyProviderTitle', { ns: 'common' })}</div><div className="mt-1 text-text-tertiary system-xs-regular">{t('modelProvider.emptyProviderTip', { ns: 'common' })}</div>@@ -139,6 +172,7 @@ const ModelProviderPage = ({ searchText }: Props) => {<ProviderAddedCardkey={provider.provider}provider={provider}+ pluginDetail={pluginDetailMap.get(providerToPluginId(provider.provider))}/>))}</div>@@ -152,13 +186,14 @@ const ModelProviderPage = ({ searchText }: Props) => {notConfiguredkey={provider.provider}provider={provider}+ pluginDetail={pluginDetailMap.get(providerToPluginId(provider.provider))}/>))}</div></>)}{- enable_marketplace && (+ enableMarketplace && (<InstallFromMarketplaceproviders={providers}searchText={searchText}diff --git a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsxindex 289146f2d2a..ab712f27ccd 100644--- a/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx+++ b/web/app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx@@ -2,10 +2,6 @@ import type {ModelProvider,} from './declarations'import type { Plugin } from '@/app/components/plugins/types'-import {- RiArrowDownSLine,- RiArrowRightUpLine,-} from '@remixicon/react'import { useTheme } from 'next-themes'import Link from 'next/link'import { useCallback, useState } from 'react'@@ -47,15 +43,25 @@ const InstallFromMarketplace = ({<div className="mb-2"><Divider className="!mt-4 h-px" /><div className="flex items-center justify-between">- <div className="system-md-semibold flex cursor-pointer items-center gap-1 text-text-primary" onClick={() => setCollapse(!collapse)}>- <RiArrowDownSLine className={cn('h-4 w-4', collapse && '-rotate-90')} />+ <button+ type="button"+ className="flex cursor-pointer items-center gap-1 border-0 bg-transparent p-0 text-left text-text-primary system-md-semibold"+ onClick={() => setCollapse(prev => !prev)}+ aria-expanded={!collapse}+ >+ <span className={cn('i-ri-arrow-down-s-line h-4 w-4', collapse && '-rotate-90')} />{t('modelProvider.installProvider', { ns: 'common' })}- </div>+ </button><div className="mb-2 flex items-center pt-2">- <span className="system-sm-regular pr-1 text-text-tertiary">{t('modelProvider.discoverMore', { ns: 'common' })}</span>- <Link target="_blank" href={getMarketplaceUrl('', { theme })} className="system-sm-medium inline-flex items-center text-text-accent">+ <span className="pr-1 text-text-tertiary system-sm-regular">{t('modelProvider.discoverMore', { ns: 'common' })}</span>+ <Link+ target="_blank"+ rel="noopener noreferrer"+ href={getMarketplaceUrl('', { theme })}+ className="inline-flex items-center text-text-accent system-sm-medium"+ >{t('marketplace.difyMarketplace', { ns: 'plugin' })}- <RiArrowRightUpLine className="h-4 w-4" />+ <span className="i-ri-arrow-right-up-line h-4 w-4" /></Link></div></div>diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/credential-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/credential-item.spec.tsxindex 1083b17c28a..c5ef0028fba 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/credential-item.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/__tests__/credential-item.spec.tsx@@ -2,12 +2,6 @@ import type { Credential } from '../../../declarations'import { fireEvent, render, screen } from '@testing-library/react'import CredentialItem from '../credential-item'-vi.mock('@remixicon/react', () => ({- RiCheckLine: () => <div data-testid="check-icon" />,- RiDeleteBinLine: () => <div data-testid="delete-icon" />,- RiEqualizer2Line: () => <div data-testid="edit-icon" />,-}))-vi.mock('@/app/components/header/indicator', () => ({default: () => <div data-testid="indicator" />,}))@@ -61,8 +55,12 @@ describe('CredentialItem', () => {render(<CredentialItem credential={credential} onEdit={onEdit} onDelete={onDelete} />)- fireEvent.click(screen.getByTestId('edit-icon').closest('button') as HTMLButtonElement)- fireEvent.click(screen.getByTestId('delete-icon').closest('button') as HTMLButtonElement)+ const buttons = screen.getAllByRole('button')+ const editButton = buttons.find(b => b.querySelector('.i-ri-equalizer-2-line'))!+ const deleteButton = buttons.find(b => b.querySelector('.i-ri-delete-bin-line'))!++ fireEvent.click(editButton)+ fireEvent.click(deleteButton)expect(onEdit).toHaveBeenCalledWith(credential)expect(onDelete).toHaveBeenCalledWith(credential)@@ -81,7 +79,10 @@ describe('CredentialItem', () => {/>,)- fireEvent.click(screen.getByTestId('delete-icon').closest('button') as HTMLButtonElement)+ const deleteButton = screen.getAllByRole('button')+ .find(b => b.querySelector('.i-ri-delete-bin-line'))!++ fireEvent.click(deleteButton)expect(onDelete).not.toHaveBeenCalled()})@@ -121,14 +122,16 @@ describe('CredentialItem', () => {render(<CredentialItem credential={credential} disabled onDelete={onDelete} />)- fireEvent.click(screen.getByTestId('delete-icon').closest('button') as HTMLButtonElement)+ const deleteButton = screen.getAllByRole('button')+ .find(b => b.querySelector('.i-ri-delete-bin-line'))!+ fireEvent.click(deleteButton)expect(onDelete).not.toHaveBeenCalled()})// showSelectedIcon=true: check icon area is always rendered; check icon only appears when IDs matchit('should render check icon area when showSelectedIcon=true and selectedCredentialId matches', () => {- render(+ const { container } = render(<CredentialItemcredential={credential}showSelectedIcon@@ -136,7 +139,7 @@ describe('CredentialItem', () => {/>,)- expect(screen.getByTestId('check-icon')).toBeInTheDocument()+ expect(container.querySelector('.i-ri-check-line')).toBeInTheDocument()})it('should not render check icon when showSelectedIcon=true but selectedCredentialId does not match', () => {diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/credential-item.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/credential-item.tsxindex 11fb65c3e59..95f84e5908c 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/credential-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/authorized/credential-item.tsx@@ -1,9 +1,4 @@import type { Credential } from '../../declarations'-import {- RiCheckLine,- RiDeleteBinLine,- RiEqualizer2Line,-} from '@remixicon/react'import {memo,useMemo,@@ -11,7 +6,7 @@ import {import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'import Badge from '@/app/components/base/badge'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import Indicator from '@/app/components/header/indicator'import { cn } from '@/utils/classnames'@@ -56,7 +51,7 @@ const CredentialItem = ({key={credential.credential_id}className={cn('group flex h-8 items-center rounded-lg p-1 hover:bg-state-base-hover',- (disabled || credential.not_allowed_to_use) && 'cursor-not-allowed opacity-50',+ (disabled || credential.not_allowed_to_use) ? 'cursor-not-allowed opacity-50' : onItemClick && 'cursor-pointer',)}onClick={() => {if (disabled || credential.not_allowed_to_use)@@ -70,7 +65,7 @@ const CredentialItem = ({<div className="h-4 w-4">{selectedCredentialId === credential.credential_id && (- <RiCheckLine className="h-4 w-4 text-text-accent" />+ <span className="i-ri-check-line h-4 w-4 text-text-accent" />)}</div>@@ -78,7 +73,7 @@ const CredentialItem = ({}<Indicator className="ml-2 mr-1.5 shrink-0" /><div- className="system-md-regular truncate text-text-secondary"+ className="truncate text-text-secondary system-md-regular"title={credential.credential_name}>{credential.credential_name}@@ -96,38 +91,50 @@ const CredentialItem = ({<div className="ml-2 hidden shrink-0 items-center group-hover:flex">{!disableEdit && !credential.not_allowed_to_use && (- <Tooltip popupContent={t('operation.edit', { ns: 'common' })}>- <ActionButton- disabled={disabled}- onClick={(e) => {- e.stopPropagation()- onEdit?.(credential)- }}- >- <RiEqualizer2Line className="h-4 w-4 text-text-tertiary" />- </ActionButton>+ <Tooltip>+ <TooltipTrigger+ render={(+ <ActionButton+ disabled={disabled}+ onClick={(e) => {+ e.stopPropagation()+ onEdit?.(credential)+ }}+ >+ <span className="i-ri-equalizer-2-line h-4 w-4 text-text-tertiary" />+ </ActionButton>+ )}+ />+ <TooltipContent>{t('operation.edit', { ns: 'common' })}</TooltipContent></Tooltip>)}{!disableDelete && (- <Tooltip popupContent={disableDeleteWhenSelected ? disableDeleteTip : t('operation.delete', { ns: 'common' })}>- <ActionButton- className="hover:bg-transparent"- onClick={(e) => {- if (disabled || disableDeleteWhenSelected)- return- e.stopPropagation()- onDelete?.(credential)- }}- >- <RiDeleteBinLine className={cn(- 'h-4 w-4 text-text-tertiary',- !disableDeleteWhenSelected && 'hover:text-text-destructive',- disableDeleteWhenSelected && 'opacity-50',+ <Tooltip>+ <TooltipTrigger+ render={(+ <ActionButton+ className="hover:bg-transparent"+ onClick={(e) => {+ if (disabled || disableDeleteWhenSelected)+ return+ e.stopPropagation()+ onDelete?.(credential)+ }}+ >+ <span className={cn(+ 'i-ri-delete-bin-line h-4 w-4 text-text-tertiary',+ !disableDeleteWhenSelected && 'hover:text-text-destructive',+ disableDeleteWhenSelected && 'opacity-50',+ )}+ />+ </ActionButton>)}- />- </ActionButton>+ />+ <TooltipContent>+ {disableDeleteWhenSelected ? disableDeleteTip : t('operation.delete', { ns: 'common' })}+ </TooltipContent></Tooltip>)}@@ -139,8 +146,9 @@ const CredentialItem = ({if (credential.not_allowed_to_use) {return (- <Tooltip popupContent={t('auth.customCredentialUnavailable', { ns: 'plugin' })}>- {Item}+ <Tooltip>+ <TooltipTrigger render={Item} />+ <TooltipContent>{t('auth.customCredentialUnavailable', { ns: 'plugin' })}</TooltipContent></Tooltip>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-credential-status.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-credential-status.spec.tsxindex a58178f21e2..ac35be3ef7f 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-credential-status.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/__tests__/use-credential-status.spec.tsx@@ -53,4 +53,14 @@ describe('useCredentialStatus', () => {expect(result.current.hasCredential).toBe(false)expect(result.current.available_credentials).toBeUndefined()})++ it('handles undefined provider gracefully', () => {+ const { result } = renderHook(() => useCredentialStatus(undefined))+ expect(result.current.hasCredential).toBe(false)+ expect(result.current.authorized).toBeFalsy()+ expect(result.current.authRemoved).toBe(false)+ expect(result.current.available_credentials).toBeUndefined()+ expect(result.current.current_credential_id).toBeUndefined()+ expect(result.current.current_credential_name).toBeUndefined()+ })})diff --git a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-credential-status.ts b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-credential-status.tsindex 263940afcbe..84ac587656a 100644--- a/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-credential-status.ts+++ b/web/app/components/header/account-setting/model-provider-page/model-auth/hooks/use-credential-status.ts@@ -3,12 +3,12 @@ import type {} from '../../declarations'import { useMemo } from 'react'-export const useCredentialStatus = (provider: ModelProvider) => {+export const useCredentialStatus = (provider: ModelProvider | undefined) => {const {current_credential_id,current_credential_name,available_credentials,- } = provider.custom_configuration+ } = provider?.custom_configuration ?? {}const hasCredential = !!available_credentials?.lengthconst authorized = current_credential_id && current_credential_nameconst authRemoved = hasCredential && !current_credential_id && !current_credential_namediff --git a/web/app/components/header/account-setting/model-provider-page/model-badge/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-badge/index.tsxindex 29da08dc220..cb641ec0fb5 100644--- a/web/app/components/header/account-setting/model-provider-page/model-badge/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-badge/index.tsx@@ -10,7 +10,7 @@ const ModelBadge: FC<ModelBadgeProps> = ({children,}) => {return (- <div className={cn('system-2xs-medium-uppercase flex h-[18px] cursor-default items-center rounded-[5px] border border-divider-deep px-1 text-text-tertiary', className)}>+ <div className={cn('inline-flex h-[18px] shrink-0 items-center justify-center whitespace-nowrap rounded-[5px] border border-divider-deep bg-components-badge-bg-dimm px-[5px] text-text-tertiary system-2xs-medium-uppercase', className)}>{children}</div>)diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsxindex 8118db6deab..a47b5eb1702 100644--- a/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/__tests__/index.spec.tsx@@ -1,7 +1,6 @@-import type { ComponentProps } from 'react'-import type { Credential, CredentialFormSchema, CustomModel, ModelProvider } from '../../declarations'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import * as React from 'react'+import type * as React from 'react'+import type { Credential, CredentialFormSchema, ModelProvider } from '../../declarations'+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'import {ConfigurationMethodEnum,CurrentSystemQuotaTypeEnum,@@ -45,6 +44,15 @@ const mockHandlers = vi.hoisted(() => ({handleActiveCredential: vi.fn(),}))+type FormResponse = {+ isCheckValidated: boolean+ values: Record<string, unknown>+}+const mockFormState = vi.hoisted(() => ({+ responses: [] as FormResponse[],+ setFieldValue: vi.fn(),+}))+vi.mock('../../model-auth/hooks', () => ({useCredentialData: () => ({isLoading: mockState.isLoading,@@ -79,6 +87,36 @@ vi.mock('../../hooks', () => ({useLanguage: () => 'en_US',}))+vi.mock('@/app/components/base/form/form-scenarios/auth', async () => {+ const React = await import('react')+ const AuthForm = React.forwardRef(({+ onChange,+ }: {+ onChange?: (field: string, value: string) => void+ }, ref: React.ForwardedRef<{ getFormValues: () => FormResponse, getForm: () => { setFieldValue: (field: string, value: string) => void } }>) => {+ React.useImperativeHandle(ref, () => ({+ getFormValues: () => mockFormState.responses.shift() || { isCheckValidated: false, values: {} },+ getForm: () => ({ setFieldValue: mockFormState.setFieldValue }),+ }))+ return (+ <div>+ <button type="button" onClick={() => onChange?.('__model_name', 'updated-model')}>Model Name Change</button>+ </div>+ )+ })++ return { default: AuthForm }+})++vi.mock('../../model-auth', () => ({+ CredentialSelector: ({ onSelect }: { onSelect: (credential: Credential & { addNewCredential?: boolean }) => void }) => (+ <div>+ <button type="button" onClick={() => onSelect({ credential_id: 'existing' })}>Choose Existing</button>+ <button type="button" onClick={() => onSelect({ credential_id: 'new', addNewCredential: true })}>Add New</button>+ </div>+ ),+}))+const createI18n = (text: string) => ({ en_US: text, zh_Hans: text })const createProvider = (overrides?: Partial<ModelProvider>): ModelProvider => ({@@ -121,7 +159,7 @@ const createProvider = (overrides?: Partial<ModelProvider>): ModelProvider => ({...overrides,})-const renderModal = (overrides?: Partial<ComponentProps<typeof ModelModal>>) => {+const renderModal = (overrides?: Partial<React.ComponentProps<typeof ModelModal>>) => {const provider = createProvider()const props = {provider,@@ -131,50 +169,13 @@ const renderModal = (overrides?: Partial<ComponentProps<typeof ModelModal>>) =>onRemove: vi.fn(),...overrides,}- render(<ModelModal {...props} />)- return props-}--const mockFormRef1 = {- getFormValues: vi.fn(),- getForm: vi.fn(() => ({ setFieldValue: vi.fn() })),-}--const mockFormRef2 = {- getFormValues: vi.fn(),- getForm: vi.fn(() => ({ setFieldValue: vi.fn() })),+ const view = render(<ModelModal {...props} />)+ return {+ ...props,+ unmount: view.unmount,+ }}-vi.mock('@/app/components/base/form/form-scenarios/auth', () => ({- default: React.forwardRef((props: { formSchemas: Record<string, unknown>[], onChange?: (f: string, v: string) => void }, ref: React.ForwardedRef<unknown>) => {- React.useImperativeHandle(ref, () => {- // Return the mock depending on schemas passed (hacky but works for refs)- if (props.formSchemas.length > 0 && props.formSchemas[0].name === '__model_name')- return mockFormRef1- return mockFormRef2- })- return (- <div data-testid="auth-form" onClick={() => props.onChange?.('test-field', 'val')}>- AuthForm Mock (- {props.formSchemas.length}- {' '}- fields)- </div>- )- }),-}))--vi.mock('../../model-auth', () => ({- CredentialSelector: ({ onSelect }: { onSelect: (val: unknown) => void }) => (- <button onClick={() => onSelect({ addNewCredential: true })} data-testid="credential-selector">- Select Credential- </button>- ),- useAuth: vi.fn(),- useCredentialData: vi.fn(),- useModelFormSchemas: vi.fn(),-}))-describe('ModelModal', () => {beforeEach(() => {vi.clearAllMocks()@@ -187,131 +188,168 @@ describe('ModelModal', () => {mockState.formValues = {}mockState.modelNameAndTypeFormSchemas = []mockState.modelNameAndTypeFormValues = {}-- // reset form refs- mockFormRef1.getFormValues.mockReturnValue({ isCheckValidated: true, values: { __model_name: 'test', __model_type: ModelTypeEnum.textGeneration } })- mockFormRef2.getFormValues.mockReturnValue({ isCheckValidated: true, values: { __authorization_name__: 'test_auth', api_key: 'sk-test' } })+ mockFormState.responses = []})- it('should render title and loading state for predefined credential modal', () => {+ it('should show title, description, and loading state for predefined models', () => {mockState.isLoading = true- renderModal()++ const predefined = renderModal()+expect(screen.getByText('common.modelProvider.auth.apiKeyModal.title')).toBeInTheDocument()expect(screen.getByText('common.modelProvider.auth.apiKeyModal.desc')).toBeInTheDocument()- })+ expect(screen.getByRole('status')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.save' })).toBeDisabled()- it('should render model credential title when mode is configModelCredential', () => {- renderModal({- mode: ModelModalModeEnum.configModelCredential,- model: { model: 'gpt-4', model_type: ModelTypeEnum.textGeneration },- })+ predefined.unmount()+ const customizable = renderModal({ configurateMethod: ConfigurationMethodEnum.customizableModel })+ expect(screen.queryByText('common.modelProvider.auth.apiKeyModal.desc')).not.toBeInTheDocument()+ customizable.unmount()++ mockState.credentialData = { credentials: {}, available_credentials: [] }+ renderModal({ mode: ModelModalModeEnum.configModelCredential, model: { model: 'gpt-4', model_type: ModelTypeEnum.textGeneration } })expect(screen.getByText('common.modelProvider.auth.addModelCredential')).toBeInTheDocument()})- it('should render edit credential title when credential exists', () => {- renderModal({- mode: ModelModalModeEnum.configModelCredential,- credential: { credential_id: '1' } as unknown as Credential,- })- expect(screen.getByText('common.modelProvider.auth.editModelCredential')).toBeInTheDocument()+ it('should reveal the credential label when adding a new credential', () => {+ renderModal({ mode: ModelModalModeEnum.addCustomModelToModelList })++ expect(screen.queryByText('common.modelProvider.auth.modelCredential')).not.toBeInTheDocument()++ fireEvent.click(screen.getByText('Add New'))++ expect(screen.getByText('common.modelProvider.auth.modelCredential')).toBeInTheDocument()})- it('should change title to Add Model when mode is configCustomModel', () => {- mockState.modelNameAndTypeFormSchemas = [{ variable: '__model_name', type: 'text' } as unknown as CredentialFormSchema]- renderModal({ mode: ModelModalModeEnum.configCustomModel })- expect(screen.getByText('common.modelProvider.auth.addModel')).toBeInTheDocument()+ it('should call onCancel when the cancel button is clicked', () => {+ const { onCancel } = renderModal()++ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))++ expect(onCancel).toHaveBeenCalledTimes(1)})- it('should validate and fail save if form is invalid in configCustomModel mode', async () => {- mockState.modelNameAndTypeFormSchemas = [{ variable: '__model_name', type: 'text' } as unknown as CredentialFormSchema]- mockFormRef1.getFormValues.mockReturnValue({ isCheckValidated: false, values: {} })- renderModal({ mode: ModelModalModeEnum.configCustomModel })- fireEvent.click(screen.getByRole('button', { name: 'common.operation.add' }))- expect(mockHandlers.handleSaveCredential).not.toHaveBeenCalled()+ it('should call onCancel when the escape key is pressed', () => {+ const { onCancel } = renderModal()++ fireEvent.keyDown(document, { key: 'Escape' })++ expect(onCancel).toHaveBeenCalledTimes(1)+ })++ it('should confirm deletion when a delete dialog is shown', () => {+ mockState.credentialData = { credentials: { api_key: 'secret' }, available_credentials: [] }+ mockState.deleteCredentialId = 'delete-id'++ const credential: Credential = { credential_id: 'cred-1' }+ const { onCancel } = renderModal({ credential })++ const alertDialog = screen.getByRole('alertdialog', { hidden: true })+ expect(alertDialog).toHaveTextContent('common.modelProvider.confirmDelete')++ fireEvent.click(within(alertDialog).getByRole('button', { hidden: true, name: 'common.operation.confirm' }))++ expect(mockHandlers.handleConfirmDelete).toHaveBeenCalledTimes(1)+ expect(onCancel).toHaveBeenCalledTimes(1)})- it('should validate and save new credential and model in configCustomModel mode', async () => {- mockState.modelNameAndTypeFormSchemas = [{ variable: '__model_name', type: 'text' } as unknown as CredentialFormSchema]- const props = renderModal({ mode: ModelModalModeEnum.configCustomModel })+ it('should handle save flows for different modal modes', async () => {+ mockState.modelNameAndTypeFormSchemas = [{ variable: '__model_name', type: 'text-input' } as unknown as CredentialFormSchema]+ mockState.formSchemas = [{ variable: 'api_key', type: 'secret-input' } as unknown as CredentialFormSchema]+ mockFormState.responses = [+ { isCheckValidated: true, values: { __model_name: 'custom-model', __model_type: ModelTypeEnum.textGeneration } },+ { isCheckValidated: true, values: { __authorization_name__: 'Auth Name', api_key: 'secret' } },+ ]+ const configCustomModel = renderModal({ mode: ModelModalModeEnum.configCustomModel })+ fireEvent.click(screen.getAllByText('Model Name Change')[0])fireEvent.click(screen.getByRole('button', { name: 'common.operation.add' }))+ expect(mockFormState.setFieldValue).toHaveBeenCalledWith('__model_name', 'updated-model')await waitFor(() => {expect(mockHandlers.handleSaveCredential).toHaveBeenCalledWith({credential_id: undefined,- credentials: { api_key: 'sk-test' },- name: 'test_auth',- model: 'test',+ credentials: { api_key: 'secret' },+ name: 'Auth Name',+ model: 'custom-model',model_type: ModelTypeEnum.textGeneration,})- expect(props.onSave).toHaveBeenCalled()})- })+ expect(configCustomModel.onSave).toHaveBeenCalledWith({ __authorization_name__: 'Auth Name', api_key: 'secret' })+ configCustomModel.unmount()- it('should save credential only in standard configProviderCredential mode', async () => {- const { onSave } = renderModal({ mode: ModelModalModeEnum.configProviderCredential })+ mockFormState.responses = [{ isCheckValidated: true, values: { __authorization_name__: 'Model Auth', api_key: 'abc' } }]+ const model = { model: 'gpt-4', model_type: ModelTypeEnum.textGeneration }+ const configModelCredential = renderModal({+ mode: ModelModalModeEnum.configModelCredential,+ model,+ credential: { credential_id: 'cred-123' },+ })fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => {+ expect(mockHandlers.handleSaveCredential).toHaveBeenCalledWith({+ credential_id: 'cred-123',+ credentials: { api_key: 'abc' },+ name: 'Model Auth',+ model: 'gpt-4',+ model_type: ModelTypeEnum.textGeneration,+ })+ })+ expect(configModelCredential.onSave).toHaveBeenCalledWith({ __authorization_name__: 'Model Auth', api_key: 'abc' })+ configModelCredential.unmount()+ mockFormState.responses = [{ isCheckValidated: true, values: { __authorization_name__: 'Provider Auth', api_key: 'provider-key' } }]+ const configProviderCredential = renderModal({ mode: ModelModalModeEnum.configProviderCredential })+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))await waitFor(() => {expect(mockHandlers.handleSaveCredential).toHaveBeenCalledWith({credential_id: undefined,- credentials: { api_key: 'sk-test' },- name: 'test_auth',+ credentials: { api_key: 'provider-key' },+ name: 'Provider Auth',})- expect(onSave).toHaveBeenCalled()})- })+ configProviderCredential.unmount()- it('should save active credential and cancel when picking existing credential in addCustomModelToModelList mode', async () => {- renderModal({ mode: ModelModalModeEnum.addCustomModelToModelList, model: { model: 'm1', model_type: ModelTypeEnum.textGeneration } as unknown as CustomModel })- // By default selected is undefined so button clicks form- // Let's not click credential selector, so it evaluates without it. If selectedCredential is undefined, form validation is checked.- mockFormRef2.getFormValues.mockReturnValue({ isCheckValidated: false, values: {} })+ const addToModelList = renderModal({+ mode: ModelModalModeEnum.addCustomModelToModelList,+ model,+ })+ fireEvent.click(screen.getByText('Choose Existing'))fireEvent.click(screen.getByRole('button', { name: 'common.operation.add' }))- expect(mockHandlers.handleSaveCredential).not.toHaveBeenCalled()- })-- it('should save active credential when picking existing credential in addCustomModelToModelList mode', async () => {- renderModal({ mode: ModelModalModeEnum.addCustomModelToModelList, model: { model: 'm2', model_type: ModelTypeEnum.textGeneration } as unknown as CustomModel })-- // Select existing credential (addNewCredential: true simulates new but we can simulate false if we just hack the mocked state in the component, but it's internal.- // The credential selector sets selectedCredential.- fireEvent.click(screen.getByTestId('credential-selector')) // Sets addNewCredential = true internally, so it proceeds to form save-- mockFormRef2.getFormValues.mockReturnValue({ isCheckValidated: true, values: { __authorization_name__: 'auth', api: 'key' } })+ expect(mockHandlers.handleActiveCredential).toHaveBeenCalledWith({ credential_id: 'existing' }, model)+ expect(addToModelList.onCancel).toHaveBeenCalled()+ addToModelList.unmount()++ mockFormState.responses = [{ isCheckValidated: true, values: { __authorization_name__: 'New Auth', api_key: 'new-key' } }]+ const addToModelListWithNew = renderModal({+ mode: ModelModalModeEnum.addCustomModelToModelList,+ model,+ })+ fireEvent.click(screen.getByText('Add New'))fireEvent.click(screen.getByRole('button', { name: 'common.operation.add' }))-await waitFor(() => {expect(mockHandlers.handleSaveCredential).toHaveBeenCalledWith({credential_id: undefined,- credentials: { api: 'key' },- name: 'auth',- model: 'm2',+ credentials: { api_key: 'new-key' },+ name: 'New Auth',+ model: 'gpt-4',model_type: ModelTypeEnum.textGeneration,})})- })+ addToModelListWithNew.unmount()- it('should open and confirm deletion of credential', () => {- mockState.credentialData = { credentials: { api_key: '123' }, available_credentials: [] }- mockState.formValues = { api_key: '123' } // To trigger isEditMode = true- const credential = { credential_id: 'c1' } as unknown as Credential- renderModal({ credential })+ mockFormState.responses = [{ isCheckValidated: false, values: {} }]+ const invalidSave = renderModal({ mode: ModelModalModeEnum.configProviderCredential })+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.save' }))+ await waitFor(() => {+ expect(mockHandlers.handleSaveCredential).toHaveBeenCalledTimes(4)+ })+ invalidSave.unmount()- // Open Delete Confirm+ mockState.credentialData = { credentials: { api_key: 'value' }, available_credentials: [] }+ mockState.formValues = { api_key: 'value' }+ const removable = renderModal({ credential: { credential_id: 'remove-1' } })fireEvent.click(screen.getByRole('button', { name: 'common.operation.remove' }))- expect(mockHandlers.openConfirmDelete).toHaveBeenCalledWith(credential, undefined)-- // Simulate the dialog appearing and confirming- mockState.deleteCredentialId = 'c1'- renderModal({ credential }) // Re-render logic mock- fireEvent.click(screen.getAllByRole('button', { name: 'common.operation.confirm' })[0])-- expect(mockHandlers.handleConfirmDelete).toHaveBeenCalled()- })-- it('should bind escape key to cancel', () => {- const props = renderModal()- fireEvent.keyDown(document, { key: 'Escape' })- expect(props.onCancel).toHaveBeenCalled()+ expect(mockHandlers.openConfirmDelete).toHaveBeenCalledWith({ credential_id: 'remove-1' }, undefined)+ removable.unmount()})})diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/dialog.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/dialog.spec.tsxnew file mode 100644index 00000000000..9c08560a256--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/dialog.spec.tsx@@ -0,0 +1,271 @@+import type { ReactNode } from 'react'+import type { Credential, ModelProvider } from '../declarations'+import { act, render, screen } from '@testing-library/react'+import { ConfigurationMethodEnum, ModelModalModeEnum } from '../declarations'+import ModelModal from './index'++type DialogProps = {+ children: ReactNode+ onOpenChange?: (open: boolean) => void+}++type AlertDialogProps = {+ children: ReactNode+ onOpenChange?: (open: boolean) => void+}++let mockLanguage = 'en_US'+let latestDialogOnOpenChange: DialogProps['onOpenChange']+let latestAlertDialogOnOpenChange: AlertDialogProps['onOpenChange']+let mockAvailableCredentials: Credential[] | undefined = []+let mockDeleteCredentialId: string | null = null++const mockCloseConfirmDelete = vi.fn()+const mockHandleConfirmDelete = vi.fn()++vi.mock('@/app/components/base/form/form-scenarios/auth', () => ({+ default: () => <div data-testid="auth-form" />,+}))++vi.mock('../model-auth', () => ({+ CredentialSelector: ({ credentials }: { credentials: Credential[] }) => <div>{`credentials:${credentials.length}`}</div>,+}))++vi.mock('@/app/components/base/ui/dialog', () => ({+ Dialog: ({ children, onOpenChange }: DialogProps) => {+ latestDialogOnOpenChange = onOpenChange+ return <div>{children}</div>+ },+ DialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ DialogCloseButton: () => <button type="button">close</button>,+}))++vi.mock('@/app/components/base/ui/alert-dialog', () => ({+ AlertDialog: ({ children, onOpenChange }: AlertDialogProps) => {+ latestAlertDialogOnOpenChange = onOpenChange+ return <div>{children}</div>+ },+ AlertDialogActions: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ AlertDialogCancelButton: ({ children }: { children: ReactNode }) => <button type="button">{children}</button>,+ AlertDialogConfirmButton: ({ children, onClick }: { children: ReactNode, onClick?: () => void }) => <button type="button" onClick={onClick}>{children}</button>,+ AlertDialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ AlertDialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}))++vi.mock('../model-auth/hooks', () => ({+ useCredentialData: () => ({+ isLoading: false,+ credentialData: {+ credentials: {},+ available_credentials: mockAvailableCredentials,+ },+ }),+ useAuth: () => ({+ handleSaveCredential: vi.fn(),+ handleConfirmDelete: mockHandleConfirmDelete,+ deleteCredentialId: mockDeleteCredentialId,+ closeConfirmDelete: mockCloseConfirmDelete,+ openConfirmDelete: vi.fn(),+ doingAction: false,+ handleActiveCredential: vi.fn(),+ }),+ useModelFormSchemas: () => ({+ formSchemas: [],+ formValues: {},+ modelNameAndTypeFormSchemas: [],+ modelNameAndTypeFormValues: {},+ }),+}))++vi.mock('@/context/app-context', () => ({+ useAppContext: () => ({+ isCurrentWorkspaceManager: true,+ }),+}))++vi.mock('@/hooks/use-i18n', () => ({+ useRenderI18nObject: () => (value: Record<string, string>) => value[mockLanguage] || value.en_US,+}))++vi.mock('../hooks', () => ({+ useLanguage: () => mockLanguage,+}))++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'openai',+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ help: {+ title: { en_US: 'Help', zh_Hans: '帮助' },+ url: { en_US: 'https://example.com', zh_Hans: 'https://example.cn' },+ },+ icon_small: { en_US: '', zh_Hans: '' },+ supported_model_types: [],+ configurate_methods: [],+ provider_credential_schema: { credential_form_schemas: [] },+ model_credential_schema: {+ model: { label: { en_US: 'Model', zh_Hans: '模型' }, placeholder: { en_US: 'Select', zh_Hans: '选择' } },+ credential_form_schemas: [],+ },+ custom_configuration: {+ status: 'active',+ available_credentials: [],+ custom_models: [],+ can_added_models: [],+ },+ system_configuration: {+ enabled: true,+ current_quota_type: 'trial',+ quota_configurations: [],+ },+ allow_custom_token: true,+ ...overrides,+} as unknown as ModelProvider)++describe('ModelModal dialog branches', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockLanguage = 'en_US'+ latestDialogOnOpenChange = undefined+ latestAlertDialogOnOpenChange = undefined+ mockAvailableCredentials = []+ mockDeleteCredentialId = null+ })++ it('should only cancel when the dialog reports it has closed', () => {+ const onCancel = vi.fn()+ render(+ <ModelModal+ provider={createProvider()}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ onCancel={onCancel}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ act(() => {+ latestDialogOnOpenChange?.(true)+ latestDialogOnOpenChange?.(false)+ })++ expect(onCancel).toHaveBeenCalledTimes(1)+ })++ it('should only close the confirm dialog when the alert dialog closes', () => {+ mockDeleteCredentialId = 'cred-1'++ render(+ <ModelModal+ provider={createProvider()}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ onCancel={vi.fn()}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ act(() => {+ latestAlertDialogOnOpenChange?.(true)+ latestAlertDialogOnOpenChange?.(false)+ })++ expect(mockCloseConfirmDelete).toHaveBeenCalledTimes(1)+ })++ it('should pass an empty credential list to the selector when no credentials are available', () => {+ mockAvailableCredentials = undefined++ render(+ <ModelModal+ provider={createProvider()}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ mode={ModelModalModeEnum.addCustomModelToModelList}+ onCancel={vi.fn()}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ expect(screen.getByText('credentials:0')).toBeInTheDocument()+ })++ it('should hide the help link when provider help is missing', () => {+ render(+ <ModelModal+ provider={createProvider({ help: undefined })}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ onCancel={vi.fn()}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ expect(screen.queryByRole('link', { name: 'Help' })).not.toBeInTheDocument()+ })++ it('should prevent navigation when help text exists without a help url', () => {+ mockLanguage = 'zh_Hans'++ render(+ <ModelModal+ provider={createProvider({+ help: {+ title: { en_US: 'English Help' },+ url: '' as unknown as ModelProvider['help']['url'],+ } as ModelProvider['help'],+ })}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ onCancel={vi.fn()}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ const link = screen.getByText('English Help').closest('a')+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true })+ expect(link).not.toBeNull()+ link!.dispatchEvent(clickEvent)++ expect(clickEvent.defaultPrevented).toBe(true)+ })++ it('should fall back to localized and english help urls when titles are missing', () => {+ mockLanguage = 'zh_Hans'+ const { rerender } = render(+ <ModelModal+ provider={createProvider({+ help: {+ url: { zh_Hans: 'https://example.cn', en_US: 'https://example.com' },+ } as ModelProvider['help'],+ })}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ onCancel={vi.fn()}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ expect(screen.getByRole('link', { name: 'https://example.cn' })).toHaveAttribute('href', 'https://example.cn')++ rerender(+ <ModelModal+ provider={createProvider({+ help: {+ url: { en_US: 'https://example.com' },+ } as ModelProvider['help'],+ })}+ configurateMethod={ConfigurationMethodEnum.predefinedModel}+ onCancel={vi.fn()}+ onSave={vi.fn()}+ onRemove={vi.fn()}+ />,+ )++ const link = screen.getByRole('link', { name: 'https://example.com' })+ const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true })+ link.dispatchEvent(clickEvent)++ expect(link).toHaveAttribute('href', 'https://example.com')+ expect(clickEvent.defaultPrevented).toBe(false)+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsxindex ab6f23c8312..326b3b2f435 100644--- a/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-modal/index.tsx@@ -9,11 +9,9 @@ import type {FormRefObject,FormSchema,} from '@/app/components/base/form/types'-import { RiCloseLine } from '@remixicon/react'import {memo,useCallback,- useEffect,useMemo,useRef,useState,@@ -21,15 +19,23 @@ import {import { useTranslation } from 'react-i18next'import Badge from '@/app/components/base/badge'import Button from '@/app/components/base/button'-import Confirm from '@/app/components/base/confirm'import AuthForm from '@/app/components/base/form/form-scenarios/auth'import { LinkExternal02 } from '@/app/components/base/icons/src/vender/line/general'import { Lock01 } from '@/app/components/base/icons/src/vender/solid/security'import Loading from '@/app/components/base/loading'import {- PortalToFollowElem,- PortalToFollowElemContent,-} from '@/app/components/base/portal-to-follow-elem'+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogTitle,+} from '@/app/components/base/ui/alert-dialog'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+} from '@/app/components/base/ui/dialog'import {useAuth,useCredentialData,@@ -197,7 +203,7 @@ const ModelModal: FC<ModelModalProps> = ({}return (- <div className="title-2xl-semi-bold text-text-primary">+ <div className="text-text-primary title-2xl-semi-bold">{label}</div>)@@ -206,7 +212,7 @@ const ModelModal: FC<ModelModalProps> = ({const modalDesc = useMemo(() => {if (providerFormSchemaPredefined) {return (- <div className="system-xs-regular mt-1 text-text-tertiary">+ <div className="mt-1 text-text-tertiary system-xs-regular">{t('modelProvider.auth.apiKeyModal.desc', { ns: 'common' })}</div>)@@ -223,7 +229,7 @@ const ModelModal: FC<ModelModalProps> = ({className="mr-2 h-4 w-4 shrink-0"provider={provider}/>- <div className="system-md-regular mr-1 text-text-secondary">{renderI18nObject(provider.label)}</div>+ <div className="mr-1 text-text-secondary system-md-regular">{renderI18nObject(provider.label)}</div></div>)}@@ -235,7 +241,7 @@ const ModelModal: FC<ModelModalProps> = ({provider={provider}modelName={model.model}/>- <div className="system-md-regular mr-1 text-text-secondary">{model.model}</div>+ <div className="mr-1 text-text-secondary system-md-regular">{model.model}</div><Badge>{model.model_type}</Badge></div>)@@ -275,174 +281,171 @@ const ModelModal: FC<ModelModalProps> = ({}, [])const notAllowCustomCredential = provider.allow_custom_token === false- useEffect(() => {- const handleKeyDown = (event: KeyboardEvent) => {- if (event.key === 'Escape') {- event.stopPropagation()- onCancel()- }- }-- document.addEventListener('keydown', handleKeyDown, true)- return () => {- document.removeEventListener('keydown', handleKeyDown, true)- }+ const handleOpenChange = useCallback((open: boolean) => {+ if (!open)+ onCancel()}, [onCancel])+ const handleConfirmOpenChange = useCallback((open: boolean) => {+ if (!open)+ closeConfirmDelete()+ }, [closeConfirmDelete])+return (- <PortalToFollowElem open>- <PortalToFollowElemContent className="z-[60] h-full w-full">- <div className="fixed inset-0 flex items-center justify-center bg-black/[.25]">- <div className="relative w-[640px] rounded-2xl bg-components-panel-bg shadow-xl">- <div- className="absolute right-5 top-5 flex h-8 w-8 cursor-pointer items-center justify-center"- onClick={onCancel}- >- <RiCloseLine className="h-4 w-4 text-text-tertiary" />- </div>- <div className="p-6 pb-3">- {modalTitle}- {modalDesc}- {modalModel}- </div>- <div className="max-h-[calc(100vh-320px)] overflow-y-auto px-6 py-3">- {- mode === ModelModalModeEnum.configCustomModel && (- <AuthForm- formSchemas={modelNameAndTypeFormSchemas.map((formSchema) => {- return {- ...formSchema,- name: formSchema.variable,- }- }) as FormSchema[]}- defaultValues={modelNameAndTypeFormValues}- inputClassName="justify-start"- ref={formRef1}- onChange={handleModelNameAndTypeChange}- />- )- }- {- mode === ModelModalModeEnum.addCustomModelToModelList && (- <CredentialSelector- credentials={available_credentials || []}- onSelect={setSelectedCredential}- selectedCredential={selectedCredential}- disabled={isLoading}- notAllowAddNewCredential={notAllowCustomCredential}- />- )- }- {- showCredentialLabel && (- <div className="system-xs-medium-uppercase mb-3 mt-6 flex items-center text-text-tertiary">- {t('modelProvider.auth.modelCredential', { ns: 'common' })}- <div className="ml-2 h-px grow bg-gradient-to-r from-divider-regular to-background-gradient-mask-transparent" />- </div>- )- }- {- isLoading && (- <div className="mt-3 flex items-center justify-center">- <Loading />- </div>- )- }- {- !isLoading- && showCredentialForm- && (- <AuthForm- formSchemas={formSchemas.map((formSchema) => {- return {- ...formSchema,- name: formSchema.variable,- showRadioUI: formSchema.type === FormTypeEnum.radio,- }- }) as FormSchema[]}- defaultValues={formValues}- inputClassName="justify-start"- ref={formRef2}- />+ <Dialog open onOpenChange={handleOpenChange}>+ <DialogContent+ backdropProps={{ forceRender: true }}+ className="w-[640px] max-w-[640px] overflow-hidden p-0"+ >+ <DialogCloseButton className="right-5 top-5 h-8 w-8" />+ <div className="p-6 pb-3">+ {modalTitle}+ {modalDesc}+ {modalModel}+ </div>+ <div className="max-h-[calc(100vh-320px)] overflow-y-auto px-6 py-3">+ {+ mode === ModelModalModeEnum.configCustomModel && (+ <AuthForm+ formSchemas={modelNameAndTypeFormSchemas.map((formSchema) => {+ return {+ ...formSchema,+ name: formSchema.variable,+ }+ }) as FormSchema[]}+ defaultValues={modelNameAndTypeFormValues}+ inputClassName="justify-start"+ ref={formRef1}+ onChange={handleModelNameAndTypeChange}+ />+ )+ }+ {+ mode === ModelModalModeEnum.addCustomModelToModelList && (+ <CredentialSelector+ credentials={available_credentials || []}+ onSelect={setSelectedCredential}+ selectedCredential={selectedCredential}+ disabled={isLoading}+ notAllowAddNewCredential={notAllowCustomCredential}+ />+ )+ }+ {+ showCredentialLabel && (+ <div className="mb-3 mt-6 flex items-center text-text-tertiary system-xs-medium-uppercase">+ {t('modelProvider.auth.modelCredential', { ns: 'common' })}+ <div className="ml-2 h-px grow bg-gradient-to-r from-divider-regular to-background-gradient-mask-transparent" />+ </div>+ )+ }+ {+ isLoading && (+ <div className="mt-3 flex items-center justify-center">+ <Loading />+ </div>+ )+ }+ {+ !isLoading+ && showCredentialForm+ && (+ <AuthForm+ formSchemas={formSchemas.map((formSchema) => {+ return {+ ...formSchema,+ name: formSchema.variable,+ showRadioUI: formSchema.type === FormTypeEnum.radio,+ }+ }) as FormSchema[]}+ defaultValues={formValues}+ inputClassName="justify-start"+ ref={formRef2}+ />+ )+ }+ </div>+ <div className="flex justify-between p-6 pt-5">+ {+ (provider.help && (provider.help.title || provider.help.url))+ ? (+ <a+ href={provider.help?.url[language] || provider.help?.url.en_US}+ target="_blank"+ rel="noopener noreferrer"+ className="mt-2 inline-block align-middle text-text-accent system-xs-regular"+ onClick={e => !provider.help.url && e.preventDefault()}+ >+ {provider.help.title?.[language] || provider.help.url[language] || provider.help.title?.en_US || provider.help.url.en_US}+ <LinkExternal02 className="ml-1 mt-[-2px] inline-block h-3 w-3" />+ </a>)- }- </div>- <div className="flex justify-between p-6 pt-5">- {- (provider.help && (provider.help.title || provider.help.url))- ? (- <a- href={provider.help?.url[language] || provider.help?.url.en_US}- target="_blank"- rel="noopener noreferrer"- className="system-xs-regular mt-2 inline-block align-middle text-text-accent"- onClick={e => !provider.help.url && e.preventDefault()}- >- {provider.help.title?.[language] || provider.help.url[language] || provider.help.title?.en_US || provider.help.url.en_US}- <LinkExternal02 className="ml-1 mt-[-2px] inline-block h-3 w-3" />- </a>- )- : <div />- }- <div className="ml-2 flex items-center justify-end space-x-2">- {- isEditMode && (- <Button- variant="warning"- onClick={() => openConfirmDelete(credential, model)}- >- {t('operation.remove', { ns: 'common' })}- </Button>- )- }- <Button- onClick={onCancel}- >- {t('operation.cancel', { ns: 'common' })}- </Button>+ : <div />+ }+ <div className="ml-2 flex items-center justify-end space-x-2">+ {+ isEditMode && (<Button- variant="primary"- onClick={handleSave}- disabled={isLoading || doingAction}+ variant="warning"+ onClick={() => openConfirmDelete(credential, model)}>- {saveButtonText}+ {t('operation.remove', { ns: 'common' })}</Button>- </div>- </div>- {- (mode === ModelModalModeEnum.configCustomModel || mode === ModelModalModeEnum.configProviderCredential) && (- <div className="border-t-[0.5px] border-t-divider-regular">- <div className="flex items-center justify-center rounded-b-2xl bg-background-section-burn py-3 text-xs text-text-tertiary">- <Lock01 className="mr-1 h-3 w-3 text-text-tertiary" />- {t('modelProvider.encrypted.front', { ns: 'common' })}- <a- className="mx-1 text-text-accent"- target="_blank"- rel="noopener noreferrer"- href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html"- >- PKCS1_OAEP- </a>- {t('modelProvider.encrypted.back', { ns: 'common' })}- </div>- </div>)}+ <Button+ onClick={onCancel}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>+ <Button+ variant="primary"+ onClick={handleSave}+ disabled={isLoading || doingAction}+ >+ {saveButtonText}+ </Button></div>- {- deleteCredentialId && (- <Confirm- isShow- title={t('modelProvider.confirmDelete', { ns: 'common' })}- isDisabled={doingAction}- onCancel={closeConfirmDelete}- onConfirm={handleDeleteCredential}- />- )- }</div>- </PortalToFollowElemContent>- </PortalToFollowElem>+ {+ (mode === ModelModalModeEnum.configCustomModel || mode === ModelModalModeEnum.configProviderCredential) && (+ <div className="border-t-[0.5px] border-t-divider-regular">+ <div className="flex items-center justify-center rounded-b-2xl bg-background-section-burn py-3 text-xs text-text-tertiary">+ <Lock01 className="mr-1 h-3 w-3 text-text-tertiary" />+ {t('modelProvider.encrypted.front', { ns: 'common' })}+ <a+ className="mx-1 text-text-accent"+ target="_blank"+ rel="noopener noreferrer"+ href="https://pycryptodome.readthedocs.io/en/latest/src/cipher/oaep.html"+ >+ PKCS1_OAEP+ </a>+ {t('modelProvider.encrypted.back', { ns: 'common' })}+ </div>+ </div>+ )+ }+ </DialogContent>+ <AlertDialog open={!!deleteCredentialId} onOpenChange={handleConfirmOpenChange}>+ <AlertDialogContent backdropProps={{ forceRender: true }}>+ <div className="flex flex-col gap-2 p-6 pb-4">+ <AlertDialogTitle className="text-text-primary title-2xl-semi-bold">+ {t('modelProvider.confirmDelete', { ns: 'common' })}+ </AlertDialogTitle>+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton>{t('operation.cancel', { ns: 'common' })}</AlertDialogCancelButton>+ <AlertDialogConfirmButton+ disabled={doingAction}+ onClick={handleDeleteCredential}+ >+ {t('operation.confirm', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ </Dialog>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-name/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-name/index.tsxindex bf6c10aeeb0..3186e28e2e7 100644--- a/web/app/components/header/account-setting/model-provider-page/model-name/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-name/index.tsx@@ -39,7 +39,7 @@ const ModelName: FC<ModelNameProps> = ({if (!modelItem)return nullreturn (- <div className={cn('system-sm-regular flex items-center gap-0.5 overflow-hidden truncate text-ellipsis text-components-input-text-filled', className)}>+ <div className={cn('flex items-center gap-0.5 overflow-hidden truncate text-ellipsis text-components-input-text-filled system-sm-regular', className)}><divclassName="truncate"title={modelItem.label[language] || modelItem.label.en_US}diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsxindex f38e8f8c174..496058bf9b2 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/index.spec.tsx@@ -1,4 +1,4 @@-import { fireEvent, render, screen } from '@testing-library/react'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import ModelParameterModal from '../index'let isAPIKeySet = true@@ -49,7 +49,7 @@ vi.mock('@/service/use-common', () => ({data: {data: parameterRules,},- isPending: isRulesLoading,+ isLoading: isRulesLoading,}),}))@@ -77,9 +77,10 @@ vi.mock('../parameter-item', () => ({}))vi.mock('../../model-selector', () => ({- default: ({ onSelect }: { onSelect: (value: { provider: string, model: string }) => void }) => (+ default: ({ onHide, onSelect }: { onHide: () => void, onSelect: (value: { provider: string, model: string }) => void }) => (<div data-testid="model-selector"><button onClick={() => onSelect({ provider: 'openai', model: 'gpt-4.1' })}>Select GPT-4.1</button>+ <button onClick={onHide}>hide</button></div>),}))@@ -91,7 +92,7 @@ vi.mock('../presets-parameter', () => ({}))vi.mock('../trigger', () => ({- default: () => <button>Open Settings</button>,+ default: () => <button type="button">Open Settings</button>,}))vi.mock('@/config', async (importOriginal) => {@@ -231,4 +232,67 @@ describe('ModelParameterModal', () => {expect(screen.queryByTestId('param-temperature')).not.toBeInTheDocument()expect(screen.getByTestId('model-selector')).toBeInTheDocument()})++ it('should support custom triggers, workflow mode, and missing default model values', async () => {+ render(+ <ModelParameterModal+ {...defaultProps}+ provider=""+ modelId=""+ isInWorkflow+ renderTrigger={({ open }) => <span>{open ? 'Custom Open' : 'Custom Closed'}</span>}+ />,+ )++ fireEvent.click(screen.getByText('Custom Closed'))++ expect(screen.getByText('Custom Open')).toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toBeInTheDocument()++ fireEvent.click(screen.getByText('hide'))++ await waitFor(() => {+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()+ })+ })++ it('should append the stop parameter in advanced mode and show the single-model debug label', () => {+ render(+ <ModelParameterModal+ {...defaultProps}+ isAdvancedMode+ debugWithMultipleModel+ />,+ )++ fireEvent.click(screen.getByText('Open Settings'))++ expect(screen.getByTestId('param-stop')).toBeInTheDocument()+ expect(screen.getByText(/debugAsSingleModel/i)).toBeInTheDocument()+ })++ it('should render the empty loading fallback when rules resolve to an empty list', () => {+ parameterRules = []+ isRulesLoading = true++ render(<ModelParameterModal {...defaultProps} />)+ fireEvent.click(screen.getByText('Open Settings'))++ expect(screen.getByRole('status')).toBeInTheDocument()+ expect(screen.queryByTestId('param-temperature')).not.toBeInTheDocument()+ })++ it('should support custom trigger placement outside workflow mode', () => {+ render(+ <ModelParameterModal+ {...defaultProps}+ renderTrigger={({ open }) => <span>{open ? 'Popup Open' : 'Popup Closed'}</span>}+ />,+ )++ fireEvent.click(screen.getByText('Popup Closed'))++ expect(screen.getByText('Popup Open')).toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toBeInTheDocument()+ })})diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsxindex ecf50a8aad3..5aec68c0987 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/parameter-item.spec.tsx@@ -109,7 +109,7 @@ describe('ParameterItem', () => {it('should render select for string with options', () => {render(<ParameterItem parameterRule={createRule({ type: 'string', options: ['a', 'b'] })} value="a" />)- // SimpleSelect renders an element with text 'a'+ // Select renders the selected value in the triggerexpect(screen.getByText('a')).toBeInTheDocument()})diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/presets-parameter.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/presets-parameter.spec.tsxindex 14cff933e2e..33437afbf72 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/presets-parameter.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/presets-parameter.spec.tsx@@ -18,13 +18,12 @@ describe('PresetsParameter', () => {expect(onSelect).toHaveBeenCalledWith(1)})- // open=true: trigger has bg-state-base-hover class- it('should apply hover background class when open is true', () => {+ it('should mark trigger as open when dropdown is expanded', () => {render(<PresetsParameter onSelect={vi.fn()} />)fireEvent.click(screen.getByRole('button', { name: /common\.modelProvider\.loadPresets/i }))const button = screen.getByRole('button', { name: /common\.modelProvider\.loadPresets/i })- expect(button).toHaveClass('bg-state-base-hover')+ expect(button).toHaveAttribute('data-popup-open')})// Tone map branch 2: Balanced → Scales02 icondiff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/trigger.spec.tsxindex 2fe906c17f6..dab87cbd16a 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/trigger.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/__tests__/trigger.spec.tsx@@ -1,140 +1,322 @@import type { ComponentProps } from 'react'import { render, screen } from '@testing-library/react'-import userEvent from '@testing-library/user-event'import Trigger from '../trigger'+const mockUseCredentialPanelState = vi.fn()+vi.mock('../../hooks', () => ({useLanguage: () => 'en_US',}))vi.mock('@/context/provider-context', () => ({useProviderContext: () => ({- modelProviders: [{ provider: 'openai', label: { en_US: 'OpenAI' } }],+ modelProviders: [{+ provider: 'openai',+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ }],}),}))+vi.mock('../../provider-added-card/use-credential-panel-state', () => ({+ useCredentialPanelState: () => mockUseCredentialPanelState(),+}))+vi.mock('../../model-icon', () => ({default: () => <div data-testid="model-icon">Icon</div>,}))vi.mock('../../model-name', () => ({- default: ({ modelItem }: { modelItem: { model: string } }) => <div>{modelItem.model}</div>,+ default: ({+ modelItem,+ showMode,+ showFeatures,+ }: {+ modelItem: { model: string }+ showMode?: boolean+ showFeatures?: boolean+ }) => (+ <div>+ <span>{modelItem.model}</span>+ {showMode && <span data-testid="model-name-mode">mode</span>}+ {showFeatures && <span data-testid="model-name-features">features</span>}+ </div>+ ),}))+const activeCredentialState = {+ variant: 'api-active' as const,+ supportsCredits: true,+ isCreditsExhausted: false,+ priority: 'apiKey' as const,+ showPrioritySwitcher: true,+ hasCredentials: true,+ credentialName: 'Primary Key',+ credits: 10,+}+describe('Trigger', () => {- const currentProvider = { provider: 'openai', label: { en_US: 'OpenAI' } } as unknown as ComponentProps<typeof Trigger>['currentProvider']- const currentModel = { model: 'gpt-4' } as unknown as ComponentProps<typeof Trigger>['currentModel']+ const currentProvider = {+ provider: 'openai',+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ } as unknown as ComponentProps<typeof Trigger>['currentProvider']++ const currentModel = {+ model: 'gpt-4',+ status: 'active',+ } as unknown as ComponentProps<typeof Trigger>['currentModel']beforeEach(() => {vi.clearAllMocks()+ mockUseCredentialPanelState.mockReturnValue(activeCredentialState)})- it('should render initialized state', () => {- render(- <Trigger- currentProvider={currentProvider}- currentModel={currentModel}- />,- )- expect(screen.getByText('gpt-4')).toBeInTheDocument()- expect(screen.getByTestId('model-icon')).toBeInTheDocument()- })+ describe('Rendering', () => {+ it('should render active state with model features in non-workflow mode', () => {+ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )- it('should render fallback model id when current model is missing', () => {- render(- <Trigger- modelId="gpt-4"- providerName="openai"- />,- )- expect(screen.getByText('gpt-4')).toBeInTheDocument()- })+ expect(screen.getByText('gpt-4')).toBeInTheDocument()+ expect(screen.getByTestId('model-icon')).toBeInTheDocument()+ expect(screen.getByTestId('model-name-mode')).toBeInTheDocument()+ expect(screen.getByTestId('model-name-features')).toBeInTheDocument()+ })- // isInWorkflow=true: workflow border class + RiArrowDownSLine arrow- it('should render workflow styles when isInWorkflow is true', () => {- // Act- const { container } = render(- <Trigger- currentProvider={currentProvider}- currentModel={currentModel}- isInWorkflow- />,- )-- // Assert- expect(container.firstChild).toHaveClass('border-workflow-block-parma-bg')- expect(container.firstChild).toHaveClass('bg-workflow-block-parma-bg')- expect(container.querySelectorAll('svg').length).toBe(2)- })+ it('should render fallback model id when current model is missing', () => {+ render(+ <Trigger+ modelId="gpt-4"+ providerName="openai"+ />,+ )- // disabled=true + hasDeprecated=true: AlertTriangle + deprecated tooltip- it('should show deprecated warning when disabled with hasDeprecated', () => {- // Act- render(- <Trigger- currentProvider={currentProvider}- currentModel={currentModel}- disabled- hasDeprecated- />,- )-- // Assert - AlertTriangle renders with warning color- const warningIcon = document.querySelector('.text-\\[\\#F79009\\]')- expect(warningIcon).toBeInTheDocument()- })+ expect(screen.getByText('gpt-4')).toBeInTheDocument()+ })++ it('should render split layout with workflow styles when workflow mode is enabled', () => {+ const { container } = render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ isInWorkflow+ providerName="openai"+ modelId="gpt-4"+ />,+ )- // disabled=true + modelDisabled=true: status text tooltip- it('should show model status tooltip when disabled with modelDisabled', () => {- // Act- render(- <Trigger- currentProvider={currentProvider}- currentModel={{ ...currentModel, status: 'no-configure' } as unknown as typeof currentModel}- disabled- modelDisabled- />,- )-- // Assert - AlertTriangle warning icon should be present- const warningIcon = document.querySelector('.text-\\[\\#F79009\\]')- expect(warningIcon).toBeInTheDocument()+ const leftPanel = container.querySelector('.rounded-l-lg')+ expect(leftPanel).toBeInTheDocument()+ expect(leftPanel).toHaveClass('border-workflow-block-parma-bg')+ const rightPanel = container.querySelector('.rounded-r-lg')+ expect(rightPanel).toBeInTheDocument()+ expect(rightPanel).toHaveClass('border-workflow-block-parma-bg')+ })++ it('should render empty state when no provider or model is selected', () => {+ render(<Trigger isInWorkflow />)++ expect(screen.getByText('workflow:errorMsg.configureModel')).toBeInTheDocument()+ })++ it('should render non-workflow empty state with warning border', () => {+ const { container } = render(<Trigger />)++ expect(screen.getByText('workflow:errorMsg.configureModel')).toBeInTheDocument()+ expect(container.firstChild).toHaveClass('border-text-warning')+ })})- it('should render empty tooltip content when disabled without deprecated or modelDisabled', async () => {- const user = userEvent.setup()- const { container } = render(- <Trigger- currentProvider={currentProvider}- currentModel={currentModel}- disabled- hasDeprecated={false}- modelDisabled={false}- />,- )- const warningIcon = document.querySelector('.text-\\[\\#F79009\\]')- expect(warningIcon).toBeInTheDocument()- const trigger = container.querySelector('[data-state]')- expect(trigger).toBeInTheDocument()- await user.hover(trigger as HTMLElement)- const tooltip = screen.queryByRole('tooltip')- if (tooltip)- expect(tooltip).toBeEmptyDOMElement()- expect(screen.queryByText('modelProvider.deprecated')).not.toBeInTheDocument()- expect(screen.queryByText('No Configure')).not.toBeInTheDocument()+ describe('Status badges', () => {+ it('should render credits exhausted badge in non-workflow mode', () => {+ mockUseCredentialPanelState.mockReturnValue({+ ...activeCredentialState,+ variant: 'credits-exhausted',+ isCreditsExhausted: true,+ priority: 'credits',+ })++ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.creditsExhausted')).toBeInTheDocument()+ expect(screen.queryByTestId('model-name-mode')).not.toBeInTheDocument()+ expect(screen.queryByTestId('model-name-features')).not.toBeInTheDocument()+ })++ it('should render api unavailable badge in non-workflow mode', () => {+ mockUseCredentialPanelState.mockReturnValue({+ ...activeCredentialState,+ variant: 'api-unavailable',+ })++ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.apiKeyUnavailable')).toBeInTheDocument()+ })++ it('should render credits exhausted badge in workflow mode', () => {+ mockUseCredentialPanelState.mockReturnValue({+ ...activeCredentialState,+ variant: 'credits-exhausted',+ isCreditsExhausted: true,+ priority: 'credits',+ })++ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ isInWorkflow+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.creditsExhausted')).toBeInTheDocument()+ })++ it('should render api unavailable badge in workflow mode', () => {+ mockUseCredentialPanelState.mockReturnValue({+ ...activeCredentialState,+ variant: 'api-unavailable',+ })++ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ isInWorkflow+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.apiKeyUnavailable')).toBeInTheDocument()+ })++ it('should render incompatible badge when model is deprecated (currentModel missing)', () => {+ render(+ <Trigger+ currentProvider={currentProvider}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.incompatible')).toBeInTheDocument()+ })++ it('should render credits exhausted badge when model is missing and AI credits are exhausted without api key', () => {+ mockUseCredentialPanelState.mockReturnValue({+ ...activeCredentialState,+ variant: 'no-usage',+ priority: 'apiKey',+ hasCredentials: false,+ isCreditsExhausted: true,+ credentialName: undefined,+ })++ render(+ <Trigger+ currentProvider={currentProvider}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.creditsExhausted')).toBeInTheDocument()+ })++ it('should render configure required badge when model status is no-configure', () => {+ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={{ ...currentModel, status: 'no-configure' } as typeof currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.configureRequired')).toBeInTheDocument()+ })++ it('should render disabled badge when model status is disabled', () => {+ render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={{ ...currentModel, status: 'disabled' } as typeof currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.disabled')).toBeInTheDocument()+ })++ it('should render incompatible badge when provider plugin is not installed', () => {+ render(+ <Trigger+ modelId="gpt-4"+ providerName="unknown-provider"+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.incompatible')).toBeInTheDocument()+ })})- // providerName not matching any provider: find() returns undefined- it('should render without crashing when providerName does not match any provider', () => {- // Act- render(- <Trigger- modelId="gpt-4"- providerName="unknown-provider"- />,- )-- // Assert- expect(screen.getByText('gpt-4')).toBeInTheDocument()+ describe('Split layout', () => {+ it('should use split layout with settings button in non-workflow mode', () => {+ const { container } = render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ const splitContainer = container.querySelector('.rounded-l-lg')+ expect(splitContainer).toBeInTheDocument()+ const settingsButton = container.querySelector('.rounded-r-lg')+ expect(settingsButton).toBeInTheDocument()+ })++ it('should use split layout for error states in non-workflow mode', () => {+ mockUseCredentialPanelState.mockReturnValue({+ ...activeCredentialState,+ variant: 'api-unavailable',+ })++ const { container } = render(+ <Trigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName="openai"+ modelId="gpt-4"+ />,+ )++ const splitContainer = container.querySelector('.rounded-l-lg')+ expect(splitContainer).toBeInTheDocument()+ })})})diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/derive-trigger-status.spec.ts b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/derive-trigger-status.spec.tsnew file mode 100644index 00000000000..828895d35a4--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/derive-trigger-status.spec.ts@@ -0,0 +1,112 @@+import type { ModelItem, ModelProvider } from '../declarations'+import type { CredentialPanelState } from '../provider-added-card/use-credential-panel-state'+import { ModelStatusEnum } from '../declarations'+import { deriveTriggerStatus } from './derive-trigger-status'++const baseCredentialState: CredentialPanelState = {+ variant: 'api-active',+ priority: 'apiKey',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: true,+ isCreditsExhausted: false,+ credentialName: 'Primary Key',+ credits: 10,+}++const mockProvider = { provider: 'openai' } as ModelProvider+const mockModel = { model: 'gpt-4', status: ModelStatusEnum.active } as ModelItem++describe('deriveTriggerStatus', () => {+ it('returns empty when modelId is missing', () => {+ expect(deriveTriggerStatus(undefined, 'openai', mockProvider, mockModel, baseCredentialState)).toBe('empty')+ })++ it('returns empty when providerName is missing', () => {+ expect(deriveTriggerStatus('gpt-4', undefined, mockProvider, mockModel, baseCredentialState)).toBe('empty')+ })++ it('returns incompatible when provider plugin is not installed', () => {+ expect(deriveTriggerStatus('gpt-4', 'openai', undefined, mockModel, baseCredentialState)).toBe('incompatible')+ })++ it('returns credits-exhausted when credits priority and exhausted', () => {+ const state: CredentialPanelState = {+ ...baseCredentialState,+ priority: 'credits',+ isCreditsExhausted: true,+ }+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, mockModel, state)).toBe('credits-exhausted')+ })++ it('returns active when credits priority but not exhausted', () => {+ const state: CredentialPanelState = {+ ...baseCredentialState,+ priority: 'credits',+ isCreditsExhausted: false,+ }+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, mockModel, state)).toBe('active')+ })++ it('returns api-key-unavailable when variant is api-unavailable', () => {+ const state: CredentialPanelState = {+ ...baseCredentialState,+ variant: 'api-unavailable',+ }+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, mockModel, state)).toBe('api-key-unavailable')+ })++ it('returns incompatible when currentModel is missing (deprecated)', () => {+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, undefined, baseCredentialState)).toBe('incompatible')+ })++ it('returns credits-exhausted when currentModel is missing and AI credits are exhausted without api key', () => {+ const state: CredentialPanelState = {+ ...baseCredentialState,+ priority: 'apiKey',+ hasCredentials: false,+ isCreditsExhausted: true,+ credentialName: undefined,+ }+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, undefined, state)).toBe('credits-exhausted')+ })++ it('returns configure-required when model status is no-configure', () => {+ const model = { ...mockModel, status: ModelStatusEnum.noConfigure } as ModelItem+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, model, baseCredentialState)).toBe('configure-required')+ })++ it('returns incompatible when model status is noPermission', () => {+ const model = { ...mockModel, status: ModelStatusEnum.noPermission } as ModelItem+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, model, baseCredentialState)).toBe('incompatible')+ })++ it('returns disabled when model status is disabled', () => {+ const model = { ...mockModel, status: ModelStatusEnum.disabled } as ModelItem+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, model, baseCredentialState)).toBe('disabled')+ })++ it('returns active when all conditions are satisfied', () => {+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, mockModel, baseCredentialState)).toBe('active')+ })++ it('prioritises credits-exhausted over api-unavailable', () => {+ const state: CredentialPanelState = {+ ...baseCredentialState,+ priority: 'credits',+ isCreditsExhausted: true,+ variant: 'api-unavailable',+ }+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, mockModel, state)).toBe('credits-exhausted')+ })++ it('does not return credits-exhausted when supportsCredits is false', () => {+ const state: CredentialPanelState = {+ ...baseCredentialState,+ priority: 'credits',+ isCreditsExhausted: true,+ supportsCredits: false,+ }+ expect(deriveTriggerStatus('gpt-4', 'openai', mockProvider, mockModel, state)).toBe('active')+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/derive-trigger-status.ts b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/derive-trigger-status.tsnew file mode 100644index 00000000000..8492107eabb--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/derive-trigger-status.ts@@ -0,0 +1,12 @@+import type { DerivedModelStatus } from '../derive-model-status'+import {+ DERIVED_MODEL_STATUS_BADGE_I18N,+ DERIVED_MODEL_STATUS_TOOLTIP_I18N,+ deriveModelStatus,+} from '../derive-model-status'++export type TriggerStatus = DerivedModelStatus++export const deriveTriggerStatus = deriveModelStatus+export const TRIGGER_STATUS_BADGE_I18N = DERIVED_MODEL_STATUS_BADGE_I18N+export const TRIGGER_STATUS_TOOLTIP_I18N = DERIVED_MODEL_STATUS_TOOLTIP_I18Ndiff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsxindex 86280f3fb0e..fc10536de89 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx@@ -9,20 +9,19 @@ import type {} from '../declarations'import type { ParameterValue } from './parameter-item'import type { TriggerProps } from './trigger'-import { useMemo, useState } from 'react'+import { useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { ArrowNarrowLeft } from '@/app/components/base/icons/src/vender/line/arrows'import Loading from '@/app/components/base/loading'import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'+ Popover,+ PopoverClose,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'import { PROVIDER_WITH_PRESET_TONE, STOP_PARAMETER_RULE, TONE_LIST } from '@/config'-import { useProviderContext } from '@/context/provider-context'import { useModelParameterRules } from '@/service/use-common'import { cn } from '@/utils/classnames'-import { ModelStatusEnum } from '../declarations'import {useTextGenerationCurrentProviderAndModelAndModelList,} from '../hooks'@@ -66,9 +65,9 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({isInWorkflow,}) => {const { t } = useTranslation()- const { isAPIKeySet } = useProviderContext()const [open, setOpen] = useState(false)- const { data: parameterRulesData, isPending: isLoading } = useModelParameterRules(provider, modelId)+ const settingsIconRef = useRef<HTMLDivElement>(null)+ const { data: parameterRulesData, isLoading } = useModelParameterRules(provider, modelId)const {currentProvider,currentModel,@@ -77,10 +76,6 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({{ provider, model: modelId },)- const hasDeprecated = !currentProvider || !currentModel- const modelDisabled = currentModel?.status !== ModelStatusEnum.active- const disabled = !isAPIKeySet || hasDeprecated || modelDisabled-const parameterRules: ModelParameterRule[] = useMemo(() => {return parameterRulesData?.data || []}, [parameterRulesData])@@ -129,117 +124,118 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({}return (- <PortalToFollowElem+ <Popoveropen={open}- onOpenChange={setOpen}- placement={isInWorkflow ? 'left' : 'bottom-end'}- offset={4}+ onOpenChange={(newOpen) => {+ if (readonly)+ return+ setOpen(newOpen)+ }}>- <div className="relative">- <PortalToFollowElemTrigger- onClick={() => {- if (readonly)- return- setOpen(v => !v)- }}- className="block"- >- {- renderTrigger- ? renderTrigger({- open,- disabled,- modelDisabled,- hasDeprecated,- currentProvider,- currentModel,- providerName: provider,- modelId,- })- : (- <Trigger- disabled={disabled}- isInWorkflow={isInWorkflow}- modelDisabled={modelDisabled}- hasDeprecated={hasDeprecated}- currentProvider={currentProvider}- currentModel={currentModel}- providerName={provider}- modelId={modelId}- />- )- }- </PortalToFollowElemTrigger>- <PortalToFollowElemContent className={cn('z-[60]', portalToFollowElemContentClassName)}>- <div className={cn(popupClassName, 'w-[389px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg')}>- <div className={cn('max-h-[420px] overflow-y-auto p-4 pt-3')}>- <div className="relative">- <div className={cn('system-sm-semibold mb-1 flex h-6 items-center text-text-secondary')}>- {t('modelProvider.model', { ns: 'common' }).toLocaleUpperCase()}- </div>- <ModelSelector- defaultModel={(provider || modelId) ? { provider, model: modelId } : undefined}- modelList={activeTextGenerationModelList}- onSelect={handleChangeModel}- />- </div>- {- !!parameterRules.length && (- <div className="my-3 h-px bg-divider-subtle" />- )- }- {- isLoading && (- <div className="mt-5"><Loading /></div>- )- }- {- !isLoading && !!parameterRules.length && (- <div className="mb-2 flex items-center justify-between">- <div className={cn('system-sm-semibold flex h-6 items-center text-text-secondary')}>{t('modelProvider.parameters', { ns: 'common' })}</div>- {- PROVIDER_WITH_PRESET_TONE.includes(provider) && (- <PresetsParameter onSelect={handleSelectPresetParameter} />- )- }- </div>- )- }- {- !isLoading && !!parameterRules.length && (- [- ...parameterRules,- ...(isAdvancedMode ? [STOP_PARAMETER_RULE] : []),- ].map(parameter => (- <ParameterItem- key={`${modelId}-${parameter.name}`}- parameterRule={parameter}- value={completionParams?.[parameter.name]}- onChange={v => handleParamChange(parameter.name, v)}- onSwitch={(checked, assignValue) => handleSwitch(parameter.name, checked, assignValue)}+ <PopoverTrigger+ render={(+ <button type="button" className="block w-full border-none bg-transparent p-0 text-left [color:inherit] [font:inherit]">+ {+ renderTrigger+ ? renderTrigger({+ open,+ currentProvider,+ currentModel,+ providerName: provider,+ modelId,+ })+ : (+ <TriggerisInWorkflow={isInWorkflow}+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName={provider}+ modelId={modelId}+ settingsRef={settingsIconRef}/>- ))- )- }- </div>- {!hideDebugWithMultipleModel && (- <div- className="bg-components-section-burn system-sm-regular flex h-[50px] cursor-pointer items-center justify-between rounded-b-xl border-t border-t-divider-subtle px-4 text-text-accent"- onClick={() => onDebugWithMultipleModelChange?.()}- >+ )+ }+ </button>+ )}+ />+ <PopoverContent+ placement={isInWorkflow ? 'left' : (renderTrigger ? 'bottom-end' : 'left-start')}+ sideOffset={4}+ className={portalToFollowElemContentClassName}+ popupClassName={cn(popupClassName, 'w-[400px] rounded-2xl')}+ positionerProps={!renderTrigger ? { anchor: settingsIconRef } : undefined}+ >+ <div className="relative px-3 pb-1 pt-3.5">+ <div className="pl-1 pr-8 text-text-primary system-xl-semibold">+ {t('modelProvider.modelSettings', { ns: 'common' })}+ </div>+ <PopoverClose className="absolute right-2.5 top-2.5 flex items-center justify-center rounded-lg p-1.5 hover:bg-state-base-hover">+ <span className="i-ri-close-line h-4 w-4 text-text-tertiary" />+ </PopoverClose>+ </div>+ <div className="max-h-[420px] overflow-y-auto">+ <div className="px-4 pb-4 pt-2">+ <ModelSelector+ defaultModel={(provider || modelId) ? { provider, model: modelId } : undefined}+ modelList={activeTextGenerationModelList}+ onSelect={handleChangeModel}+ onHide={() => setOpen(false)}+ />+ </div>+ {+ !!parameterRules.length && (+ <div className="flex flex-col gap-2 border-t border-divider-subtle px-4 pb-4 pt-3">+ <div className="flex items-center gap-1">+ <div className="flex flex-1 items-center text-text-secondary system-sm-semibold-uppercase">{t('modelProvider.parameters', { ns: 'common' })}</div>+ {+ PROVIDER_WITH_PRESET_TONE.includes(provider) && (+ <PresetsParameter onSelect={handleSelectPresetParameter} />+ )+ }+ </div>{- debugWithMultipleModel- ? t('debugAsSingleModel', { ns: 'appDebug' })- : t('debugAsMultipleModel', { ns: 'appDebug' })+ isLoading+ ? <div className="py-5"><Loading /></div>+ : (+ [+ ...parameterRules,+ ...(isAdvancedMode ? [STOP_PARAMETER_RULE] : []),+ ].map(parameter => (+ <ParameterItem+ key={`${modelId}-${parameter.name}`}+ parameterRule={parameter}+ value={completionParams?.[parameter.name]}+ onChange={v => handleParamChange(parameter.name, v)}+ onSwitch={(checked, assignValue) => handleSwitch(parameter.name, checked, assignValue)}+ isInWorkflow={isInWorkflow}+ />+ ))+ )}- <ArrowNarrowLeft className="h-3 w-3 rotate-180" /></div>- )}+ )+ }+ {+ !parameterRules.length && isLoading && (+ <div className="px-4 py-5"><Loading /></div>+ )+ }+ </div>+ {!hideDebugWithMultipleModel && (+ <div+ className="flex h-[50px] cursor-pointer items-center justify-between rounded-b-xl border-t border-t-divider-subtle px-4 text-text-accent system-sm-regular"+ onClick={() => onDebugWithMultipleModelChange?.()}+ >+ {+ debugWithMultipleModel+ ? t('debugAsSingleModel', { ns: 'appDebug' })+ : t('debugAsMultipleModel', { ns: 'appDebug' })+ }+ <ArrowNarrowLeft className="h-3 w-3 rotate-180" /></div>- </PortalToFollowElemContent>- </div>- </PortalToFollowElem>+ )}+ </PopoverContent>+ </Popover>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.select.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.select.spec.tsxnew file mode 100644index 00000000000..21703fbed64--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.select.spec.tsx@@ -0,0 +1,48 @@+import type { ReactNode } from 'react'+import { fireEvent, render, screen } from '@testing-library/react'+import ParameterItem from './parameter-item'++vi.mock('../hooks', () => ({+ useLanguage: () => 'en_US',+}))++vi.mock('@/app/components/base/ui/select', () => ({+ Select: ({ children, onValueChange }: { children: ReactNode, onValueChange: (value: string | undefined) => void }) => (+ <div>+ <button type="button" onClick={() => onValueChange('updated')}>select-updated</button>+ <button type="button" onClick={() => onValueChange(undefined)}>select-empty</button>+ {children}+ </div>+ ),+ SelectContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectItem: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectTrigger: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ SelectValue: () => <div>SelectValue</div>,+}))++describe('ParameterItem select mode', () => {+ it('should propagate both explicit and empty select values', () => {+ const onChange = vi.fn()++ render(+ <ParameterItem+ parameterRule={{+ name: 'format',+ label: { en_US: 'Format', zh_Hans: 'Format' },+ type: 'string',+ options: ['json', 'text'],+ required: false,+ help: { en_US: 'Help', zh_Hans: 'Help' },+ }}+ value="json"+ onChange={onChange}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'select-updated' }))+ fireEvent.click(screen.getByRole('button', { name: 'select-empty' }))++ expect(onChange).toHaveBeenNthCalledWith(1, 'updated')+ expect(onChange).toHaveBeenNthCalledWith(2, undefined)+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsxindex 8ae0b99159c..86fb6d81d02 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx@@ -1,12 +1,11 @@-import type { FC } from 'react'import type { ModelParameterRule } from '../declarations'import { useEffect, useRef, useState } from 'react'import Radio from '@/app/components/base/radio'-import { SimpleSelect } from '@/app/components/base/select'import Slider from '@/app/components/base/slider'import Switch from '@/app/components/base/switch'import TagInput from '@/app/components/base/tag-input'-import Tooltip from '@/app/components/base/tooltip'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/app/components/base/ui/select'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { cn } from '@/utils/classnames'import { useLanguage } from '../hooks'import { isNullOrUndefined } from '../utils'@@ -20,13 +19,13 @@ type ParameterItemProps = {onSwitch?: (checked: boolean, assignValue: ParameterValue) => voidisInWorkflow?: boolean}-const ParameterItem: FC<ParameterItemProps> = ({+function ParameterItem({parameterRule,value,onChange,onSwitch,isInWorkflow,-}) => {+}: ParameterItemProps) {const language = useLanguage()const [localValue, setLocalValue] = useState(value)const numberInputRef = useRef<HTMLInputElement>(null)@@ -99,10 +98,6 @@ const ParameterItem: FC<ParameterItemProps> = ({handleInputChange(e.target.value)}- const handleSelect = (option: { value: string | number, name: string }) => {- handleInputChange(option.value)- }-const handleTagChange = (newSequences: string[]) => {handleInputChange(newSequences)}@@ -222,13 +217,19 @@ const ParameterItem: FC<ParameterItemProps> = ({if (parameterRule.type === 'string' && !!parameterRule?.options?.length) {return (- <SimpleSelect- className="!py-0"- wrapperClassName={cn('!h-8 w-full')}- defaultValue={renderValue as string}- onSelect={handleSelect}- items={parameterRule.options.map(option => ({ value: option, name: option }))}- />+ <Select+ value={renderValue as string}+ onValueChange={v => handleInputChange(v ?? undefined)}+ >+ <SelectTrigger className="w-full">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {parameterRule.options!.map(option => (+ <SelectItem key={option} value={option}>{option}</SelectItem>+ ))}+ </SelectContent>+ </Select>)}@@ -272,13 +273,18 @@ const ParameterItem: FC<ParameterItemProps> = ({</div>{parameterRule.help && (- <Tooltip- popupContent={(+ <Tooltip>+ <TooltipTrigger+ render={(+ <span className="mr-1 flex h-4 w-4 shrink-0 items-center justify-center">+ <span aria-hidden className="i-ri-question-line h-3.5 w-3.5 text-text-quaternary" />+ </span>+ )}+ />+ <TooltipContent popupClassName="mr-1"><div className="w-[150px] whitespace-pre-wrap">{parameterRule.help[language] || parameterRule.help.en_US}</div>- )}- popupClassName="mr-1"- triggerClassName="mr-1 w-4 h-4 shrink-0"- />+ </TooltipContent>+ </Tooltip>)}</div>diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/presets-parameter.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/presets-parameter.tsxindex 35e15a29f43..e356ec55872 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/presets-parameter.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/presets-parameter.tsx@@ -1,14 +1,16 @@-import type { FC } from 'react'-import { RiArrowDownSLine } from '@remixicon/react'-import { useCallback } from 'react'+import type { ReactNode } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'-import Dropdown from '@/app/components/base/dropdown'import { Brush01 } from '@/app/components/base/icons/src/vender/solid/editor'import { Scales02 } from '@/app/components/base/icons/src/vender/solid/FinanceAndECommerce'import { Target04 } from '@/app/components/base/icons/src/vender/solid/general'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuTrigger,+} from '@/app/components/base/ui/dropdown-menu'import { TONE_LIST } from '@/config'-import { cn } from '@/utils/classnames'const toneI18nKeyMap = {Creative: 'model.tone.Creative',@@ -17,53 +19,42 @@ const toneI18nKeyMap = {Custom: 'model.tone.Custom',} as const+const TONE_ICONS: Record<number, ReactNode> = {+ 1: <Brush01 className="mr-2 h-[14px] w-[14px] text-[#6938EF]" />,+ 2: <Scales02 className="mr-2 h-[14px] w-[14px] text-indigo-600" />,+ 3: <Target04 className="mr-2 h-[14px] w-[14px] text-[#107569]" />,+}+type PresetsParameterProps = {onSelect: (toneId: number) => void}-const PresetsParameter: FC<PresetsParameterProps> = ({- onSelect,-}) => {++function PresetsParameter({ onSelect }: PresetsParameterProps) {const { t } = useTranslation()- const renderTrigger = useCallback((open: boolean) => {- return (- <Button- size="small"- variant="secondary"- className={cn(open && 'bg-state-base-hover')}- >- {t('modelProvider.loadPresets', { ns: 'common' })}- <RiArrowDownSLine className="ml-0.5 h-3.5 w-3.5" />- </Button>- )- }, [t])- const getToneIcon = (toneId: number) => {- const className = 'mr-2 w-[14px] h-[14px]'- const res = ({- 1: <Brush01 className={`${className} text-[#6938EF]`} />,- 2: <Scales02 className={`${className} text-indigo-600`} />,- 3: <Target04 className={`${className} text-[#107569]`} />,- })[toneId]- return res- }- const options = TONE_LIST.slice(0, 3).map((tone) => {- return {- value: tone.id,- text: (- <div className="flex h-full items-center">- {getToneIcon(tone.id)}- {t(toneI18nKeyMap[tone.name], { ns: 'common' })}- </div>- ),- }- })return (- <Dropdown- renderTrigger={renderTrigger}- items={options}- onSelect={item => onSelect(item.value as number)}- popupClassName="z-[1003]"- />+ <DropdownMenu>+ <DropdownMenuTrigger+ render={(+ <Button+ size="small"+ variant="secondary"+ className="data-[popup-open]:bg-state-base-hover"+ />+ )}+ >+ {t('modelProvider.loadPresets', { ns: 'common' })}+ <span className="i-ri-arrow-down-s-line ml-0.5 h-3.5 w-3.5" />+ </DropdownMenuTrigger>+ <DropdownMenuContent>+ {TONE_LIST.slice(0, 3).map(tone => (+ <DropdownMenuItem key={tone.id} onClick={() => onSelect(tone.id)}>+ {TONE_ICONS[tone.id]}+ {t(toneI18nKeyMap[tone.name], { ns: 'common' })}+ </DropdownMenuItem>+ ))}+ </DropdownMenuContent>+ </DropdownMenu>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger.tsxindex 3389f5112ef..289a08e89ee 100644--- a/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger.tsx@@ -1,110 +1,136 @@-import type { FC } from 'react'+import type { FC, Ref } from 'react'import type {Model,ModelItem,ModelProvider,} from '../declarations'-import { RiArrowDownSLine } from '@remixicon/react'import { useTranslation } from 'react-i18next'-import { AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'-import { SlidersH } from '@/app/components/base/icons/src/vender/line/mediaAndDevices'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { useProviderContext } from '@/context/provider-context'import { cn } from '@/utils/classnames'-import { MODEL_STATUS_TEXT } from '../declarations'-import { useLanguage } from '../hooks'import ModelIcon from '../model-icon'import ModelName from '../model-name'+import { useCredentialPanelState } from '../provider-added-card/use-credential-panel-state'+import {+ deriveTriggerStatus,+ TRIGGER_STATUS_BADGE_I18N,+ TRIGGER_STATUS_TOOLTIP_I18N,+} from './derive-trigger-status'export type TriggerProps = {open?: boolean- disabled?: booleancurrentProvider?: ModelProvider | ModelcurrentModel?: ModelItemproviderName?: stringmodelId?: string- hasDeprecated?: boolean- modelDisabled?: booleanisInWorkflow?: boolean+ settingsRef?: Ref<HTMLDivElement>}+const Trigger: FC<TriggerProps> = ({- disabled,currentProvider,currentModel,providerName,modelId,- hasDeprecated,- modelDisabled,isInWorkflow,+ settingsRef,}) => {const { t } = useTranslation()- const language = useLanguage()const { modelProviders } = useProviderContext()+ const currentModelProvider = modelProviders.find(p => p.provider === providerName)+ const credentialState = useCredentialPanelState(currentModelProvider)+ const status = deriveTriggerStatus(modelId, providerName, currentModelProvider, currentModel, credentialState)+ const badgeKey = TRIGGER_STATUS_BADGE_I18N[status as keyof typeof TRIGGER_STATUS_BADGE_I18N]+ const tooltipKey = TRIGGER_STATUS_TOOLTIP_I18N[status as keyof typeof TRIGGER_STATUS_TOOLTIP_I18N]+ const badgeLabel = badgeKey ? t(badgeKey, { ns: 'common' }) : null+ const tooltipLabel = tooltipKey ? t(tooltipKey, { ns: 'common' }) : null+ const isActive = status === 'active'+ const iconProvider = currentProvider || modelProviders.find(item => item.provider === providerName)++ if (status === 'empty') {+ return (+ <div+ className={cn(+ 'relative flex h-8 min-w-[296px] cursor-pointer items-center rounded-lg px-2',+ isInWorkflow+ ? 'border border-text-warning bg-state-warning-hover pr-[30px]'+ : 'border border-text-warning bg-state-warning-hover ring-inset ring-text-warning hover:ring-[0.5px]',+ )}+ >+ <div className="mr-2 flex h-6 w-6 shrink-0 items-center justify-center">+ <div className="flex h-5 w-5 items-center justify-center rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-subtle">+ <span className="i-ri-brain-2-line h-3.5 w-3.5 text-text-quaternary" />+ </div>+ </div>+ <div className="mr-1 flex-1 truncate text-[13px] font-normal text-text-secondary">+ {t('workflow:errorMsg.configureModel')}+ </div>+ <span className={cn('i-ri-arrow-down-s-line h-4 w-4 shrink-0 text-text-tertiary', isInWorkflow && 'absolute right-2 top-[9px] h-3.5 w-3.5')} />+ </div>+ )+ }return (- <div- className={cn(- 'relative flex h-8 cursor-pointer items-center rounded-lg px-2',- !isInWorkflow && 'border ring-inset hover:ring-[0.5px]',- !isInWorkflow && (disabled ? 'border-text-warning bg-state-warning-hover ring-text-warning' : 'border-util-colors-indigo-indigo-600 bg-state-accent-hover ring-util-colors-indigo-indigo-600'),- isInWorkflow && 'border border-workflow-block-parma-bg bg-workflow-block-parma-bg pr-[30px] hover:border-components-input-border-active',- )}- >- {- currentProvider && (- <ModelIcon- className="mr-1.5 !h-5 !w-5"- provider={currentProvider}- modelName={currentModel?.model}- />- )- }- {- !currentProvider && (- <ModelIcon- className="mr-1.5 !h-5 !w-5"- provider={modelProviders.find(item => item.provider === providerName)}- modelName={modelId}- />- )- }- {- currentModel && (- <ModelName- className="mr-1.5 text-text-primary"- modelItem={currentModel}- showMode- showFeatures- />- )- }- {- !currentModel && (- <div className="mr-1 truncate text-[13px] font-medium text-text-primary">- {modelId}+ <div className="flex h-8 min-w-[296px] cursor-pointer items-center gap-px overflow-hidden rounded-lg">+ <div className={cn('flex flex-1 items-center gap-0.5 rounded-l-lg p-1', isInWorkflow ? 'border border-workflow-block-parma-bg bg-workflow-block-parma-bg' : 'bg-components-input-bg-normal')}>+ <ModelIcon+ className="p-0.5"+ provider={iconProvider}+ modelName={currentModel?.model || modelId}+ />+ <div className="flex flex-1 items-center truncate px-1 py-[3px]">+ {currentModel+ ? (+ <ModelName+ className="grow"+ modelItem={currentModel}+ showMode={isActive}+ showFeatures={isActive}+ />+ )+ : <div className="truncate text-[13px] font-normal text-components-input-text-filled">{modelId}</div>}+ </div>+ {badgeKey && (+ tooltipLabel+ ? (+ <Tooltip>+ <TooltipTrigger+ render={(+ <div className="flex shrink-0 items-center pr-0.5">+ <div className="flex min-w-[20px] shrink-0 items-center justify-center gap-[3px] rounded-md border border-text-warning bg-components-badge-bg-dimm px-[5px] py-0.5">+ <span className="i-ri-alert-fill h-3 w-3 text-text-warning" />+ <span className="whitespace-nowrap text-text-warning system-xs-medium">+ {badgeLabel}+ </span>+ </div>+ </div>+ )}+ />+ <TooltipContent placement="top">+ {tooltipLabel}+ </TooltipContent>+ </Tooltip>+ )+ : (+ <div className="flex shrink-0 items-center pr-0.5">+ <div className="flex min-w-[20px] shrink-0 items-center justify-center gap-[3px] rounded-md border border-text-warning bg-components-badge-bg-dimm px-[5px] py-0.5">+ <span className="i-ri-alert-fill h-3 w-3 text-text-warning" />+ <span className="whitespace-nowrap text-text-warning system-xs-medium">+ {badgeLabel}+ </span>+ </div>+ </div>+ )+ )}+ {!badgeKey && (+ <div className="flex shrink-0 items-center pr-1">+ <span className="i-ri-arrow-down-s-line h-4 w-4 text-text-tertiary" /></div>- )- }- {- disabled- ? (- <Tooltip- popupContent={- hasDeprecated- ? t('modelProvider.deprecated', { ns: 'common' })- : (modelDisabled && currentModel)- ? MODEL_STATUS_TEXT[currentModel.status as string][language]- : ''- }- >- <AlertTriangle className="h-4 w-4 text-[#F79009]" />- </Tooltip>- )- : (- <SlidersH className={cn(!isInWorkflow ? 'text-indigo-600' : 'text-text-tertiary', 'h-4 w-4 shrink-0')} />- )- }- {isInWorkflow && (<RiArrowDownSLine className="absolute right-2 top-[9px] h-3.5 w-3.5 text-text-tertiary" />)}+ )}+ </div>+ <div ref={settingsRef} className={cn('flex shrink-0 items-center justify-center rounded-r-lg p-2', isInWorkflow ? 'border border-workflow-block-parma-bg bg-workflow-block-parma-bg' : 'bg-components-button-tertiary-bg')}>+ <span className="i-ri-equalizer-2-line h-4 w-4 text-text-tertiary" />+ </div></div>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/deprecated-model-trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/deprecated-model-trigger.spec.tsxdeleted file mode 100644index c6ba54d8004..00000000000--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/deprecated-model-trigger.spec.tsx+++ /dev/null@@ -1,61 +0,0 @@-import { fireEvent, render, screen } from '@testing-library/react'-import DeprecatedModelTrigger from '../deprecated-model-trigger'--vi.mock('../../model-icon', () => ({- default: ({ modelName }: { modelName: string }) => <span>{modelName}</span>,-}))--const mockUseProviderContext = vi.hoisted(() => vi.fn())-vi.mock('@/context/provider-context', () => ({- useProviderContext: mockUseProviderContext,-}))--describe('DeprecatedModelTrigger', () => {- beforeEach(() => {- vi.clearAllMocks()- mockUseProviderContext.mockReturnValue({- modelProviders: [{ provider: 'someone-else' }, { provider: 'openai' }],- })- })-- it('should render model name', () => {- render(<DeprecatedModelTrigger modelName="gpt-deprecated" providerName="openai" />)- expect(screen.getAllByText('gpt-deprecated').length).toBeGreaterThan(0)- })-- it('should show deprecated tooltip when warn icon is hovered', async () => {- const { container } = render(- <DeprecatedModelTrigger- modelName="gpt-deprecated"- providerName="openai"- showWarnIcon- />,- )-- const tooltipTrigger = container.querySelector('[data-state]') as HTMLElement- fireEvent.mouseEnter(tooltipTrigger)-- expect(await screen.findByText('common.modelProvider.deprecated')).toBeInTheDocument()- })-- it('should render when provider is not found', () => {- mockUseProviderContext.mockReturnValue({- modelProviders: [{ provider: 'someone-else' }],- })-- render(<DeprecatedModelTrigger modelName="gpt-deprecated" providerName="openai" />)- expect(screen.getAllByText('gpt-deprecated').length).toBeGreaterThan(0)- })-- it('should not show deprecated tooltip when warn icon is disabled', async () => {- render(- <DeprecatedModelTrigger- modelName="gpt-deprecated"- providerName="openai"- showWarnIcon={false}- />,- )-- expect(screen.queryByText('common.modelProvider.deprecated')).not.toBeInTheDocument()- })-})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/empty-trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/empty-trigger.spec.tsxdeleted file mode 100644index e560866846f..00000000000--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/empty-trigger.spec.tsx+++ /dev/null@@ -1,31 +0,0 @@-import { render, screen } from '@testing-library/react'-import EmptyTrigger from '../empty-trigger'--describe('EmptyTrigger', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- it('should render configure model text', () => {- render(<EmptyTrigger open={false} />)- expect(screen.getByText('plugin.detailPanel.configureModel')).toBeInTheDocument()- })-- // open=true: hover bg class present- it('should apply hover background class when open is true', () => {- // Act- const { container } = render(<EmptyTrigger open={true} />)-- // Assert- expect(container.firstChild).toHaveClass('bg-components-input-bg-hover')- })-- // className prop truthy: custom className appears on root- it('should apply custom className when provided', () => {- // Act- const { container } = render(<EmptyTrigger open={false} className="custom-class" />)-- // Assert- expect(container.firstChild).toHaveClass('custom-class')- })-})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsxindex 27239a7079d..2bcb7b712bb 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/index.spec.tsx@@ -1,4 +1,6 @@-import type { Model, ModelItem } from '../../declarations'+import type { ReactNode } from 'react'+import type { DefaultModel, Model, ModelItem } from '../../declarations'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen } from '@testing-library/react'import {ConfigurationMethodEnum,@@ -7,16 +9,20 @@ import {} from '../../declarations'import ModelSelector from '../index'-vi.mock('../model-trigger', () => ({- default: () => <div>model-trigger</div>,-}))+vi.mock('../model-selector-trigger', () => ({+ default: ({+ currentProvider,+ currentModel,+ defaultModel,+ }: { currentProvider?: Model, currentModel?: ModelItem, defaultModel?: DefaultModel }) => {+ if (currentProvider && currentModel)+ return <div>model-trigger</div>-vi.mock('../deprecated-model-trigger', () => ({- default: ({ modelName }: { modelName: string }) => <div>{`deprecated:${modelName}`}</div>,-}))+ if (defaultModel)+ return <div>{`deprecated:${defaultModel.model}`}</div>-vi.mock('../empty-trigger', () => ({- default: () => <div>empty-trigger</div>,+ return <div>empty-trigger</div>+ },}))vi.mock('../popup', () => ({@@ -52,24 +58,43 @@ const makeModel = (overrides: Partial<Model> = {}): Model => ({...overrides,})+const createTestQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: { retry: false },+ mutations: { retry: false },+ },+})++const renderWithQueryClient = (node: ReactNode) => {+ const queryClient = createTestQueryClient()+ return render(+ <QueryClientProvider client={queryClient}>+ {node}+ </QueryClientProvider>,+ )+}+describe('ModelSelector', () => {beforeEach(() => {vi.clearAllMocks()})it('should toggle popup and close it after selecting a model', () => {- render(<ModelSelector modelList={[makeModel()]} />)+ renderWithQueryClient(<ModelSelector modelList={[makeModel()]} />)- fireEvent.click(screen.getByText('empty-trigger'))+ const triggerButton = screen.getByRole('button', { name: 'empty-trigger' })++ fireEvent.click(triggerButton)+ expect(triggerButton).toHaveAttribute('aria-expanded', 'true')expect(screen.getByText('select')).toBeInTheDocument()fireEvent.click(screen.getByText('select'))- expect(screen.queryByText('select')).not.toBeInTheDocument()+ expect(triggerButton).toHaveAttribute('aria-expanded', 'false')})it('should call onSelect when provided', () => {const onSelect = vi.fn()- render(<ModelSelector modelList={[makeModel()]} onSelect={onSelect} />)+ renderWithQueryClient(<ModelSelector modelList={[makeModel()]} onSelect={onSelect} />)fireEvent.click(screen.getByText('empty-trigger'))fireEvent.click(screen.getByText('select'))@@ -78,24 +103,26 @@ describe('ModelSelector', () => {})it('should close popup when popup requests hide', () => {- render(<ModelSelector modelList={[makeModel()]} />)+ renderWithQueryClient(<ModelSelector modelList={[makeModel()]} />)- fireEvent.click(screen.getByText('empty-trigger'))+ const triggerButton = screen.getByRole('button', { name: 'empty-trigger' })+ fireEvent.click(triggerButton)+ expect(triggerButton).toHaveAttribute('aria-expanded', 'true')expect(screen.getByText('hide')).toBeInTheDocument()fireEvent.click(screen.getByText('hide'))- expect(screen.queryByText('hide')).not.toBeInTheDocument()+ expect(triggerButton).toHaveAttribute('aria-expanded', 'false')})it('should not open popup when readonly', () => {- render(<ModelSelector modelList={[makeModel()]} readonly />)+ renderWithQueryClient(<ModelSelector modelList={[makeModel()]} readonly />)fireEvent.click(screen.getByText('empty-trigger'))expect(screen.queryByText('select')).not.toBeInTheDocument()})it('should render deprecated trigger when defaultModel is not in list', () => {- const { rerender } = render(+ const { unmount } = renderWithQueryClient(<ModelSelectordefaultModel={{ provider: 'openai', model: 'missing-model' }}modelList={[makeModel()]}@@ -104,7 +131,8 @@ describe('ModelSelector', () => {expect(screen.getByText('deprecated:missing-model')).toBeInTheDocument()- rerender(+ unmount()+ renderWithQueryClient(<ModelSelectordefaultModel={{ provider: '', model: '' }}modelList={[makeModel()]}@@ -114,7 +142,7 @@ describe('ModelSelector', () => {})it('should render model trigger when defaultModel matches', () => {- render(+ renderWithQueryClient(<ModelSelectordefaultModel={{ provider: 'openai', model: 'gpt-4' }}modelList={[makeModel()]}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-trigger.spec.tsxdeleted file mode 100644index 245234b61d6..00000000000--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/model-trigger.spec.tsx+++ /dev/null@@ -1,91 +0,0 @@-import type { Model, ModelItem } from '../../declarations'-import { fireEvent, render, screen } from '@testing-library/react'-import {- ConfigurationMethodEnum,- ModelStatusEnum,- ModelTypeEnum,-} from '../../declarations'-import ModelTrigger from '../model-trigger'--vi.mock('../../hooks', async () => {- const actual = await vi.importActual<typeof import('../../hooks')>('../../hooks')- return {- ...actual,- useLanguage: () => 'en_US',- }-})--vi.mock('../../model-icon', () => ({- default: ({ modelName }: { modelName: string }) => <span>{modelName}</span>,-}))--vi.mock('../../model-name', () => ({- default: ({ modelItem }: { modelItem: ModelItem }) => <span>{modelItem.label.en_US}</span>,-}))--const makeModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({- model: 'gpt-4',- label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' },- model_type: ModelTypeEnum.textGeneration,- fetch_from: ConfigurationMethodEnum.predefinedModel,- status: ModelStatusEnum.active,- model_properties: {},- load_balancing_enabled: false,- ...overrides,-})--const makeModel = (overrides: Partial<Model> = {}): Model => ({- provider: 'openai',- icon_small: { en_US: '', zh_Hans: '' },- label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },- models: [makeModelItem()],- status: ModelStatusEnum.active,- ...overrides,-})--describe('ModelTrigger', () => {- beforeEach(() => {- vi.clearAllMocks()- })-- it('should show model name', () => {- render(- <ModelTrigger- open- provider={makeModel()}- model={makeModelItem()}- />,- )-- expect(screen.getByText('GPT-4')).toBeInTheDocument()- })-- it('should show status tooltip content when model is not active', async () => {- const { container } = render(- <ModelTrigger- open={false}- provider={makeModel()}- model={makeModelItem({ status: ModelStatusEnum.noConfigure })}- />,- )-- const tooltipTrigger = container.querySelector('[data-state]') as HTMLElement- fireEvent.mouseEnter(tooltipTrigger)-- expect(await screen.findByText('No Configure')).toBeInTheDocument()- })-- it('should not show status icon when readonly', () => {- render(- <ModelTrigger- open={false}- provider={makeModel()}- model={makeModelItem({ status: ModelStatusEnum.noConfigure })}- readonly- />,- )-- expect(screen.getByText('GPT-4')).toBeInTheDocument()- expect(screen.queryByText('No Configure')).not.toBeInTheDocument()- })-})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsxindex e06b9ca789f..050bb099d81 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup-item.spec.tsx@@ -2,21 +2,23 @@ import type { DefaultModel, Model, ModelItem } from '../../declarations'import { fireEvent, render, screen } from '@testing-library/react'import {ConfigurationMethodEnum,+ CustomConfigurationStatusEnum,ModelFeatureEnum,ModelStatusEnum,ModelTypeEnum,+ PreferredProviderTypeEnum,} from '../../declarations'import PopupItem from '../popup-item'const mockUpdateModelList = vi.hoisted(() => vi.fn())const mockUpdateModelProviders = vi.hoisted(() => vi.fn())-const mockLanguageRef = vi.hoisted(() => ({ value: 'en_US' }))+const mockUseLanguage = vi.hoisted(() => vi.fn(() => 'en_US'))vi.mock('../../hooks', async () => {const actual = await vi.importActual<typeof import('../../hooks')>('../../hooks')return {...actual,- useLanguage: () => mockLanguageRef.value,+ useLanguage: mockUseLanguage,useUpdateModelList: () => mockUpdateModelList,useUpdateModelProviders: () => mockUpdateModelProviders,}@@ -34,6 +36,36 @@ vi.mock('../../model-name', () => ({default: ({ modelItem }: { modelItem: ModelItem }) => <span>{modelItem.label.en_US}</span>,}))+vi.mock('../feature-icon', () => ({+ default: ({ feature }: { feature: string }) => <span data-testid="feature-icon">{feature}</span>,+}))++vi.mock('@/app/components/base/tooltip', () => ({+ default: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}))++vi.mock('@/app/components/base/ui/popover', () => ({+ Popover: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ PopoverTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,+ PopoverContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}))++const mockCredentialPanelState = vi.hoisted(() => vi.fn())+vi.mock('../../provider-added-card/use-credential-panel-state', () => ({+ useCredentialPanelState: mockCredentialPanelState,+}))++vi.mock('../../provider-added-card/use-change-provider-priority', () => ({+ useChangeProviderPriority: () => ({+ isChangingPriority: false,+ handleChangePriority: vi.fn(),+ }),+}))++vi.mock('../../provider-added-card/model-auth-dropdown/dropdown-content', () => ({+ default: ({ onClose }: { onClose: () => void }) => <button type="button" onClick={onClose}>close dropdown</button>,+}))+const mockSetShowModelModal = vi.hoisted(() => vi.fn())vi.mock('@/context/modal-context', () => ({useModalContext: () => ({@@ -46,6 +78,11 @@ vi.mock('@/context/provider-context', () => ({useProviderContext: mockUseProviderContext,}))+const mockUseAppContext = vi.hoisted(() => vi.fn())+vi.mock('@/context/app-context', () => ({+ useAppContext: mockUseAppContext,+}))+const makeModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({model: 'gpt-4',label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' },@@ -67,18 +104,53 @@ const makeModel = (overrides: Partial<Model> = {}): Model => ({...overrides,})+const makeProvider = (overrides: Record<string, unknown> = {}) => ({+ provider: 'openai',+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_name: 'my-api-key',+ },+ ...overrides,+})+describe('PopupItem', () => {beforeEach(() => {vi.clearAllMocks()- mockLanguageRef.value = 'en_US'+ mockUseLanguage.mockReturnValue('en_US')mockUseProviderContext.mockReturnValue({- modelProviders: [{ provider: 'openai' }],+ modelProviders: [makeProvider()],+ })+ mockUseAppContext.mockReturnValue({+ currentWorkspace: { trial_credits: 200, trial_credits_used: 0 },})+ mockCredentialPanelState.mockReturnValue({+ variant: 'api-active',+ priority: 'apiKey',+ supportsCredits: false,+ showPrioritySwitcher: false,+ hasCredentials: true,+ isCreditsExhausted: false,+ credentialName: 'my-api-key',+ credits: 200,+ })+ })++ it('should render nothing when provider is not found in modelProviders', () => {+ mockUseProviderContext.mockReturnValue({+ modelProviders: [],+ })++ const { container } = render(+ <PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />,+ )++ expect(container.innerHTML).toBe('')})it('should call onSelect when clicking an active model', () => {const onSelect = vi.fn()- render(<PopupItem model={makeModel()} onSelect={onSelect} />)+ render(<PopupItem model={makeModel()} onSelect={onSelect} onHide={vi.fn()} />)fireEvent.click(screen.getByText('GPT-4'))@@ -91,6 +163,7 @@ describe('PopupItem', () => {<PopupItemmodel={makeModel({ models: [makeModelItem({ status: ModelStatusEnum.disabled })] })}onSelect={onSelect}+ onHide={vi.fn()}/>,)@@ -104,6 +177,7 @@ describe('PopupItem', () => {<PopupItemmodel={makeModel({ models: [makeModelItem({ status: ModelStatusEnum.noConfigure })] })}onSelect={vi.fn()}+ onHide={vi.fn()}/>,)@@ -123,6 +197,7 @@ describe('PopupItem', () => {models: [makeModelItem({ status: ModelStatusEnum.noConfigure, model_type: undefined as unknown as ModelTypeEnum })],})}onSelect={vi.fn()}+ onHide={vi.fn()}/>,)@@ -141,92 +216,148 @@ describe('PopupItem', () => {defaultModel={defaultModel}model={makeModel()}onSelect={vi.fn()}+ onHide={vi.fn()}/>,)expect(screen.getByText('GPT-4')).toBeInTheDocument()})- it('should not show check icon when model matches but provider does not', () => {- const defaultModel: DefaultModel = { provider: 'anthropic', model: 'gpt-4' }+ it('should fall back to english labels when the current language is unavailable', () => {+ mockUseLanguage.mockReturnValue('zh_Hans')+render(<PopupItem- defaultModel={defaultModel}- model={makeModel()}+ model={makeModel({+ label: { en_US: 'OpenAI only' } as Model['label'],+ models: [makeModelItem({ label: { en_US: 'GPT-4 only' } as ModelItem['label'] })],+ })}onSelect={vi.fn()}+ onHide={vi.fn()}/>,)- const checkIcons = document.querySelectorAll('.h-4.w-4.shrink-0.text-text-accent')- expect(checkIcons.length).toBe(0)+ expect(screen.getByText('OpenAI only')).toBeInTheDocument()+ expect(screen.getByText('GPT-4 only')).toBeInTheDocument()})- it('should not show mode badge when model_properties.mode is absent', () => {- const modelItem = makeModelItem({ model_properties: {} })- render(- <PopupItem- model={makeModel({ models: [modelItem] })}- onSelect={vi.fn()}- />,- )+ it('should toggle collapsed state when clicking provider header', () => {+ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />)- expect(screen.queryByText('CHAT')).not.toBeInTheDocument()+ expect(screen.getByText('GPT-4')).toBeInTheDocument()++ fireEvent.click(screen.getByText('OpenAI'))++ expect(screen.queryByText('GPT-4')).not.toBeInTheDocument()++ fireEvent.click(screen.getByText('OpenAI'))++ expect(screen.getByText('GPT-4')).toBeInTheDocument()})- it('should fall back to en_US label when current locale translation is empty', () => {- mockLanguageRef.value = 'zh_Hans'- const model = makeModel({- label: { en_US: 'English Label', zh_Hans: '' },+ it('should show credential name when using custom provider', () => {+ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />)++ expect(screen.getByText('my-api-key')).toBeInTheDocument()+ })++ it('should render the inactive credential badge when the api key is not active', () => {+ mockCredentialPanelState.mockReturnValue({+ variant: 'api-inactive',+ priority: 'apiKey',+ supportsCredits: false,+ showPrioritySwitcher: false,+ hasCredentials: true,+ isCreditsExhausted: false,+ credentialName: 'stale-key',+ credits: 200,})- render(<PopupItem model={model} onSelect={vi.fn()} />)- expect(screen.getByText('English Label')).toBeInTheDocument()+ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />)++ expect(screen.getByText('stale-key')).toBeInTheDocument()+ expect(document.querySelector('.bg-components-badge-status-light-error-bg')).not.toBeNull()})- it('should not show context_size badge when absent', () => {- const modelItem = makeModelItem({ model_properties: { mode: 'chat' } })- render(- <PopupItem- model={makeModel({ models: [modelItem] })}- onSelect={vi.fn()}- />,- )+ it('should show configure required when no credential name', () => {+ mockUseProviderContext.mockReturnValue({+ modelProviders: [makeProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ current_credential_name: '',+ },+ })],+ })+ mockCredentialPanelState.mockReturnValue({+ variant: 'api-required-configure',+ priority: 'apiKey',+ supportsCredits: false,+ showPrioritySwitcher: false,+ hasCredentials: false,+ isCreditsExhausted: false,+ credentialName: undefined,+ credits: 0,+ })- expect(screen.queryByText(/K$/)).not.toBeInTheDocument()+ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />)++ expect(screen.getByText(/modelProvider\.selector\.configureRequired/)).toBeInTheDocument()})- it('should not show capabilities section when features are empty', () => {- const modelItem = makeModelItem({ features: [] })- render(- <PopupItem- model={makeModel({ models: [modelItem] })}- onSelect={vi.fn()}- />,- )+ it('should show credits info when using system provider with remaining credits', () => {+ mockUseProviderContext.mockReturnValue({+ modelProviders: [makeProvider({+ preferred_provider_type: PreferredProviderTypeEnum.system,+ })],+ })+ mockCredentialPanelState.mockReturnValue({+ variant: 'credits-active',+ priority: 'credits',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: false,+ isCreditsExhausted: false,+ credentialName: undefined,+ credits: 200,+ })++ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />)- expect(screen.queryByText('common.model.capabilities')).not.toBeInTheDocument()+ expect(screen.getByText(/modelProvider\.selector\.aiCredits/)).toBeInTheDocument()})- it('should not show capabilities for non-qualifying model types', () => {- const modelItem = makeModelItem({- model_type: ModelTypeEnum.tts,- features: [ModelFeatureEnum.vision],+ it('should show credits exhausted when system provider has no credits', () => {+ mockUseProviderContext.mockReturnValue({+ modelProviders: [makeProvider({+ preferred_provider_type: PreferredProviderTypeEnum.system,+ })],})- render(- <PopupItem- model={makeModel({ models: [modelItem] })}- onSelect={vi.fn()}- />,- )+ mockUseAppContext.mockReturnValue({+ currentWorkspace: { trial_credits: 100, trial_credits_used: 100 },+ })+ mockCredentialPanelState.mockReturnValue({+ variant: 'credits-exhausted',+ priority: 'credits',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: false,+ isCreditsExhausted: true,+ credentialName: undefined,+ credits: 0,+ })++ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={vi.fn()} />)- expect(screen.queryByText('common.model.capabilities')).not.toBeInTheDocument()+ expect(screen.getByText(/modelProvider\.selector\.creditsExhausted/)).toBeInTheDocument()})- it('should show en_US label when language is fr_FR and fr_FR key is absent', () => {- mockLanguageRef.value = 'fr_FR'- const model = makeModel({ label: { en_US: 'FallbackLabel', zh_Hans: 'FallbackLabel' } })- render(<PopupItem model={model} onSelect={vi.fn()} />)+ it('should close the dropdown through dropdown content callbacks', () => {+ const onHide = vi.fn()++ render(<PopupItem model={makeModel()} onSelect={vi.fn()} onHide={onHide} />)++ fireEvent.click(screen.getByRole('button', { name: 'close dropdown' }))- expect(screen.getByText('FallbackLabel')).toBeInTheDocument()+ expect(onHide).toHaveBeenCalled()})})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsxindex d01ba3a577e..dee16e394e5 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/__tests__/popup.spec.tsx@@ -1,6 +1,5 @@-import type { Model, ModelItem } from '../../declarations'-import { fireEvent, render, screen } from '@testing-library/react'-import { tooltipManager } from '@/app/components/base/tooltip/TooltipManager'+import type { Model, ModelItem, ModelProvider } from '../../declarations'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'import {ConfigurationMethodEnum,ModelFeatureEnum,@@ -23,11 +22,32 @@ vi.mock('@/utils/tool-call', () => ({supportFunctionCall: mockSupportFunctionCall,}))+type MockMarketplacePlugin = {+ plugin_id: string+ latest_package_identifier: string+}++type MockContextProvider = Pick<ModelProvider, 'provider' | 'label' | 'icon_small' | 'icon_small_dark' | 'custom_configuration' | 'system_configuration'>++const mockMarketplacePlugins = vi.hoisted(() => ({+ current: [] as MockMarketplacePlugin[],+ isLoading: false,+}))+const mockContextModelProviders = vi.hoisted(() => ({+ current: [] as MockContextProvider[],+}))+const mockTrialModels = vi.hoisted(() => ({+ current: ['test-openai', 'test-anthropic'] as string[],+}))vi.mock('../../hooks', async () => {const actual = await vi.importActual<typeof import('../../hooks')>('../../hooks')return {...actual,useLanguage: () => mockLanguage,+ useMarketplaceAllPlugins: () => ({+ plugins: mockMarketplacePlugins.current,+ isLoading: mockMarketplacePlugins.isLoading,+ }),}})@@ -35,6 +55,81 @@ vi.mock('../popup-item', () => ({default: ({ model }: { model: Model }) => <div>{model.provider}</div>,}))+vi.mock('@/context/provider-context', () => ({+ useProviderContext: () => ({ modelProviders: mockContextModelProviders.current }),+}))++vi.mock('@/context/global-public-context', () => ({+ useSystemFeaturesQuery: () => ({+ data: { trial_models: mockTrialModels.current },+ }),+}))++const mockTrialCredits = vi.hoisted(() => ({+ credits: 200,+ totalCredits: 200,+ isExhausted: false,+ isLoading: false,+ nextCreditResetDate: undefined as number | undefined,+}))+vi.mock('../../provider-added-card/use-trial-credits', () => ({+ useTrialCredits: () => mockTrialCredits,+}))++vi.mock('../../provider-added-card/model-auth-dropdown/credits-exhausted-alert', () => ({+ default: ({ hasApiKeyFallback }: { hasApiKeyFallback: boolean }) => (+ <div data-testid="credits-exhausted-alert" data-has-api-key-fallback={String(hasApiKeyFallback)} />+ ),+}))++vi.mock('next-themes', () => ({+ useTheme: () => ({ theme: 'light' }),+}))++vi.mock('@/config', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/config')>()+ return { ...actual, IS_CLOUD_EDITION: true }+})++const mockInstallMutateAsync = vi.hoisted(() => vi.fn())+vi.mock('@/service/use-plugins', () => ({+ useInstallPackageFromMarketPlace: () => ({ mutateAsync: mockInstallMutateAsync }),+}))++const mockRefreshPluginList = vi.hoisted(() => vi.fn())+vi.mock('@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list', () => ({+ default: () => ({ refreshPluginList: mockRefreshPluginList }),+}))++const mockCheck = vi.hoisted(() => vi.fn())+vi.mock('@/app/components/plugins/install-plugin/base/check-task-status', () => ({+ default: () => ({ check: mockCheck }),+}))++vi.mock('@/utils/var', () => ({+ getMarketplaceUrl: vi.fn(() => 'https://marketplace.example.com'),+}))++vi.mock('../../utils', async () => {+ const actual = await vi.importActual<typeof import('../../utils')>('../../utils')+ return {+ ...actual,+ MODEL_PROVIDER_QUOTA_GET_PAID: ['test-openai', 'test-anthropic'],+ providerIconMap: {+ 'test-openai': ({ className }: { className?: string }) => <span className={className}>OAI</span>,+ 'test-anthropic': ({ className }: { className?: string }) => <span className={className}>ANT</span>,+ },+ modelNameMap: {+ 'test-openai': 'TestOpenAI',+ 'test-anthropic': 'TestAnthropic',+ },+ providerKeyToPluginId: {+ 'test-openai': 'langgenius/openai',+ 'test-anthropic': 'langgenius/anthropic',+ },+ }+})+const makeModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({model: 'gpt-4',label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' },@@ -55,18 +150,40 @@ const makeModel = (overrides: Partial<Model> = {}): Model => ({...overrides,})-describe('Popup', () => {- let closeActiveTooltipSpy: ReturnType<typeof vi.spyOn>+const makeContextProvider = (overrides: Partial<MockContextProvider> = {}): MockContextProvider => ({+ provider: 'test-openai',+ label: { en_US: 'Test OpenAI', zh_Hans: 'Test OpenAI' },+ icon_small: { en_US: '', zh_Hans: '' },+ icon_small_dark: { en_US: '', zh_Hans: '' },+ custom_configuration: {+ status: 'no-configure',+ } as MockContextProvider['custom_configuration'],+ system_configuration: {+ enabled: false,+ } as MockContextProvider['system_configuration'],+ ...overrides,+})+describe('Popup', () => {beforeEach(() => {vi.clearAllMocks()mockLanguage = 'en_US'mockSupportFunctionCall.mockReturnValue(true)- closeActiveTooltipSpy = vi.spyOn(tooltipManager, 'closeActiveTooltip')+ mockMarketplacePlugins.current = []+ mockMarketplacePlugins.isLoading = false+ mockContextModelProviders.current = []+ mockTrialModels.current = ['test-openai', 'test-anthropic']+ Object.assign(mockTrialCredits, {+ credits: 200,+ totalCredits: 200,+ isExhausted: false,+ isLoading: false,+ nextCreditResetDate: undefined,+ })})it('should filter models by search and allow clearing search', () => {- render(+ const { container } = render(<PopupmodelList={[makeModel()]}onSelect={vi.fn()}@@ -78,11 +195,39 @@ describe('Popup', () => {const input = screen.getByPlaceholderText('datasetSettings.form.searchModel')fireEvent.change(input, { target: { value: 'not-found' } })- expect(screen.getByText('No model found for “not-found”')).toBeInTheDocument()+ expect(screen.getByText('No model found for \u201Cnot-found\u201D')).toBeInTheDocument()- fireEvent.change(input, { target: { value: '' } })+ const clearIcon = container.querySelector('.i-custom-vender-solid-general-x-circle')+ expect(clearIcon).toBeInTheDocument()+ fireEvent.click(clearIcon!)expect((input as HTMLInputElement).value).toBe('')- expect(screen.getByText('openai')).toBeInTheDocument()+ })++ it('should not show compatible-only helper text when no scope features are applied', () => {+ render(+ <Popup+ modelList={[makeModel()]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ expect(screen.queryByText('common.modelProvider.selector.onlyCompatibleModelsShown')).not.toBeInTheDocument()+ })++ it('should show compatible-only helper banner when scope features are applied', () => {+ const { container } = render(+ <Popup+ modelList={[makeModel()]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ scopeFeatures={[ModelFeatureEnum.vision]}+ />,+ )++ expect(screen.getByTestId('compatible-models-banner')).toBeInTheDocument()+ expect(screen.getByText('common.modelProvider.selector.onlyCompatibleModelsShown')).toBeInTheDocument()+ expect(container.querySelector('.i-ri-information-2-fill')).toBeInTheDocument()})it('should filter by scope features including toolCall and non-toolCall checks', () => {@@ -90,7 +235,6 @@ describe('Popup', () => {makeModel({ models: [makeModelItem({ features: [ModelFeatureEnum.toolCall, ModelFeatureEnum.vision] })] }),]- // When tool-call support is missing, it should be filtered out.mockSupportFunctionCall.mockReturnValue(false)const { unmount } = render(<Popup@@ -100,9 +244,8 @@ describe('Popup', () => {scopeFeatures={[ModelFeatureEnum.toolCall, ModelFeatureEnum.vision]}/>,)- expect(screen.getByText('No model found for “”')).toBeInTheDocument()+ expect(screen.getByText('No model found for \u201C\u201D')).toBeInTheDocument()- // When tool-call support exists, the non-toolCall feature check should also pass.unmount()mockSupportFunctionCall.mockReturnValue(true)const { unmount: unmount2 } = render(@@ -126,7 +269,6 @@ describe('Popup', () => {)expect(screen.getByText('openai')).toBeInTheDocument()- // When features are missing, non-toolCall feature checks should fail.unmount3()render(<Popup@@ -136,15 +278,23 @@ describe('Popup', () => {scopeFeatures={[ModelFeatureEnum.vision]}/>,)- expect(screen.getByText('No model found for “”')).toBeInTheDocument()+ expect(screen.getByText('No model found for \u201C\u201D')).toBeInTheDocument()})- it('should match labels from other languages when current language key is missing', () => {+ it('should match model labels from fallback languages when current language key is missing', () => {mockLanguage = 'fr_FR'render(<Popup- modelList={[makeModel()]}+ modelList={[+ makeModel({+ models: [+ makeModelItem({+ label: { en_US: 'OpenAI GPT', zh_Hans: 'OpenAI GPT' },+ }),+ ],+ }),+ ]}onSelect={vi.fn()}onHide={vi.fn()}/>,@@ -152,32 +302,55 @@ describe('Popup', () => {fireEvent.change(screen.getByPlaceholderText('datasetSettings.form.searchModel'),- { target: { value: 'gpt' } },+ { target: { value: 'openai' } },)expect(screen.getByText('openai')).toBeInTheDocument()})- it('should filter out model when features array exists but does not include required scopeFeature', () => {- const modelWithToolCallOnly = makeModel({- models: [makeModelItem({ features: [ModelFeatureEnum.toolCall] })],+ it('should show credits exhausted alert when an exhausted provider supports credits', () => {+ Object.assign(mockTrialCredits, {+ credits: 0,+ totalCredits: 200,+ isExhausted: true,})+ mockContextModelProviders.current = [+ makeContextProvider({+ provider: 'test-openai',+ system_configuration: {+ enabled: true,+ } as MockContextProvider['system_configuration'],+ }),+ ]render(<Popup- modelList={[modelWithToolCallOnly]}+ modelList={[makeModel()]}onSelect={vi.fn()}onHide={vi.fn()}- scopeFeatures={[ModelFeatureEnum.vision]}/>,)- // The model item should be filtered out because it has toolCall but not vision- expect(screen.queryByText('openai')).not.toBeInTheDocument()+ expect(screen.getByTestId('credits-exhausted-alert')).toHaveAttribute('data-has-api-key-fallback', 'false')})- it('should close tooltip on scroll', () => {- const { container } = render(+ it('should not show credits exhausted alert when only non-trial system providers are exhausted', () => {+ Object.assign(mockTrialCredits, {+ credits: 0,+ totalCredits: 200,+ isExhausted: true,+ })+ mockTrialModels.current = ['test-anthropic']+ mockContextModelProviders.current = [+ makeContextProvider({+ provider: 'test-openai',+ system_configuration: {+ enabled: true,+ } as MockContextProvider['system_configuration'],+ }),+ ]++ render(<PopupmodelList={[makeModel()]}onSelect={vi.fn()}@@ -185,11 +358,28 @@ describe('Popup', () => {/>,)- fireEvent.scroll(container.firstElementChild as HTMLElement)- expect(closeActiveTooltipSpy).toHaveBeenCalled()+ expect(screen.queryByTestId('credits-exhausted-alert')).not.toBeInTheDocument()})- it('should open provider settings when clicking footer link', () => {+ it('should not mark api key fallback for non-trial system providers', () => {+ Object.assign(mockTrialCredits, {+ credits: 0,+ totalCredits: 200,+ isExhausted: true,+ })+ mockTrialModels.current = ['test-anthropic']+ mockContextModelProviders.current = [+ makeContextProvider({+ provider: 'test-openai',+ custom_configuration: {+ status: 'active',+ } as MockContextProvider['custom_configuration'],+ system_configuration: {+ enabled: true,+ } as MockContextProvider['system_configuration'],+ }),+ ]+render(<PopupmodelList={[makeModel()]}@@ -198,41 +388,258 @@ describe('Popup', () => {/>,)- fireEvent.click(screen.getByText('common.model.settingsLink'))+ expect(screen.queryByTestId('credits-exhausted-alert')).not.toBeInTheDocument()+ })+ it('should open provider settings when clicking footer link', () => {+ const onHide = vi.fn()+ render(+ <Popup+ modelList={[makeModel()]}+ onSelect={vi.fn()}+ onHide={onHide}+ />,+ )++ fireEvent.click(screen.getByText('common.modelProvider.selector.modelProviderSettings'))++ expect(onHide).toHaveBeenCalled()expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({payload: 'provider',})})- it('should call onHide when footer settings link is clicked', () => {- const mockOnHide = vi.fn()+ it('should show empty state when no providers are configured', () => {+ const onHide = vi.fn()render(<Popup- modelList={[makeModel()]}+ modelList={[]}onSelect={vi.fn()}- onHide={mockOnHide}+ onHide={onHide}/>,)- fireEvent.click(screen.getByText('common.model.settingsLink'))+ expect(screen.getByText(/modelProvider\.selector\.noProviderConfigured(?!Desc)/)).toBeInTheDocument()+ expect(screen.getByText(/modelProvider\.selector\.noProviderConfiguredDesc/)).toBeInTheDocument()- expect(mockOnHide).toHaveBeenCalled()+ fireEvent.click(screen.getByText(/modelProvider\.selector\.configure/))+ expect(onHide).toHaveBeenCalled()+ expect(mockSetShowAccountSettingModal).toHaveBeenCalledWith({+ payload: 'provider',+ })})- it('should match model label when searchText is non-empty and label key exists for current language', () => {+ it('should render marketplace providers that are not installed', () => {+ mockContextModelProviders.current = [makeContextProvider({ provider: 'test-openai' })]+render(<Popup- modelList={[makeModel()]}+ modelList={[]}onSelect={vi.fn()}onHide={vi.fn()}/>,)- // GPT-4 label has en_US key, so modelItem.label[language] is defined- const input = screen.getByPlaceholderText('datasetSettings.form.searchModel')- fireEvent.change(input, { target: { value: 'gpt' } })+ expect(screen.queryByText('TestOpenAI')).not.toBeInTheDocument()+ expect(screen.getByText('TestAnthropic')).toBeInTheDocument()+ expect(screen.getByText(/modelProvider\.selector\.fromMarketplace/)).toBeInTheDocument()+ expect(screen.getByText(/modelProvider\.selector\.discoverMoreInMarketplace/)).toBeInTheDocument()+ })- expect(screen.getByText('openai')).toBeInTheDocument()+ it('should show installed marketplace providers without models when AI credits are available', () => {+ mockContextModelProviders.current = [makeContextProvider({+ provider: 'test-anthropic',+ system_configuration: {+ enabled: true,+ } as MockContextProvider['system_configuration'],+ })]++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ expect(screen.getByText('test-anthropic')).toBeInTheDocument()+ expect(screen.getByText('TestOpenAI')).toBeInTheDocument()+ })++ it('should hide installed marketplace providers without models when AI credits are exhausted', () => {+ Object.assign(mockTrialCredits, {+ credits: 0,+ totalCredits: 200,+ isExhausted: true,+ })+ mockContextModelProviders.current = [makeContextProvider({+ provider: 'test-anthropic',+ system_configuration: {+ enabled: true,+ } as MockContextProvider['system_configuration'],+ })]++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ expect(screen.queryByText('test-anthropic')).not.toBeInTheDocument()+ expect(screen.queryByText('TestAnthropic')).not.toBeInTheDocument()+ expect(screen.getByText('TestOpenAI')).toBeInTheDocument()+ })++ it('should toggle marketplace section collapse', () => {+ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ expect(screen.getByText('TestOpenAI')).toBeInTheDocument()++ fireEvent.click(screen.getByText(/modelProvider\.selector\.fromMarketplace/))++ expect(screen.queryByText('TestOpenAI')).not.toBeInTheDocument()++ fireEvent.click(screen.getByText(/modelProvider\.selector\.fromMarketplace/))++ expect(screen.getByText('TestOpenAI')).toBeInTheDocument()+ })++ it('should install plugin when clicking install button', async () => {+ mockMarketplacePlugins.current = [+ { plugin_id: 'langgenius/openai', latest_package_identifier: 'langgenius/openai:1.0.0' },+ ]+ mockInstallMutateAsync.mockResolvedValue({ all_installed: true, task_id: 'task-1' })++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ const installButtons = screen.getAllByText(/common\.modelProvider\.selector\.install/)+ fireEvent.click(installButtons[0])++ await waitFor(() => {+ expect(mockInstallMutateAsync).toHaveBeenCalledWith('langgenius/openai:1.0.0')+ })+ expect(mockRefreshPluginList).toHaveBeenCalled()+ })++ it('should handle install failure gracefully', async () => {+ mockMarketplacePlugins.current = [+ { plugin_id: 'langgenius/openai', latest_package_identifier: 'langgenius/openai:1.0.0' },+ ]+ mockInstallMutateAsync.mockRejectedValue(new Error('Install failed'))++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ const installButtons = screen.getAllByText(/common\.modelProvider\.selector\.install/)+ fireEvent.click(installButtons[0])++ await waitFor(() => {+ expect(mockInstallMutateAsync).toHaveBeenCalled()+ })++ // Should not crash, install buttons should still be available+ expect(screen.getAllByText(/common\.modelProvider\.selector\.install/).length).toBeGreaterThan(0)+ })++ it('should run checkTaskStatus when not all_installed', async () => {+ mockMarketplacePlugins.current = [+ { plugin_id: 'langgenius/openai', latest_package_identifier: 'langgenius/openai:1.0.0' },+ ]+ mockInstallMutateAsync.mockResolvedValue({ all_installed: false, task_id: 'task-1' })+ mockCheck.mockResolvedValue(undefined)++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ const installButtons = screen.getAllByText(/common\.modelProvider\.selector\.install/)+ fireEvent.click(installButtons[0])++ await waitFor(() => {+ expect(mockCheck).toHaveBeenCalledWith({+ taskId: 'task-1',+ pluginUniqueIdentifier: 'langgenius/openai:1.0.0',+ })+ })+ expect(mockRefreshPluginList).toHaveBeenCalled()+ })++ it('should skip install requests when marketplace plugins are still loading', async () => {+ mockMarketplacePlugins.current = [+ { plugin_id: 'langgenius/openai', latest_package_identifier: 'langgenius/openai:1.0.0' },+ ]+ mockMarketplacePlugins.isLoading = true++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ fireEvent.click(screen.getAllByText(/common\.modelProvider\.selector\.install/)[0])++ await waitFor(() => {+ expect(mockInstallMutateAsync).not.toHaveBeenCalled()+ })+ })++ it('should skip install requests when the marketplace plugin cannot be found', async () => {+ mockMarketplacePlugins.current = []++ render(+ <Popup+ modelList={[]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ fireEvent.click(screen.getAllByText(/common\.modelProvider\.selector\.install/)[0])++ await waitFor(() => {+ expect(mockInstallMutateAsync).not.toHaveBeenCalled()+ })+ })++ it('should sort the selected provider to the top when a default model is provided', () => {+ render(+ <Popup+ defaultModel={{ provider: 'anthropic', model: 'claude-3' }}+ modelList={[+ makeModel({ provider: 'openai', label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' } }),+ makeModel({ provider: 'anthropic', label: { en_US: 'Anthropic', zh_Hans: 'Anthropic' } }),+ ]}+ onSelect={vi.fn()}+ onHide={vi.fn()}+ />,+ )++ const providerLabels = screen.getAllByText(/openai|anthropic/)+ expect(providerLabels[0]).toHaveTextContent('anthropic')})})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/deprecated-model-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/deprecated-model-trigger.tsxdeleted file mode 100644index 7809e955c69..00000000000--- a/web/app/components/header/account-setting/model-provider-page/model-selector/deprecated-model-trigger.tsx+++ /dev/null@@ -1,54 +0,0 @@-import type { FC } from 'react'-import { useTranslation } from 'react-i18next'-import { AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'-import Tooltip from '@/app/components/base/tooltip'-import { useProviderContext } from '@/context/provider-context'-import { cn } from '@/utils/classnames'-import ModelIcon from '../model-icon'--type ModelTriggerProps = {- modelName: string- providerName: string- className?: string- showWarnIcon?: boolean- contentClassName?: string-}-const ModelTrigger: FC<ModelTriggerProps> = ({- modelName,- providerName,- className,- showWarnIcon,- contentClassName,-}) => {- const { t } = useTranslation()- const { modelProviders } = useProviderContext()- const currentProvider = modelProviders.find(provider => provider.provider === providerName)-- return (- <div- className={cn('group box-content flex h-8 grow cursor-pointer items-center gap-1 rounded-lg bg-components-input-bg-disabled p-[3px] pl-1', className)}- >- <div className={cn('flex w-full items-center', contentClassName)}>- <div className="flex min-w-0 flex-1 items-center gap-1 py-[1px]">- <ModelIcon- className="h-4 w-4"- provider={currentProvider}- modelName={modelName}- />- <div className="system-sm-regular truncate text-components-input-text-filled">- {modelName}- </div>- </div>- <div className="flex shrink-0 items-center justify-center">- {showWarnIcon && (- <Tooltip popupContent={t('modelProvider.deprecated', { ns: 'common' })}>- <AlertTriangle className="h-4 w-4 text-text-warning-secondary" />- </Tooltip>- )}- </div>- </div>- </div>- )-}--export default ModelTriggerdiff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/empty-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/empty-trigger.tsxdeleted file mode 100644index 4989e9e26cc..00000000000--- a/web/app/components/header/account-setting/model-provider-page/model-selector/empty-trigger.tsx+++ /dev/null@@ -1,42 +0,0 @@-import type { FC } from 'react'-import { RiEqualizer2Line } from '@remixicon/react'-import { useTranslation } from 'react-i18next'-import { CubeOutline } from '@/app/components/base/icons/src/vender/line/shapes'-import { cn } from '@/utils/classnames'--type ModelTriggerProps = {- open: boolean- className?: string-}-const ModelTrigger: FC<ModelTriggerProps> = ({- open,- className,-}) => {- const { t } = useTranslation()- return (- <div- className={cn(- 'flex cursor-pointer items-center gap-0.5 rounded-lg bg-components-input-bg-normal p-1 hover:bg-components-input-bg-hover',- open && 'bg-components-input-bg-hover',- className,- )}- >- <div className="flex grow items-center">- <div className="mr-1.5 flex h-4 w-4 items-center justify-center rounded-[5px] border border-dashed border-divider-regular">- <CubeOutline className="h-3 w-3 text-text-quaternary" />- </div>- <div- className="truncate text-[13px] text-text-tertiary"- title="Configure model"- >- {t('detailPanel.configureModel', { ns: 'plugin' })}- </div>- </div>- <div className="flex h-4 w-4 shrink-0 items-center justify-center">- <RiEqualizer2Line className="h-3.5 w-3.5 text-text-tertiary" />- </div>- </div>- )-}--export default ModelTriggerdiff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsxindex 50b56826eb1..44392a70a57 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/index.tsx@@ -7,15 +7,12 @@ import type {} from '../declarations'import { useState } from 'react'import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'-import { cn } from '@/utils/classnames'+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'import { useCurrentProviderAndModel } from '../hooks'-import DeprecatedModelTrigger from './deprecated-model-trigger'-import EmptyTrigger from './empty-trigger'-import ModelTrigger from './model-trigger'+import ModelSelectorTrigger from './model-selector-trigger'import Popup from './popup'type ModelSelectorProps = {@@ -24,6 +21,7 @@ type ModelSelectorProps = {triggerClassName?: stringpopupClassName?: stringonSelect?: (model: DefaultModel) => void+ onHide?: () => voidreadonly?: booleanscopeFeatures?: ModelFeatureEnum[]deprecatedClassName?: string@@ -35,10 +33,11 @@ const ModelSelector: FC<ModelSelectorProps> = ({triggerClassName,popupClassName,onSelect,+ onHide,readonly,scopeFeatures = [],deprecatedClassName,- showDeprecatedWarnIcon = false,+ showDeprecatedWarnIcon = true,}) => {const [open, setOpen] = useState(false)const {@@ -56,67 +55,54 @@ const ModelSelector: FC<ModelSelectorProps> = ({onSelect({ provider, model: model.model })}- const handleToggle = () => {- if (readonly)- return-- setOpen(v => !v)- }-return (- <PortalToFollowElem+ <Popoveropen={open}- onOpenChange={setOpen}- placement="bottom-start"- offset={4}+ onOpenChange={(newOpen) => {+ if (readonly)+ return+ setOpen(newOpen)+ }}>- <div className={cn('relative')}>- <PortalToFollowElemTrigger- onClick={handleToggle}- className="block"- >- {- currentModel && currentProvider && (- <ModelTrigger- open={open}- provider={currentProvider}- model={currentModel}- className={triggerClassName}- readonly={readonly}- />- )- }- {- !currentModel && defaultModel && (- <DeprecatedModelTrigger- modelName={defaultModel?.model || ''}- providerName={defaultModel?.provider || ''}- className={triggerClassName}- showWarnIcon={showDeprecatedWarnIcon}- contentClassName={deprecatedClassName}- />- )- }- {- !defaultModel && (- <EmptyTrigger- open={open}- className={triggerClassName}- />- )- }- </PortalToFollowElemTrigger>- <PortalToFollowElemContent className={`z-[1002] ${popupClassName}`}>- <Popup- defaultModel={defaultModel}- modelList={modelList}- onSelect={handleSelect}- scopeFeatures={scopeFeatures}- onHide={() => setOpen(false)}- />- </PortalToFollowElemContent>- </div>- </PortalToFollowElem>+ <PopoverTrigger+ render={(+ <button+ type="button"+ className="block w-full border-0 bg-transparent p-0 text-left"+ disabled={readonly}+ >+ <ModelSelectorTrigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ defaultModel={defaultModel}+ open={open}+ readonly={readonly}+ className={triggerClassName}+ deprecatedClassName={deprecatedClassName}+ showDeprecatedWarnIcon={showDeprecatedWarnIcon}+ />+ </button>+ )}+ />+ <PopoverContent+ placement="bottom-start"+ sideOffset={4}+ className={popupClassName}+ popupClassName="overflow-hidden rounded-lg"+ popupProps={{ style: { minWidth: '320px', width: 'var(--anchor-width, auto)' } }}+ >+ <Popup+ defaultModel={defaultModel}+ modelList={modelList}+ onSelect={handleSelect}+ scopeFeatures={scopeFeatures}+ onHide={() => {+ setOpen(false)+ onHide?.()+ }}+ />+ </PopoverContent>+ </Popover>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.spec.tsxnew file mode 100644index 00000000000..ff4a38a9a3d--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.spec.tsx@@ -0,0 +1,290 @@+import type { Model, ModelItem } from '../declarations'+import { render, screen } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import {+ ConfigurationMethodEnum,+ ModelFeatureEnum,+ ModelStatusEnum,+ ModelTypeEnum,+} from '../declarations'+import ModelSelectorTrigger from './model-selector-trigger'++const mockUseProviderContext = vi.hoisted(() => vi.fn())+const mockUseCredentialPanelState = vi.hoisted(() => vi.fn())+vi.mock('@/context/provider-context', () => ({+ useProviderContext: mockUseProviderContext,+}))+vi.mock('../provider-added-card/use-credential-panel-state', () => ({+ useCredentialPanelState: mockUseCredentialPanelState,+}))++const createModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({+ model: 'gpt-4',+ label: { en_US: 'GPT-4', zh_Hans: 'GPT-4' },+ model_type: ModelTypeEnum.textGeneration,+ features: [ModelFeatureEnum.vision],+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status: ModelStatusEnum.active,+ model_properties: { mode: 'chat', context_size: 4096 },+ load_balancing_enabled: false,+ ...overrides,+})++const createModel = (overrides: Partial<Model> = {}): Model => ({+ provider: 'openai',+ icon_small: {+ en_US: 'https://example.com/openai-light.png',+ zh_Hans: 'https://example.com/openai-light.png',+ },+ icon_small_dark: {+ en_US: 'https://example.com/openai-dark.png',+ zh_Hans: 'https://example.com/openai-dark.png',+ },+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [createModelItem()],+ status: ModelStatusEnum.active,+ ...overrides,+})++describe('ModelSelectorTrigger', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseProviderContext.mockReturnValue({+ modelProviders: [createModel()],+ })+ mockUseCredentialPanelState.mockReturnValue({+ variant: 'credits-active',+ priority: 'credits',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: false,+ isCreditsExhausted: false,+ credentialName: undefined,+ credits: 100,+ })+ })++ describe('Rendering', () => {+ it('should render empty state when no model is selected', () => {+ const { container } = render(<ModelSelectorTrigger />)++ expect(screen.getByText('plugin.detailPanel.configureModel')).toBeInTheDocument()+ expect(container.querySelector('.i-ri-arrow-down-s-line')).toBeInTheDocument()+ expect(container.firstElementChild).toHaveClass('bg-components-input-bg-normal')+ })++ it('should render selected model details when model is active', () => {+ const currentProvider = createModel()+ const currentModel = createModelItem()+ const { container } = render(+ <ModelSelectorTrigger+ currentProvider={currentProvider}+ currentModel={currentModel}+ />,+ )++ expect(screen.getByText('GPT-4')).toBeInTheDocument()+ expect(screen.getByText('CHAT')).toBeInTheDocument()+ expect(container.querySelector('.i-ri-arrow-down-s-line')).toBeInTheDocument()+ expect(container.firstElementChild).toHaveClass('bg-components-input-bg-normal')+ })++ it('should render deprecated default model and disabled style when selection is missing', () => {+ const { container } = render(+ <ModelSelectorTrigger+ defaultModel={{ provider: 'openai', model: 'legacy-model' }}+ />,+ )++ expect(screen.getByText('legacy-model')).toBeInTheDocument()+ expect(container.firstElementChild).toHaveClass('bg-components-input-bg-disabled')+ expect(container.querySelector('.i-ri-arrow-down-s-line')).not.toBeInTheDocument()+ })+ })++ describe('Props', () => {+ it('should apply custom className to root element', () => {+ const { container } = render(<ModelSelectorTrigger className="custom-trigger" />)++ expect(container.firstElementChild).toHaveClass('custom-trigger')+ })++ it('should apply open background style when open is true and model is active', () => {+ const { container } = render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem()}+ open+ />,+ )++ expect(container.firstElementChild).toHaveClass('bg-components-input-bg-hover')+ })++ it('should hide the expand arrow when readonly is true', () => {+ const { container } = render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem()}+ readonly+ />,+ )++ expect(container.querySelector('.i-ri-arrow-down-s-line')).not.toBeInTheDocument()+ })+ })++ describe('Status Handling', () => {+ it('should show status badge when selected model is not active and not readonly', () => {+ render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem({ status: ModelStatusEnum.noConfigure })}+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.configureRequired')).toBeInTheDocument()+ })++ it('should apply credits exhausted badge style when model quota is exceeded', () => {+ mockUseCredentialPanelState.mockReturnValue({+ variant: 'credits-exhausted',+ priority: 'credits',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: false,+ isCreditsExhausted: true,+ credentialName: undefined,+ credits: 0,+ })++ render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem()}+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.creditsExhausted').parentElement).toHaveClass('bg-components-badge-bg-dimm')+ expect(screen.queryByText('CHAT')).not.toBeInTheDocument()+ })++ it('should hide model meta when api key is unavailable', () => {+ mockUseCredentialPanelState.mockReturnValue({+ variant: 'api-unavailable',+ priority: 'apiKey',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: true,+ isCreditsExhausted: false,+ credentialName: 'Primary Key',+ credits: 0,+ })++ render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem()}+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.apiKeyUnavailable')).toBeInTheDocument()+ expect(screen.queryByText('CHAT')).not.toBeInTheDocument()+ })++ it('should show disabled badge when selected model is disabled', () => {+ render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem({ status: ModelStatusEnum.disabled })}+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.disabled')).toBeInTheDocument()+ expect(screen.queryByText('CHAT')).not.toBeInTheDocument()+ })++ it('should not show status badge when selected model is readonly', () => {+ render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem({ status: ModelStatusEnum.noConfigure })}+ readonly+ />,+ )++ expect(screen.queryByText('common.modelProvider.selector.configureRequired')).not.toBeInTheDocument()+ })++ it('should show incompatible tooltip when hovering no-permission status badge', async () => {+ const user = userEvent.setup()+ render(+ <ModelSelectorTrigger+ currentProvider={createModel()}+ currentModel={createModelItem({ status: ModelStatusEnum.noPermission })}+ />,+ )++ expect(screen.queryByText('CHAT')).not.toBeInTheDocument()+ await user.hover(screen.getByText('common.modelProvider.selector.incompatible'))++ expect(await screen.findByText('common.modelProvider.selector.incompatibleTip')).toBeInTheDocument()+ })+ })++ describe('Edge Cases', () => {+ it('should show incompatible badge for deprecated selection', async () => {+ const user = userEvent.setup()+ render(+ <ModelSelectorTrigger+ defaultModel={{ provider: 'openai', model: 'legacy-model' }}+ />,+ )++ expect(screen.getByText('common.modelProvider.selector.incompatible')).toBeInTheDocument()+ await user.hover(screen.getByText('common.modelProvider.selector.incompatible'))++ expect(await screen.findByText('common.modelProvider.selector.incompatibleTip')).toBeInTheDocument()+ })++ it('should show credits exhausted badge for deprecated selection when ai credits are exhausted without api key', async () => {+ const user = userEvent.setup()+ mockUseCredentialPanelState.mockImplementation(provider => ({+ variant: provider ? 'no-usage' : 'credits-active',+ priority: provider ? 'apiKey' : 'credits',+ supportsCredits: !!provider,+ showPrioritySwitcher: true,+ hasCredentials: false,+ isCreditsExhausted: !!provider,+ credentialName: undefined,+ credits: provider ? 0 : 100,+ }))++ render(+ <ModelSelectorTrigger+ defaultModel={{ provider: 'openai', model: 'legacy-model' }}+ />,+ )++ expect(mockUseCredentialPanelState).toHaveBeenCalledWith(expect.objectContaining({ provider: 'openai' }))+ expect(screen.getByText('common.modelProvider.selector.creditsExhausted')).toBeInTheDocument()+ await user.hover(screen.getByText('common.modelProvider.selector.creditsExhausted'))++ expect(await screen.findByText('common.modelProvider.selector.creditsExhaustedTip')).toBeInTheDocument()+ })++ it('should render fallback icon when deprecated provider is not found', () => {+ mockUseProviderContext.mockReturnValue({+ modelProviders: [],+ })+ const { container } = render(+ <ModelSelectorTrigger+ defaultModel={{ provider: 'unknown-provider', model: 'legacy-model' }}+ />,+ )++ expect(container.querySelector('img[alt="model-icon"]')).not.toBeInTheDocument()+ expect(container.querySelector('svg')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsxnew file mode 100644index 00000000000..75dbd6559c5--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/model-selector-trigger.tsx@@ -0,0 +1,175 @@+import type { FC } from 'react'+import type {+ DefaultModel,+ Model,+ ModelItem,+} from '../declarations'+import { useTranslation } from 'react-i18next'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'+import { useProviderContext } from '@/context/provider-context'+import { cn } from '@/utils/classnames'+import {+ DERIVED_MODEL_STATUS_BADGE_I18N,+ DERIVED_MODEL_STATUS_TOOLTIP_I18N,+ deriveModelStatus,+} from '../derive-model-status'+import ModelIcon from '../model-icon'+import ModelName from '../model-name'+import { useCredentialPanelState } from '../provider-added-card/use-credential-panel-state'++type ModelSelectorTriggerProps = {+ currentProvider?: Model+ currentModel?: ModelItem+ defaultModel?: DefaultModel+ open?: boolean+ readonly?: boolean+ className?: string+ deprecatedClassName?: string+ showDeprecatedWarnIcon?: boolean+}++const ModelSelectorTrigger: FC<ModelSelectorTriggerProps> = ({+ currentProvider,+ currentModel,+ defaultModel,+ open,+ readonly,+ className,+ deprecatedClassName,+ showDeprecatedWarnIcon = true,+}) => {+ const { t } = useTranslation()+ const { modelProviders } = useProviderContext()++ const isSelected = !!currentProvider && !!currentModel+ const isDeprecated = !isSelected && !!defaultModel+ const isEmpty = !isSelected && !defaultModel+ const selectedProvider = isSelected+ ? modelProviders.find(provider => provider.provider === currentProvider.provider)+ : undefined+ const deprecatedProvider = isDeprecated+ ? modelProviders.find(p => p.provider === defaultModel.provider)+ : undefined+ const resolvedProvider = isSelected ? selectedProvider : deprecatedProvider+ const selectedProviderState = useCredentialPanelState(resolvedProvider)++ const status = deriveModelStatus(+ isSelected ? currentModel?.model : defaultModel?.model,+ isSelected ? currentProvider?.provider : defaultModel?.provider,+ resolvedProvider,+ currentModel,+ selectedProviderState,+ )++ const isActive = status === 'active'+ const isDisabled = status !== 'active' && status !== 'empty'+ const statusI18nKey = DERIVED_MODEL_STATUS_BADGE_I18N[status as keyof typeof DERIVED_MODEL_STATUS_BADGE_I18N]+ const tooltipI18nKey = DERIVED_MODEL_STATUS_TOOLTIP_I18N[status as keyof typeof DERIVED_MODEL_STATUS_TOOLTIP_I18N]+ const statusLabel = statusI18nKey ? t(statusI18nKey, { ns: 'common' }) : null+ const tooltipLabel = tooltipI18nKey ? t(tooltipI18nKey, { ns: 'common' }) : null+ const isCreditsExhausted = status === 'credits-exhausted'+ const shouldShowModelMeta = status === 'active'+ const deprecatedStatusLabel = statusLabel || t('modelProvider.selector.incompatible', { ns: 'common' })+ const deprecatedTooltipLabel = tooltipLabel || t('modelProvider.selector.incompatibleTip', { ns: 'common' })++ return (+ <div+ className={cn(+ 'group flex h-8 items-center gap-0.5 rounded-lg p-1',+ isDisabled+ ? 'bg-components-input-bg-disabled'+ : 'bg-components-input-bg-normal',+ !readonly && !isDisabled && 'cursor-pointer hover:bg-components-input-bg-hover',+ open && !isDisabled && 'bg-components-input-bg-hover',+ className,+ )}+ >+ {isEmpty+ ? (+ <div className="flex h-6 w-6 items-center justify-center">+ <div className="flex h-5 w-5 items-center justify-center rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-subtle">+ <span className="i-ri-brain-2-line h-3.5 w-3.5 text-text-quaternary" />+ </div>+ </div>+ )+ : (+ <ModelIcon+ className="p-0.5"+ provider={isSelected ? currentProvider : deprecatedProvider}+ modelName={isSelected ? currentModel.model : defaultModel?.model}+ />+ )}++ <div className={cn('flex grow items-center gap-1 truncate px-1 py-[3px]', isDeprecated && deprecatedClassName)}>+ {isSelected && (+ <ModelName+ className="grow"+ modelItem={currentModel}+ showMode={shouldShowModelMeta}+ showFeatures={shouldShowModelMeta}+ />+ )}+ {isDeprecated && (+ <div className="grow truncate text-components-input-text-filled system-sm-regular">+ {defaultModel.model}+ </div>+ )}+ {isEmpty && (+ <div className="grow truncate text-[13px] text-text-quaternary">+ {t('detailPanel.configureModel', { ns: 'plugin' })}+ </div>+ )}++ {isSelected && !readonly && !isActive && statusI18nKey && (+ <Tooltip>+ <TooltipTrigger+ disabled={!tooltipLabel}+ render={(+ <div+ className={cn(+ 'flex shrink-0 items-center gap-[3px] rounded-md border border-text-warning px-[5px] py-0.5',+ isCreditsExhausted && 'min-w-[20px] justify-center bg-components-badge-bg-dimm',+ )}+ >+ <span className="i-ri-alert-fill h-3 w-3 text-text-warning" />+ <span className="whitespace-nowrap text-text-warning system-xs-medium">+ {statusLabel}+ </span>+ </div>+ )}+ />+ {tooltipLabel && (+ <TooltipContent placement="top">+ {tooltipLabel}+ </TooltipContent>+ )}+ </Tooltip>+ )}++ {isDeprecated && showDeprecatedWarnIcon && (+ <Tooltip>+ <TooltipTrigger+ render={(+ <div className="flex shrink-0 items-center gap-[3px] rounded-md border border-text-warning bg-components-badge-bg-dimm px-[5px] py-0.5">+ <span className="i-ri-alert-fill h-3 w-3 text-text-warning" />+ <span className="whitespace-nowrap text-text-warning system-xs-medium">+ {deprecatedStatusLabel}+ </span>+ </div>+ )}+ />+ <TooltipContent placement="top">+ {deprecatedTooltipLabel}+ </TooltipContent>+ </Tooltip>+ )}++ {!readonly && (isActive || isEmpty) && (+ <span className="i-ri-arrow-down-s-line h-3.5 w-3.5 shrink-0 text-text-tertiary" />+ )}+ </div>+ </div>+ )+}++export default ModelSelectorTriggerdiff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/model-trigger.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/model-trigger.tsxdeleted file mode 100644index b44dbfefb16..00000000000--- a/web/app/components/header/account-setting/model-provider-page/model-selector/model-trigger.tsx+++ /dev/null@@ -1,78 +0,0 @@-import type { FC } from 'react'-import type {- Model,- ModelItem,-} from '../declarations'-import { RiArrowDownSLine } from '@remixicon/react'-import { AlertTriangle } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'-import Tooltip from '@/app/components/base/tooltip'-import { cn } from '@/utils/classnames'-import {- MODEL_STATUS_TEXT,- ModelStatusEnum,-} from '../declarations'-import { useLanguage } from '../hooks'-import ModelIcon from '../model-icon'-import ModelName from '../model-name'--type ModelTriggerProps = {- open: boolean- provider: Model- model: ModelItem- className?: string- readonly?: boolean-}-const ModelTrigger: FC<ModelTriggerProps> = ({- open,- provider,- model,- className,- readonly,-}) => {- const language = useLanguage()-- return (- <div- className={cn(- 'group flex h-8 items-center gap-0.5 rounded-lg bg-components-input-bg-normal p-1',- !readonly && 'cursor-pointer hover:bg-components-input-bg-hover',- open && 'bg-components-input-bg-hover',- model.status !== ModelStatusEnum.active && 'bg-components-input-bg-disabled hover:bg-components-input-bg-disabled',- className,- )}- >- <ModelIcon- className="p-0.5"- provider={provider}- modelName={model.model}- />- <div className="flex grow items-center gap-1 truncate px-1 py-[3px]">- <ModelName- className="grow"- modelItem={model}- showMode- showFeatures- />- {!readonly && (- <div className="flex h-4 w-4 shrink-0 items-center justify-center">- {- model.status !== ModelStatusEnum.active- ? (- <Tooltip popupContent={MODEL_STATUS_TEXT[model.status][language]}>- <AlertTriangle className="h-4 w-4 text-text-warning-secondary" />- </Tooltip>- )- : (- <RiArrowDownSLine- className="h-3.5 w-3.5 text-text-tertiary"- />- )- }- </div>- )}- </div>- </div>- )-}--export default ModelTriggerdiff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popover.spec.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popover.spec.tsxnew file mode 100644index 00000000000..a20a066d35d--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popover.spec.tsx@@ -0,0 +1,77 @@+import type { ReactNode } from 'react'+import { act, fireEvent, render, screen } from '@testing-library/react'+import ModelSelector from './index'++type PopoverProps = {+ children: ReactNode+ onOpenChange?: (open: boolean) => void+}++let latestOnOpenChange: PopoverProps['onOpenChange']++vi.mock('../hooks', () => ({+ useCurrentProviderAndModel: () => ({+ currentProvider: undefined,+ currentModel: undefined,+ }),+}))++vi.mock('@/app/components/base/ui/popover', () => ({+ Popover: ({ children, onOpenChange }: PopoverProps) => {+ latestOnOpenChange = onOpenChange+ return <div>{children}</div>+ },+ PopoverTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,+ PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}))++vi.mock('./model-selector-trigger', () => ({+ default: ({ open, readonly }: { open: boolean, readonly?: boolean }) => (+ <span>+ {open ? 'open' : 'closed'}+ -+ {readonly ? 'readonly' : 'editable'}+ </span>+ ),+}))++vi.mock('./popup', () => ({+ default: ({ onHide }: { onHide: () => void }) => (+ <div data-testid="popup">+ <button type="button" onClick={onHide}>hide-popup</button>+ </div>+ ),+}))++describe('ModelSelector popover branches', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ latestOnOpenChange = undefined+ })++ it('should open and close through popover callbacks when editable', () => {+ const onHide = vi.fn()+ render(<ModelSelector modelList={[]} onHide={onHide} />)++ act(() => {+ latestOnOpenChange?.(true)+ })++ expect(screen.getByText('open-editable')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'hide-popup' }))++ expect(screen.getByText('closed-editable')).toBeInTheDocument()+ expect(onHide).toHaveBeenCalledTimes(1)+ })++ it('should ignore popover open changes when readonly', () => {+ render(<ModelSelector modelList={[]} readonly />)++ act(() => {+ latestOnOpenChange?.(true)+ })++ expect(screen.getByText('closed-readonly')).toBeInTheDocument()+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsxindex 56c589e7bdf..51f50663f9e 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx@@ -4,10 +4,15 @@ import type {Model,ModelItem,} from '../declarations'-+import { useCallback, useState } from 'react'import { useTranslation } from 'react-i18next'-import { Check } from '@/app/components/base/icons/src/vender/line/general'-import Tooltip from '@/app/components/base/tooltip'+import { CreditsCoin } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { cn } from '@/utils/classnames'@@ -25,6 +30,9 @@ import {import ModelBadge from '../model-badge'import ModelIcon from '../model-icon'import ModelName from '../model-name'+import DropdownContent from '../provider-added-card/model-auth-dropdown/dropdown-content'+import { useChangeProviderPriority } from '../provider-added-card/use-change-provider-priority'+import { useCredentialPanelState } from '../provider-added-card/use-credential-panel-state'import {modelTypeFormat,sizeFormat,@@ -35,19 +43,23 @@ type PopupItemProps = {defaultModel?: DefaultModelmodel: ModelonSelect: (provider: string, model: ModelItem) => void+ onHide: () => void}const PopupItem: FC<PopupItemProps> = ({defaultModel,model,onSelect,+ onHide,}) => {+ const [collapsed, setCollapsed] = useState(false)+ const [dropdownOpen, setDropdownOpen] = useState(false)const { t } = useTranslation()const language = useLanguage()const { setShowModelModal } = useModalContext()const { modelProviders } = useProviderContext()const updateModelList = useUpdateModelList()const updateModelProviders = useUpdateModelProviders()- const currentProvider = modelProviders.find(provider => provider.provider === model.provider)!+ const currentProvider = modelProviders.find(provider => provider.provider === model.provider)const handleSelect = (provider: string, modelItem: ModelItem) => {if (modelItem.status !== ModelStatusEnum.active)return@@ -55,6 +67,8 @@ const PopupItem: FC<PopupItemProps> = ({onSelect(provider, modelItem)}const handleOpenModelModal = () => {+ if (!currentProvider)+ returnsetShowModelModal({payload: {currentProvider,@@ -71,101 +85,169 @@ const PopupItem: FC<PopupItemProps> = ({})}+ const state = useCredentialPanelState(currentProvider)+ const { isChangingPriority, handleChangePriority } = useChangeProviderPriority(currentProvider)++ const isUsingCredits = state.priority === 'credits'+ const hasCredits = !state.isCreditsExhausted+ const isApiKeyActive = state.variant === 'api-active' || state.variant === 'api-fallback'+ const { credentialName } = state++ const handleCloseDropdown = useCallback(() => {+ setDropdownOpen(false)+ onHide()+ }, [onHide])++ if (!currentProvider)+ return null+return (<div className="mb-1">- <div className="flex h-[22px] items-center px-3 text-xs font-medium text-text-tertiary">- {model.label[language] || model.label.en_US}+ <div className="sticky top-12 z-[2] flex h-[22px] items-center justify-between bg-components-panel-bg px-3 text-xs font-medium text-text-tertiary">+ <div+ className="flex cursor-pointer items-center"+ onClick={() => setCollapsed(prev => !prev)}+ >+ {model.label[language] || model.label.en_US}+ <span className={cn('i-custom-vender-solid-general-arrow-down-round-fill h-4 w-4 text-text-quaternary', collapsed && '-rotate-90')} />+ </div>+ <Popover open={dropdownOpen} onOpenChange={setDropdownOpen}>+ <PopoverTrigger+ render={(+ <button type="button" className="flex cursor-pointer items-center rounded-md px-1.5 py-1 text-text-tertiary system-xs-medium hover:bg-components-button-ghost-bg-hover">+ {isUsingCredits+ ? (+ hasCredits+ ? (+ <>+ <CreditsCoin className="h-3 w-3" />+ <span className="ml-1">{t('modelProvider.selector.aiCredits', { ns: 'common' })}</span>+ </>+ )+ : (+ <>+ <span className="i-ri-alert-fill h-3 w-3 text-text-warning-secondary" />+ <span className="ml-1 text-text-warning">{t('modelProvider.selector.creditsExhausted', { ns: 'common' })}</span>+ </>+ )+ )+ : credentialName+ ? (+ <>+ <span className={cn('h-1.5 w-1.5 shrink-0 rounded-[2px] border', isApiKeyActive ? 'border-components-badge-status-light-success-border-inner bg-components-badge-status-light-success-bg' : 'border-components-badge-status-light-error-border-inner bg-components-badge-status-light-error-bg')} />+ <span className="ml-1 text-text-tertiary">{credentialName}</span>+ </>+ )+ : (+ <>+ <span className="h-1.5 w-1.5 shrink-0 rounded-[2px] border border-components-badge-status-light-disabled-border-inner bg-components-badge-status-light-disabled-bg" />+ <span className="ml-1 text-text-tertiary">{t('modelProvider.selector.configureRequired', { ns: 'common' })}</span>+ </>+ )}+ <span className="i-ri-arrow-down-s-line !h-[14px] !w-[14px] translate-y-px text-text-tertiary" />+ </button>+ )}+ />+ <PopoverContent placement="bottom-end">+ <DropdownContent+ provider={currentProvider}+ state={state}+ isChangingPriority={isChangingPriority}+ onChangePriority={handleChangePriority}+ onClose={handleCloseDropdown}+ />+ </PopoverContent>+ </Popover></div>- {- model.models.map(modelItem => (- <Tooltip- key={modelItem.model}- position="right"- popupClassName="p-3 !w-[206px] bg-components-panel-bg-blur backdrop-blur-sm border-[0.5px] border-components-panel-border rounded-xl"- popupContent={(- <div className="flex flex-col gap-1">- <div className="flex flex-col items-start gap-2">+ {!collapsed && model.models.map(modelItem => (+ <Tooltip key={modelItem.model}>+ <TooltipTrigger+ render={(+ <button+ type="button"+ className={cn('group relative flex h-8 w-full items-center gap-1 rounded-lg px-3 py-1.5 text-left', modelItem.status === ModelStatusEnum.active ? 'cursor-pointer hover:bg-state-base-hover' : 'cursor-not-allowed hover:bg-state-base-hover-alt')}+ onClick={() => handleSelect(model.provider, modelItem)}+ >+ <div className="flex items-center gap-2"><ModelIconclassName={cn('h-5 w-5 shrink-0')}provider={model}modelName={modelItem.model}/>- <div className="system-md-medium text-wrap break-words text-text-primary">{modelItem.label[language] || modelItem.label.en_US}</div>- </div>- {/* {currentProvider?.description && (- <div className='text-text-tertiary system-xs-regular'>{currentProvider?.description?.[language] || currentProvider?.description?.en_US}</div>- )} */}- <div className="flex flex-wrap gap-1">- {!!modelItem.model_type && (- <ModelBadge>- {modelTypeFormat(modelItem.model_type)}- </ModelBadge>- )}- {!!modelItem.model_properties.mode && (- <ModelBadge>- {(modelItem.model_properties.mode as string).toLocaleUpperCase()}- </ModelBadge>- )}- {!!modelItem.model_properties.context_size && (- <ModelBadge>- {sizeFormat(modelItem.model_properties.context_size as number)}- </ModelBadge>- )}+ <ModelName+ className={cn('text-text-secondary system-sm-medium', modelItem.status !== ModelStatusEnum.active && 'opacity-60')}+ modelItem={modelItem}+ /></div>- {[ModelTypeEnum.textGeneration, ModelTypeEnum.textEmbedding, ModelTypeEnum.rerank].includes(modelItem.model_type as ModelTypeEnum)- && modelItem.features?.some(feature => [ModelFeatureEnum.vision, ModelFeatureEnum.audio, ModelFeatureEnum.video, ModelFeatureEnum.document].includes(feature))- && (- <div className="pt-2">- <div className="system-2xs-medium-uppercase mb-1 text-text-tertiary">{t('model.capabilities', { ns: 'common' })}</div>- <div className="flex flex-wrap gap-1">- {modelItem.features?.map(feature => (- <FeatureIcon- key={feature}- feature={feature}- showFeaturesLabel- />- ))}- </div>+ {+ defaultModel?.model === modelItem.model && defaultModel.provider === currentProvider.provider && (+ <span className="i-custom-vender-line-general-check h-4 w-4 shrink-0 text-text-accent" />+ )+ }+ {+ modelItem.status === ModelStatusEnum.noConfigure && (+ <div+ className="hidden cursor-pointer text-xs font-medium text-text-accent group-hover:block"+ onClick={handleOpenModelModal}+ >+ {t('operation.add', { ns: 'common' }).toLocaleUpperCase()}</div>- )}- </div>+ )+ }+ </button>)}+ />+ <TooltipContent+ placement="right"+ variant="plain"+ popupClassName="w-[206px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-3 backdrop-blur-sm">- <div- key={modelItem.model}- className={cn('group relative flex h-8 items-center gap-1 rounded-lg px-3 py-1.5', modelItem.status === ModelStatusEnum.active ? 'cursor-pointer hover:bg-state-base-hover' : 'cursor-not-allowed hover:bg-state-base-hover-alt')}- onClick={() => handleSelect(model.provider, modelItem)}- >- <div className="flex items-center gap-2">+ <div className="flex flex-col gap-1">+ <div className="flex flex-col items-start gap-2"><ModelIconclassName={cn('h-5 w-5 shrink-0')}provider={model}modelName={modelItem.model}/>- <ModelName- className={cn('system-sm-medium text-text-secondary', modelItem.status !== ModelStatusEnum.active && 'opacity-60')}- modelItem={modelItem}- />+ <div className="text-wrap break-words text-text-primary system-md-medium">{modelItem.label[language] || modelItem.label.en_US}</div>+ </div>+ <div className="flex flex-wrap gap-1">+ {!!modelItem.model_type && (+ <ModelBadge>+ {modelTypeFormat(modelItem.model_type)}+ </ModelBadge>+ )}+ {!!modelItem.model_properties.mode && (+ <ModelBadge>+ {(modelItem.model_properties.mode as string).toLocaleUpperCase()}+ </ModelBadge>+ )}+ {!!modelItem.model_properties.context_size && (+ <ModelBadge>+ {sizeFormat(modelItem.model_properties.context_size as number)}+ </ModelBadge>+ )}</div>- {- defaultModel?.model === modelItem.model && defaultModel.provider === currentProvider.provider && (- <Check className="h-4 w-4 shrink-0 text-text-accent" />- )- }- {- modelItem.status === ModelStatusEnum.noConfigure && (- <div- className="hidden cursor-pointer text-xs font-medium text-text-accent group-hover:block"- onClick={handleOpenModelModal}- >- {t('operation.add', { ns: 'common' }).toLocaleUpperCase()}+ {[ModelTypeEnum.textGeneration, ModelTypeEnum.textEmbedding, ModelTypeEnum.rerank].includes(modelItem.model_type as ModelTypeEnum)+ && modelItem.features?.some(feature => [ModelFeatureEnum.vision, ModelFeatureEnum.audio, ModelFeatureEnum.video, ModelFeatureEnum.document].includes(feature))+ && (+ <div className="pt-2">+ <div className="mb-1 text-text-tertiary system-2xs-medium-uppercase">{t('model.capabilities', { ns: 'common' })}</div>+ <div className="flex flex-wrap gap-1">+ {modelItem.features?.map(feature => (+ <FeatureIcon+ key={feature}+ feature={feature}+ showFeaturesLabel+ />+ ))}+ </div></div>- )- }+ )}</div>- </Tooltip>- ))- }+ </TooltipContent>+ </Tooltip>+ ))}</div>)}diff --git a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsxindex 93446e1a36c..b324edfefd8 100644--- a/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx+++ b/web/app/components/header/account-setting/model-provider-page/model-selector/popup.tsx@@ -4,19 +4,31 @@ import type {Model,ModelItem,} from '../declarations'-import {- RiArrowRightUpLine,- RiSearchLine,-} from '@remixicon/react'-import { useEffect, useMemo, useRef, useState } from 'react'+import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'+import { useTheme } from 'next-themes'+import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import { XCircle } from '@/app/components/base/icons/src/vender/solid/general'-import { tooltipManager } from '@/app/components/base/tooltip/TooltipManager'+import Button from '@/app/components/base/button'import { ACCOUNT_SETTING_TAB } from '@/app/components/header/account-setting/constants'+import checkTaskStatus from '@/app/components/plugins/install-plugin/base/check-task-status'+import useRefreshPluginList from '@/app/components/plugins/install-plugin/hooks/use-refresh-plugin-list'+import { useSystemFeaturesQuery } from '@/context/global-public-context'import { useModalContext } from '@/context/modal-context'+import { useProviderContext } from '@/context/provider-context'+import { useInstallPackageFromMarketPlace } from '@/service/use-plugins'+import { cn } from '@/utils/classnames'import { supportFunctionCall } from '@/utils/tool-call'-import { ModelFeatureEnum } from '../declarations'-import { useLanguage } from '../hooks'+import { getMarketplaceUrl } from '@/utils/var'+import {+ CustomConfigurationStatusEnum,+ ModelFeatureEnum,+ ModelStatusEnum,+} from '../declarations'+import { useLanguage, useMarketplaceAllPlugins } from '../hooks'+import CreditsExhaustedAlert from '../provider-added-card/model-auth-dropdown/credits-exhausted-alert'+import { useTrialCredits } from '../provider-added-card/use-trial-credits'+import { providerSupportsCredits } from '../supports-credits'+import { MODEL_PROVIDER_QUOTA_GET_PAID, modelNameMap, providerIconMap, providerKeyToPluginId } from '../utils'import PopupItem from './popup-item'type PopupProps = {@@ -34,32 +46,101 @@ const Popup: FC<PopupProps> = ({onHide,}) => {const { t } = useTranslation()+ const { theme } = useTheme()const language = useLanguage()const [searchText, setSearchText] = useState('')+ const [marketplaceCollapsed, setMarketplaceCollapsed] = useState(false)const { setShowAccountSettingModal } = useModalContext()- const scrollRef = useRef<HTMLDivElement>(null)+ const { modelProviders } = useProviderContext()+ const {+ plugins: allPlugins,+ isLoading: isMarketplacePluginsLoading,+ } = useMarketplaceAllPlugins(modelProviders, '')+ const { mutateAsync: installPackageFromMarketPlace } = useInstallPackageFromMarketPlace()+ const { refreshPluginList } = useRefreshPluginList()+ const [installingProvider, setInstallingProvider] = useState<ModelProviderQuotaGetPaid | null>(null)+ const { isExhausted: isCreditsExhausted } = useTrialCredits()+ const { data: systemFeatures } = useSystemFeaturesQuery()+ const trialModels = systemFeatures?.trial_models+ const installedProviderMap = useMemo(() => new Map(+ modelProviders.map(provider => [provider.provider, provider]),+ ), [modelProviders])+ const aiCreditVisibleProviders = useMemo(() => {+ if (isCreditsExhausted)+ return new Set<string>()- // Close any open tooltips when the user scrolls to prevent them from appearing- // in incorrect positions or becoming detached from their trigger elements- useEffect(() => {- const handleTooltipCloseOnScroll = () => {- tooltipManager.closeActiveTooltip()- }+ return new Set(+ modelProviders+ .filter(provider => providerSupportsCredits(provider, trialModels))+ .map(provider => provider.provider),+ )+ }, [isCreditsExhausted, modelProviders, trialModels])+ const showCreditsExhaustedAlert = isCreditsExhausted+ && modelProviders.some(provider => providerSupportsCredits(provider, trialModels))+ const hasApiKeyFallback = modelProviders.some((provider) => {+ const isApiKeyActive = provider.custom_configuration?.status === CustomConfigurationStatusEnum.active+ return isApiKeyActive && providerSupportsCredits(provider, trialModels)+ })- const scrollContainer = scrollRef.current- if (!scrollContainer)+ const handleInstallPlugin = useCallback(async (key: ModelProviderQuotaGetPaid) => {+ if (!allPlugins || isMarketplacePluginsLoading || installingProvider)+ return+ const pluginId = providerKeyToPluginId[key]+ const plugin = allPlugins.find(p => p.plugin_id === pluginId)+ if (!plugin)return- // Use passive listener for better performance since we don't prevent default- scrollContainer.addEventListener('scroll', handleTooltipCloseOnScroll, { passive: true })-- return () => {- scrollContainer.removeEventListener('scroll', handleTooltipCloseOnScroll)+ const uniqueIdentifier = plugin.latest_package_identifier+ setInstallingProvider(key)+ try {+ const { all_installed, task_id } = await installPackageFromMarketPlace(uniqueIdentifier)+ if (!all_installed) {+ const { check } = checkTaskStatus()+ await check({ taskId: task_id, pluginUniqueIdentifier: uniqueIdentifier })+ }+ refreshPluginList(plugin)}- }, [])+ catch { }+ finally {+ setInstallingProvider(null)+ }+ }, [allPlugins, installPackageFromMarketPlace, installingProvider, isMarketplacePluginsLoading, refreshPluginList])++ const installedModelList = useMemo(() => {+ const modelMap = new Map(modelList.map(model => [model.provider, model]))+ const installedMarketplaceModels = MODEL_PROVIDER_QUOTA_GET_PAID.flatMap((providerKey) => {+ const installedProvider = installedProviderMap.get(providerKey)++ if (!installedProvider)+ return []++ const matchedModel = modelMap.get(providerKey)+ if (matchedModel)+ return [matchedModel]++ if (!aiCreditVisibleProviders.has(providerKey))+ return []++ return [{+ provider: installedProvider.provider,+ icon_small: installedProvider.icon_small,+ icon_small_dark: installedProvider.icon_small_dark,+ label: installedProvider.label,+ models: [],+ status: ModelStatusEnum.active,+ }]+ })+ const otherModels = modelList.filter(model => !MODEL_PROVIDER_QUOTA_GET_PAID.includes(model.provider as ModelProviderQuotaGetPaid))++ return [...installedMarketplaceModels, ...otherModels]+ }, [aiCreditVisibleProviders, installedProviderMap, modelList])const filteredModelList = useMemo(() => {- return modelList.map((model) => {+ const filtered = installedModelList.map((model) => {+ const matchesProviderSearch = !searchText+ || model.provider.toLowerCase().includes(searchText.toLowerCase())+ || Object.values(model.label).some(label => label.toLowerCase().includes(searchText.toLowerCase()))+const filteredModels = model.models.filter((modelItem) => {if (modelItem.label[language] !== undefined)@@ -77,21 +158,39 @@ const Popup: FC<PopupProps> = ({return modelItem.features?.includes(feature) ?? false})})+ if (!matchesProviderSearch || (filteredModels.length === 0 && !aiCreditVisibleProviders.has(model.provider)))+ return null+return { ...model, models: filteredModels }- }).filter(model => model.models.length > 0)- }, [language, modelList, scopeFeatures, searchText])+ }).filter((model): model is Model => model !== null)++ if (defaultModel?.provider) {+ filtered.sort((a, b) => {+ const aSelected = a.provider === defaultModel.provider ? 0 : 1+ const bSelected = b.provider === defaultModel.provider ? 0 : 1+ return aSelected - bSelected+ })+ }++ return filtered+ }, [aiCreditVisibleProviders, defaultModel?.provider, installedModelList, language, scopeFeatures, searchText])++ const marketplaceProviders = useMemo(() => {+ const installedProviders = new Set(modelProviders.map(provider => provider.provider))+ return MODEL_PROVIDER_QUOTA_GET_PAID.filter(key => !installedProviders.has(key))+ }, [modelProviders])return (- <div ref={scrollRef} className="max-h-[480px] w-[320px] overflow-y-auto rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg">+ <div className="max-h-[480px] overflow-y-auto no-scrollbar"><div className="sticky top-0 z-10 bg-components-panel-bg pb-1 pl-3 pr-2 pt-3"><div className={`flex h-8 items-center rounded-lg border pl-[9px] pr-[10px]${searchText ? 'border-components-input-border-active bg-components-input-bg-active shadow-xs' : 'border-transparent bg-components-input-bg-normal'}`}>- <RiSearchLine+ <spanclassName={`- mr-[7px] h-[14px] w-[14px] shrink-0+ i-ri-search-line mr-[7px] h-[14px] w-[14px] shrink-0${searchText ? 'text-text-tertiary' : 'text-text-quaternary'}`}/>@@ -103,15 +202,29 @@ const Popup: FC<PopupProps> = ({/>{searchText && (- <XCircle- className="ml-1.5 h-[14px] w-[14px] shrink-0 cursor-pointer text-text-quaternary"+ <span+ className="i-custom-vender-solid-general-x-circle ml-1.5 h-[14px] w-[14px] shrink-0 cursor-pointer text-text-quaternary"onClick={() => setSearchText('')}/>)}</div>+ {scopeFeatures.length > 0 && (+ <div+ data-testid="compatible-models-banner"+ className="mt-2 flex items-center gap-1 rounded-lg bg-background-section-burn px-2.5 py-2"+ >+ <span className="i-ri-information-2-fill h-4 w-4 shrink-0 text-text-accent" />+ <p className="text-text-secondary system-xs-medium">+ {t('modelProvider.selector.onlyCompatibleModelsShown', { ns: 'common' })}+ </p>+ </div>+ )}</div>- <div className="p-1">+ {showCreditsExhaustedAlert && (+ <CreditsExhaustedAlert hasApiKeyFallback={hasApiKeyFallback} />+ )}+ <div className="px-1 pb-1">{filteredModelList.map(model => (<PopupItem@@ -119,26 +232,112 @@ const Popup: FC<PopupProps> = ({defaultModel={defaultModel}model={model}onSelect={onSelect}+ onHide={onHide}/>))}- {- !filteredModelList.length && (- <div className="break-all px-3 py-1.5 text-center text-xs leading-[18px] text-text-tertiary">- {`No model found for “${searchText}”`}+ {!filteredModelList.length && !installedModelList.length && (+ <div className="flex flex-col gap-2 rounded-[10px] bg-gradient-to-r from-state-base-hover to-background-gradient-mask-transparent p-4">+ <div className="flex h-10 w-10 items-center justify-center rounded-[10px] border-[0.5px] border-components-card-border bg-components-card-bg shadow-lg backdrop-blur-[5px]">+ <span className="i-ri-brain-2-line h-5 w-5 text-text-tertiary" /></div>- )- }+ <div className="flex flex-col gap-1">+ <p className="text-text-secondary system-sm-medium">+ {t('modelProvider.selector.noProviderConfigured', { ns: 'common' })}+ </p>+ <p className="text-text-tertiary system-xs-regular">+ {t('modelProvider.selector.noProviderConfiguredDesc', { ns: 'common' })}+ </p>+ </div>+ <Button+ variant="primary"+ className="w-[108px]"+ onClick={() => {+ onHide()+ setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })+ }}+ >+ {t('modelProvider.selector.configure', { ns: 'common' })}+ <span className="i-ri-arrow-right-line h-4 w-4" />+ </Button>+ </div>+ )}+ {!filteredModelList.length && installedModelList.length > 0 && (+ <div className="break-all px-3 py-1.5 text-center text-xs leading-[18px] text-text-tertiary">+ {`No model found for \u201C${searchText}\u201D`}+ </div>+ )}+ {marketplaceProviders.length > 0 && (+ <>+ <div className="mx-2 my-1 border-t border-divider-subtle" />+ <div className="mb-1">+ <div className="flex h-[22px] items-center px-3">+ <div+ className="flex flex-1 cursor-pointer items-center text-text-primary system-sm-medium"+ onClick={() => setMarketplaceCollapsed(prev => !prev)}+ >+ {t('modelProvider.selector.fromMarketplace', { ns: 'common' })}+ <span className={cn('i-custom-vender-solid-general-arrow-down-round-fill h-4 w-4 text-text-quaternary', marketplaceCollapsed && '-rotate-90')} />+ </div>+ </div>+ {!marketplaceCollapsed && (+ <>+ {marketplaceProviders.map((key) => {+ const Icon = providerIconMap[key]+ const isInstalling = installingProvider === key+ return (+ <div+ key={key}+ className="group flex cursor-pointer items-center gap-1 rounded-lg py-0.5 pl-3 pr-0.5 hover:bg-state-base-hover"+ >+ <div className="flex flex-1 items-center gap-2 py-0.5">+ <Icon className="h-5 w-5 shrink-0 rounded-md" />+ <span className="text-text-secondary system-sm-regular">{modelNameMap[key]}</span>+ </div>+ <Button+ variant="secondary"+ size="small"+ className={cn(+ 'shrink-0 backdrop-blur-[5px]',+ !isInstalling && 'hidden group-hover:flex',+ )}+ disabled={isInstalling || isMarketplacePluginsLoading}+ onClick={() => handleInstallPlugin(key)}+ >+ {isInstalling && <span className="i-ri-loader-2-line h-3.5 w-3.5 animate-spin" />}+ {isInstalling+ ? t('installModal.installing', { ns: 'plugin' })+ : t('modelProvider.selector.install', { ns: 'common' })}+ </Button>+ </div>+ )+ })}+ <a+ className="flex cursor-pointer items-center gap-0.5 px-3 pt-1.5"+ href={getMarketplaceUrl('', { theme })}+ target="_blank"+ rel="noopener noreferrer"+ >+ <span className="flex-1 text-text-accent system-xs-regular">+ {t('modelProvider.selector.discoverMoreInMarketplace', { ns: 'common' })}+ </span>+ <span className="i-ri-arrow-right-up-line !h-3 !w-3 text-text-accent" />+ </a>+ </>+ )}+ </div>+ </>+ )}</div><div- className="sticky bottom-0 flex cursor-pointer items-center rounded-b-lg border-t border-divider-subtle bg-components-panel-bg px-4 py-2 text-text-accent-light-mode-only"+ className="sticky bottom-0 flex cursor-pointer items-center gap-1 rounded-b-lg border-t border-divider-subtle bg-components-panel-bg px-3 py-2 text-text-tertiary hover:text-text-secondary"onClick={() => {onHide()setShowAccountSettingModal({ payload: ACCOUNT_SETTING_TAB.PROVIDER })}}>- <span className="system-xs-medium">{t('model.settingsLink', { ns: 'common' })}</span>- <RiArrowRightUpLine className="ml-0.5 h-3 w-3" />+ <span className="i-ri-equalizer-2-line h-4 w-4 shrink-0" />+ <span className="system-xs-medium">{t('modelProvider.selector.modelProviderSettings', { ns: 'common' })}</span></div></div>)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/add-model-button.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/add-model-button.spec.tsxdeleted file mode 100644index b594f408cba..00000000000--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/add-model-button.spec.tsx+++ /dev/null@@ -1,17 +0,0 @@-import { fireEvent, render, screen } from '@testing-library/react'-import AddModelButton from '../add-model-button'--describe('AddModelButton', () => {- it('should render button with text', () => {- render(<AddModelButton onClick={vi.fn()} />)- expect(screen.getByText('common.modelProvider.addModel')).toBeInTheDocument()- })-- it('should call onClick when clicked', () => {- const handleClick = vi.fn()- render(<AddModelButton onClick={handleClick} />)- const button = screen.getByText('common.modelProvider.addModel')- fireEvent.click(button)- expect(handleClick).toHaveBeenCalledTimes(1)- })-})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsxindex 85403b94f93..c9fa6b2f228 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/credential-panel.spec.tsx@@ -1,56 +1,58 @@import type { ModelProvider } from '../../declarations'-import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import { ToastContext } from '@/app/components/base/toast/context'-import { changeModelProviderPriority } from '@/service/common'-import { ConfigurationMethodEnum } from '../../declarations'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'+import {+ ConfigurationMethodEnum,+ CurrentSystemQuotaTypeEnum,+ CustomConfigurationStatusEnum,+ PreferredProviderTypeEnum,+} from '../../declarations'import CredentialPanel from '../credential-panel'-const mockEventEmitter = { emit: vi.fn() }-const mockNotify = vi.fn()-const mockUpdateModelList = vi.fn()-const mockUpdateModelProviders = vi.fn()-const mockCredentialStatus = {- hasCredential: true,- authorized: true,- authRemoved: false,- current_credential_name: 'test-credential',- notAllowedToUse: false,-}+const {+ mockToastNotify,+ mockUpdateModelList,+ mockUpdateModelProviders,+ mockTrialCredits,+ mockChangePriorityFn,+} = vi.hoisted(() => ({+ mockToastNotify: vi.fn(),+ mockUpdateModelList: vi.fn(),+ mockUpdateModelProviders: vi.fn(),+ mockTrialCredits: { credits: 100, totalCredits: 10_000, isExhausted: false, isLoading: false, nextCreditResetDate: undefined },+ mockChangePriorityFn: vi.fn().mockResolvedValue({ result: 'success' }),+}))vi.mock('@/config', async (importOriginal) => {const actual = await importOriginal<typeof import('@/config')>()- return {- ...actual,- IS_CLOUD_EDITION: true,- }-})--vi.mock('@/app/components/base/toast/context', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/toast/context')>()- return {- ...actual,- useToastContext: () => ({- notify: mockNotify,- }),- }+ return { ...actual, IS_CLOUD_EDITION: true }})-vi.mock('@/context/event-emitter', () => ({- useEventEmitterContextContext: () => ({- eventEmitter: mockEventEmitter,- }),+vi.mock('@/context/global-public-context', () => ({+ useSystemFeaturesQuery: () => ({ data: { trial_models: ['langgenius/openai/openai'] } }),}))-vi.mock('@/service/common', () => ({- changeModelProviderPriority: vi.fn(),+vi.mock('@/app/components/base/toast', () => ({+ default: { notify: mockToastNotify },}))-vi.mock('@/app/components/header/account-setting/model-provider-page/model-auth', () => ({- ConfigProvider: () => <div data-testid="config-provider" />,-}))--vi.mock('@/app/components/header/account-setting/model-provider-page/model-auth/hooks', () => ({- useCredentialStatus: () => mockCredentialStatus,+vi.mock('@/service/client', () => ({+ consoleQuery: {+ modelProviders: {+ models: {+ queryKey: ({ input }: { input: { params: { provider: string } } }) => ['console', 'modelProviders', 'models', input.params.provider],+ },+ changePreferredProviderType: {+ mutationOptions: (opts: Record<string, unknown>) => ({+ mutationFn: (...args: unknown[]) => {+ mockChangePriorityFn(...args)+ return Promise.resolve({ result: 'success' })+ },+ ...opts,+ }),+ },+ },+ },}))vi.mock('../../hooks', () => ({@@ -58,161 +60,395 @@ vi.mock('../../hooks', () => ({useUpdateModelProviders: () => mockUpdateModelProviders,}))-vi.mock('../priority-selector', () => ({- default: ({ value, onSelect }: { value: string, onSelect: (key: string) => void }) => (- <button data-testid="priority-selector" onClick={() => onSelect('custom')}>- Priority Selector- {' '}- {value}- </button>- ),+vi.mock('../use-trial-credits', () => ({+ useTrialCredits: () => mockTrialCredits,}))-vi.mock('../priority-use-tip', () => ({- default: () => <div data-testid="priority-use-tip">Priority Tip</div>,+vi.mock('../model-auth-dropdown', () => ({+ default: ({ state, onChangePriority }: { state: { variant: string, hasCredentials: boolean }, onChangePriority: (key: string) => void }) => (+ <div data-testid="model-auth-dropdown" data-variant={state.variant}>+ <button data-testid="change-priority-btn" onClick={() => onChangePriority('custom')}>+ Change Priority+ </button>+ </div>+ ),}))vi.mock('@/app/components/header/indicator', () => ({- default: ({ color }: { color: string }) => <div data-testid="indicator">{color}</div>,+ default: ({ color }: { color: string }) => <div data-testid="indicator" data-color={color} />,}))-describe('CredentialPanel', () => {- const mockProvider: ModelProvider = {- provider: 'test-provider',- provider_credential_schema: true,- custom_configuration: { status: 'active' },- system_configuration: { enabled: true },- preferred_provider_type: 'system',- configurate_methods: [ConfigurationMethodEnum.predefinedModel],- supported_model_types: ['gpt-4'],- } as unknown as ModelProvider+vi.mock('@/app/components/base/icons/src/vender/line/alertsAndFeedback/Warning', () => ({+ default: (props: Record<string, unknown>) => <div data-testid="warning-icon" className={props.className as string} />,+}))++const createTestQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: { retry: false, gcTime: 0 },+ mutations: { retry: false },+ },+})++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'langgenius/openai/openai',+ provider_credential_schema: { credential_form_schemas: [] },+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: 'cred-1',+ current_credential_name: 'test-credential',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'test-credential' }],+ },+ system_configuration: { enabled: true, current_quota_type: 'trial', quota_configurations: [] },+ preferred_provider_type: PreferredProviderTypeEnum.system,+ configurate_methods: [ConfigurationMethodEnum.predefinedModel],+ supported_model_types: ['llm'],+ ...overrides,+} as unknown as ModelProvider)++const renderWithQueryClient = (provider: ModelProvider) => {+ const queryClient = createTestQueryClient()+ return render(+ <QueryClientProvider client={queryClient}>+ <CredentialPanel provider={provider} />+ </QueryClientProvider>,+ )+}+describe('CredentialPanel', () => {beforeEach(() => {vi.clearAllMocks()- Object.assign(mockCredentialStatus, {- hasCredential: true,- authorized: true,- authRemoved: false,- current_credential_name: 'test-credential',- notAllowedToUse: false,- })+ Object.assign(mockTrialCredits, { credits: 100, totalCredits: 10_000, isExhausted: false, isLoading: false })})- const renderCredentialPanel = (provider: ModelProvider) => render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>- <CredentialPanel provider={provider} />- </ToastContext.Provider>,- )+ describe('Text label variants', () => {+ it('should show "AI credits in use" for credits-active variant', () => {+ renderWithQueryClient(createProvider())+ expect(screen.getByText(/aiCreditsInUse/)).toBeInTheDocument()+ })- it('should show credential name and configuration actions', () => {- renderCredentialPanel(mockProvider)+ it('should show "Credits exhausted" for credits-exhausted variant (no credentials)', () => {+ mockTrialCredits.isExhausted = true+ mockTrialCredits.credits = 0+ renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(screen.getByText(/quotaExhausted/)).toBeInTheDocument()+ })- expect(screen.getByText('test-credential')).toBeInTheDocument()- expect(screen.getByTestId('config-provider')).toBeInTheDocument()- expect(screen.getByTestId('priority-selector')).toBeInTheDocument()- })+ it('should show "No available usage" for no-usage variant (exhausted + credential unauthorized)', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1' }],+ },+ }))+ expect(screen.getByText(/noAvailableUsage/)).toBeInTheDocument()+ })- it('should show unauthorized status label when credential is missing', () => {- mockCredentialStatus.hasCredential = false- renderCredentialPanel(mockProvider)+ it('should show "AI credits in use" with warning for credits-fallback (custom priority, no credentials, credits available)', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(screen.getByText(/aiCreditsInUse/)).toBeInTheDocument()+ })++ it('should show "AI credits in use" with warning for credits-fallback (custom priority, credential unauthorized, credits available)', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1' }],+ },+ }))+ expect(screen.getByText(/aiCreditsInUse/)).toBeInTheDocument()+ })- expect(screen.getByText(/modelProvider\.auth\.unAuthorized/)).toBeInTheDocument()+ it('should show warning icon for credits-fallback variant', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(screen.getByTestId('warning-icon')).toBeInTheDocument()+ })})- it('should show removed credential label and priority tip for custom preference', () => {- mockCredentialStatus.authorized = false- mockCredentialStatus.authRemoved = true- renderCredentialPanel({ ...mockProvider, preferred_provider_type: 'custom' } as ModelProvider)+ describe('Status label variants', () => {+ it('should show green indicator and credential name for api-fallback (exhausted + authorized key)', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider())+ expect(screen.getByTestId('indicator')).toHaveAttribute('data-color', 'green')+ expect(screen.getByText('test-credential')).toBeInTheDocument()+ })- expect(screen.getByText(/modelProvider\.auth\.authRemoved/)).toBeInTheDocument()- expect(screen.getByTestId('priority-use-tip')).toBeInTheDocument()- })+ it('should show warning icon for api-fallback variant', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider())+ expect(screen.getByTestId('warning-icon')).toBeInTheDocument()+ })- it('should change priority and refresh related data after success', async () => {- const mockChangePriority = changeModelProviderPriority as ReturnType<typeof vi.fn>- mockChangePriority.mockResolvedValue({ result: 'success' })- renderCredentialPanel(mockProvider)+ it('should show green indicator for api-active (custom priority + authorized)', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ }))+ expect(screen.getByTestId('indicator')).toHaveAttribute('data-color', 'green')+ expect(screen.getByText('test-credential')).toBeInTheDocument()+ })- fireEvent.click(screen.getByTestId('priority-selector'))+ it('should NOT show warning icon for api-active variant', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ }))+ expect(screen.queryByTestId('warning-icon')).not.toBeInTheDocument()+ })- await waitFor(() => {- expect(mockChangePriority).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalled()- expect(mockUpdateModelProviders).toHaveBeenCalled()- expect(mockUpdateModelList).toHaveBeenCalledWith('gpt-4')- expect(mockEventEmitter.emit).toHaveBeenCalled()+ it('should show red indicator and credential name for api-unavailable (exhausted + named unauthorized key)', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: 'Bad Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Bad Key' }],+ },+ }))+ expect(screen.getByTestId('indicator')).toHaveAttribute('data-color', 'red')+ expect(screen.getByText('Bad Key')).toBeInTheDocument()})})- it('should render standalone priority selector without provider schema', () => {- const providerNoSchema = {- ...mockProvider,- provider_credential_schema: null,- } as unknown as ModelProvider- renderCredentialPanel(providerNoSchema)- expect(screen.getByTestId('priority-selector')).toBeInTheDocument()- expect(screen.queryByTestId('config-provider')).not.toBeInTheDocument()- })+ describe('Destructive styling', () => {+ it('should apply destructive container for credits-exhausted', () => {+ mockTrialCredits.isExhausted = true+ const { container } = renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(container.querySelector('[class*="border-state-destructive"]')).toBeTruthy()+ })- it('should show gray indicator when notAllowedToUse is true', () => {- mockCredentialStatus.notAllowedToUse = true- renderCredentialPanel(mockProvider)+ it('should apply destructive container for no-usage variant', () => {+ mockTrialCredits.isExhausted = true+ const { container } = renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1' }],+ },+ }))+ expect(container.querySelector('[class*="border-state-destructive"]')).toBeTruthy()+ })- expect(screen.getByTestId('indicator')).toHaveTextContent('gray')- })+ it('should apply destructive container for api-unavailable variant', () => {+ mockTrialCredits.isExhausted = true+ const { container } = renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: 'Bad Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Bad Key' }],+ },+ }))+ expect(container.querySelector('[class*="border-state-destructive"]')).toBeTruthy()+ })- it('should not notify or update when priority change returns non-success', async () => {- const mockChangePriority = changeModelProviderPriority as ReturnType<typeof vi.fn>- mockChangePriority.mockResolvedValue({ result: 'error' })- renderCredentialPanel(mockProvider)+ it('should apply default container for credits-active', () => {+ const { container } = renderWithQueryClient(createProvider())+ expect(container.querySelector('[class*="bg-white"]')).toBeTruthy()+ })- fireEvent.click(screen.getByTestId('priority-selector'))+ it('should apply default container for api-active', () => {+ const { container } = renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ }))+ expect(container.querySelector('[class*="bg-white"]')).toBeTruthy()+ })- await waitFor(() => {- expect(mockChangePriority).toHaveBeenCalled()+ it('should apply default container for api-fallback', () => {+ mockTrialCredits.isExhausted = true+ const { container } = renderWithQueryClient(createProvider())+ expect(container.querySelector('[class*="bg-white"]')).toBeTruthy()})- expect(mockNotify).not.toHaveBeenCalled()- expect(mockUpdateModelProviders).not.toHaveBeenCalled()- expect(mockEventEmitter.emit).not.toHaveBeenCalled()})- it('should show empty label when authorized is false and authRemoved is false', () => {- mockCredentialStatus.authorized = false- mockCredentialStatus.authRemoved = false- renderCredentialPanel(mockProvider)+ describe('Text color', () => {+ it('should use destructive text color for credits-exhausted label', () => {+ mockTrialCredits.isExhausted = true+ const { container } = renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(container.querySelector('.text-text-destructive')).toBeTruthy()+ })++ it('should use secondary text color for credits-active label', () => {+ const { container } = renderWithQueryClient(createProvider())+ expect(container.querySelector('.text-text-secondary')).toBeTruthy()+ })++ it('should use destructive text color for api-unavailable credential name', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: 'Bad Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Bad Key' }],+ },+ }))+ expect(screen.getByText('Bad Key')).toHaveClass('text-text-destructive')+ })- expect(screen.queryByText(/modelProvider\.auth\.unAuthorized/)).not.toBeInTheDocument()- expect(screen.queryByText(/modelProvider\.auth\.authRemoved/)).not.toBeInTheDocument()+ it('should use secondary text color for api-active credential name', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ }))+ expect(screen.getByText('test-credential')).toHaveClass('text-text-secondary')+ })})- it('should not show PriorityUseTip when priorityUseType is system', () => {- renderCredentialPanel(mockProvider)+ describe('Priority change', () => {+ it('should call mutation with correct params on priority change', async () => {+ renderWithQueryClient(createProvider())++ await act(async () => {+ fireEvent.click(screen.getByTestId('change-priority-btn'))+ })++ await waitFor(() => {+ expect(mockChangePriorityFn.mock.calls[0]?.[0]).toEqual({+ params: { provider: 'langgenius/openai/openai' },+ body: { preferred_provider_type: 'custom' },+ })+ })+ })++ it('should show success toast and refresh data after successful mutation', async () => {+ renderWithQueryClient(createProvider())- expect(screen.queryByTestId('priority-use-tip')).not.toBeInTheDocument()+ await act(async () => {+ fireEvent.click(screen.getByTestId('change-priority-btn'))+ })++ await waitFor(() => {+ expect(mockToastNotify).toHaveBeenCalledWith(+ expect.objectContaining({ type: 'success' }),+ )+ expect(mockUpdateModelProviders).toHaveBeenCalled()+ expect(mockUpdateModelList).toHaveBeenCalledWith('llm')+ })+ })})- it('should not iterate configurateMethods for non-predefinedModel methods', async () => {- const mockChangePriority = changeModelProviderPriority as ReturnType<typeof vi.fn>- mockChangePriority.mockResolvedValue({ result: 'success' })- const providerWithCustomMethod = {- ...mockProvider,- configurate_methods: [ConfigurationMethodEnum.customizableModel],- } as unknown as ModelProvider- renderCredentialPanel(providerWithCustomMethod)+ describe('ModelAuthDropdown integration', () => {+ it('should pass credits-active variant to dropdown when credits available', () => {+ renderWithQueryClient(createProvider())+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'credits-active')+ })++ it('should pass api-fallback variant to dropdown when exhausted with valid key', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider())+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'api-fallback')+ })++ it('should pass credits-exhausted variant when exhausted with no credentials', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'credits-exhausted')+ })++ it('should pass api-active variant for custom priority with authorized key', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'api-active')+ })++ it('should pass credits-fallback variant for custom priority with no credentials and credits available', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'credits-fallback')+ })- fireEvent.click(screen.getByTestId('priority-selector'))+ it('should pass credits-fallback variant for custom priority with named unauthorized key and credits available', () => {+ renderWithQueryClient(createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: 'Bad Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Bad Key' }],+ },+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'credits-fallback')+ })- await waitFor(() => {- expect(mockChangePriority).toHaveBeenCalled()- expect(mockNotify).toHaveBeenCalled()+ it('should pass no-usage variant when exhausted + credential but unauthorized', () => {+ mockTrialCredits.isExhausted = true+ renderWithQueryClient(createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1' }],+ },+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'no-usage')})- expect(mockUpdateModelList).not.toHaveBeenCalled()})- it('should show red indicator when hasCredential is false', () => {- mockCredentialStatus.hasCredential = false- renderCredentialPanel(mockProvider)+ describe('apiKeyOnly priority (system disabled)', () => {+ it('should derive api-required-add when system config disabled and no credentials', () => {+ renderWithQueryClient(createProvider({+ system_configuration: { enabled: false, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },+ preferred_provider_type: PreferredProviderTypeEnum.system,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'api-required-add')+ expect(screen.getByText(/apiKeyRequired/)).toBeInTheDocument()+ })- expect(screen.getByTestId('indicator')).toHaveTextContent('red')+ it('should derive api-active when system config disabled but has authorized key', () => {+ renderWithQueryClient(createProvider({+ system_configuration: { enabled: false, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },+ }))+ expect(screen.getByTestId('model-auth-dropdown')).toHaveAttribute('data-variant', 'api-active')+ })})})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 33f88db3430..7c996515b21 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/index.spec.tsx@@ -1,17 +1,28 @@-import type { ModelItem, ModelProvider } from '../../declarations'+import type { ReactNode } from 'react'+import type { ModelProvider } from '../../declarations'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'-import { fetchModelProviderModelList } from '@/service/common'+import { createStore, Provider as JotaiProvider } from 'jotai'+import { useExpandModelProviderList } from '../../atoms'import { ConfigurationMethodEnum } from '../../declarations'import ProviderAddedCard from '../index'let mockIsCurrentWorkspaceManager = true-const mockEventEmitter = {- useSubscription: vi.fn(),- emit: vi.fn(),-}+const mockFetchModelProviderModels = vi.fn()+const mockQueryOptions = vi.fn(({ input, ...options }: { input: { params: { provider: string } }, enabled?: boolean }) => ({+ queryKey: ['console', 'modelProviders', 'models', input.params.provider],+ queryFn: () => mockFetchModelProviderModels(input.params.provider),+ ...options,+}))-vi.mock('@/service/common', () => ({- fetchModelProviderModelList: vi.fn(),+vi.mock('@/service/client', () => ({+ consoleQuery: {+ modelProviders: {+ models: {+ queryOptions: (options: { input: { params: { provider: string } }, enabled?: boolean }) => mockQueryOptions(options),+ },+ },+ },}))vi.mock('@/context/app-context', () => ({@@ -20,12 +31,6 @@ vi.mock('@/context/app-context', () => ({}),}))-vi.mock('@/context/event-emitter', () => ({- useEventEmitterContextContext: () => ({- eventEmitter: mockEventEmitter,- }),-}))-// Mock internal components to simplify testing of the index filevi.mock('../credential-panel', () => ({default: () => <div data-testid="credential-panel" />,@@ -53,6 +58,38 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-auth'ManageCustomModelCredentials: () => <div data-testid="manage-custom-model" />,}))+const createTestQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: { retry: false, gcTime: 0 },+ },+})++const renderWithQueryClient = (node: ReactNode) => {+ const queryClient = createTestQueryClient()+ const store = createStore()+ return render(+ <JotaiProvider store={store}>+ <QueryClientProvider client={queryClient}>+ {node}+ </QueryClientProvider>+ </JotaiProvider>,+ )+}++const ExternalExpandControls = () => {+ const expandModelProviderList = useExpandModelProviderList()+ return (+ <>+ <button type="button" data-testid="expand-other-provider" onClick={() => expandModelProviderList('langgenius/anthropic/anthropic')}>+ expand other+ </button>+ <button type="button" data-testid="expand-current-provider" onClick={() => expandModelProviderList('langgenius/openai/openai')}>+ expand current+ </button>+ </>+ )+}+describe('ProviderAddedCard', () => {const mockProvider = {provider: 'langgenius/openai/openai',@@ -67,19 +104,21 @@ describe('ProviderAddedCard', () => {})it('should render provider added card component', () => {- render(<ProviderAddedCard provider={mockProvider} />)+ renderWithQueryClient(<ProviderAddedCard provider={mockProvider} />)expect(screen.getByTestId('provider-added-card')).toBeInTheDocument()expect(screen.getByTestId('provider-icon')).toBeInTheDocument()})it('should open, refresh and collapse model list', async () => {- vi.mocked(fetchModelProviderModelList).mockResolvedValue({ data: [{ model: 'gpt-4' }] } as unknown as { data: ModelItem[] })- render(<ProviderAddedCard provider={mockProvider} />)+ mockFetchModelProviderModels.mockResolvedValue({ data: [{ model: 'gpt-4' }] })+ renderWithQueryClient(<ProviderAddedCard provider={mockProvider} />)const showModelsBtn = screen.getByTestId('show-models-button')fireEvent.click(showModelsBtn)- expect(fetchModelProviderModelList).toHaveBeenCalledWith(`/workspaces/current/model-providers/${mockProvider.provider}/models`)+ await waitFor(() => {+ expect(mockFetchModelProviderModels).toHaveBeenCalledWith(mockProvider.provider)+ })expect(await screen.findByTestId('model-list')).toBeInTheDocument()// Test line 71-72: Opening when already fetched@@ -90,13 +129,13 @@ describe('ProviderAddedCard', () => {// Explicitly re-find and click to re-openfireEvent.click(screen.getByTestId('show-models-button'))expect(await screen.findByTestId('model-list')).toBeInTheDocument()- expect(fetchModelProviderModelList).toHaveBeenCalledTimes(1) // Should not fetch again+ expect(mockFetchModelProviderModels).toHaveBeenCalledTimes(2) // Re-open fetches again with default stale/gc behavior// Refresh list from ModelListconst refreshBtn = screen.getByRole('button', { name: 'refresh list' })fireEvent.click(refreshBtn)await waitFor(() => {- expect(fetchModelProviderModelList).toHaveBeenCalledTimes(2)+ expect(mockFetchModelProviderModels).toHaveBeenCalledTimes(3)})})@@ -105,18 +144,20 @@ describe('ProviderAddedCard', () => {const promise = new Promise((resolve) => {resolveOuter = resolve})- vi.mocked(fetchModelProviderModelList).mockReturnValue(promise as unknown as ReturnType<typeof fetchModelProviderModelList>)+ mockFetchModelProviderModels.mockReturnValue(promise)- render(<ProviderAddedCard provider={mockProvider} />)+ renderWithQueryClient(<ProviderAddedCard provider={mockProvider} />)const showModelsBtn = screen.getByTestId('show-models-button')// First call sets loading to truefireEvent.click(showModelsBtn)- expect(fetchModelProviderModelList).toHaveBeenCalledTimes(1)+ await waitFor(() => {+ expect(mockFetchModelProviderModels).toHaveBeenCalledTimes(1)+ })// Second call should return early because loading is truefireEvent.click(showModelsBtn)- expect(fetchModelProviderModelList).toHaveBeenCalledTimes(1)+ expect(mockFetchModelProviderModels).toHaveBeenCalledTimes(1)await act(async () => {resolveOuter({ data: [] })@@ -125,46 +166,25 @@ describe('ProviderAddedCard', () => {expect(await screen.findByTestId('model-list')).toBeInTheDocument()})- it('should show loading spinner while model list is being fetched', async () => {- let resolvePromise: (value: unknown) => void = () => {}- const pendingPromise = new Promise((resolve) => {- resolvePromise = resolve- })- vi.mocked(fetchModelProviderModelList).mockReturnValue(pendingPromise as ReturnType<typeof fetchModelProviderModelList>)-- render(<ProviderAddedCard provider={mockProvider} />)+ it('should only react to external expansion for the matching provider', async () => {+ mockFetchModelProviderModels.mockResolvedValue({ data: [{ model: 'gpt-4' }] })+ renderWithQueryClient(+ <>+ <ProviderAddedCard provider={mockProvider} />+ <ExternalExpandControls />+ </>,+ )- fireEvent.click(screen.getByTestId('show-models-button'))-- expect(document.querySelector('.i-ri-loader-2-line.animate-spin')).toBeInTheDocument()-- await act(async () => {- resolvePromise({ data: [] })+ fireEvent.click(screen.getByTestId('expand-other-provider'))+ await waitFor(() => {+ expect(mockFetchModelProviderModels).toHaveBeenCalledTimes(0)})- })-- it('should show modelsNum text after models have loaded', async () => {- const models = [- { model: 'gpt-4' },- { model: 'gpt-3.5' },- ]- vi.mocked(fetchModelProviderModelList).mockResolvedValue({ data: models } as unknown as { data: ModelItem[] })-- render(<ProviderAddedCard provider={mockProvider} />)-- fireEvent.click(screen.getByTestId('show-models-button'))-- await screen.findByTestId('model-list')-- const collapseBtn = screen.getByRole('button', { name: 'collapse list' })- fireEvent.click(collapseBtn)-- await waitFor(() => expect(screen.queryByTestId('model-list')).not.toBeInTheDocument())-- const numTexts = screen.getAllByText(/modelProvider\.modelsNum/)- expect(numTexts.length).toBeGreaterThan(0)- expect(screen.getByText(/modelProvider\.showModelsNum/)).toBeInTheDocument()+ fireEvent.click(screen.getByTestId('expand-current-provider'))+ await waitFor(() => {+ expect(mockFetchModelProviderModels).toHaveBeenCalledWith(mockProvider.provider)+ })+ expect(mockFetchModelProviderModels).toHaveBeenCalledTimes(1)})it('should render configure tip when provider is not in quota list and not configured', () => {@@ -172,93 +192,23 @@ describe('ProviderAddedCard', () => {...mockProvider,provider: 'custom/provider',} as unknown as ModelProvider- render(<ProviderAddedCard provider={providerWithoutQuota} notConfigured />)+ renderWithQueryClient(<ProviderAddedCard provider={providerWithoutQuota} notConfigured />)expect(screen.getByText('common.modelProvider.configureTip')).toBeInTheDocument()})- it('should refresh model list on event subscription', async () => {- let capturedHandler: (v: { type: string, payload: string } | null) => void = () => { }- mockEventEmitter.useSubscription.mockImplementation((handler: (v: unknown) => void) => {- capturedHandler = handler as (v: { type: string, payload: string } | null) => void- })- vi.mocked(fetchModelProviderModelList).mockResolvedValue({ data: [] } as unknown as { data: ModelItem[] })-- render(<ProviderAddedCard provider={mockProvider} />)-- expect(capturedHandler).toBeDefined()- act(() => {- capturedHandler({- type: 'UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST',- payload: mockProvider.provider,- })- })-- await waitFor(() => {- expect(fetchModelProviderModelList).toHaveBeenCalledTimes(1)- })-- // Should ignore non-matching events- act(() => {- capturedHandler({ type: 'OTHER', payload: '' })- capturedHandler(null)- })- expect(fetchModelProviderModelList).toHaveBeenCalledTimes(1)- })-- it('should apply anthropic background class for anthropic provider', () => {- const anthropicProvider = {- ...mockProvider,- provider: 'langgenius/anthropic/anthropic',- } as unknown as ModelProvider- const { container } = render(<ProviderAddedCard provider={anthropicProvider} />)-- expect(container.querySelector('.bg-third-party-model-bg-anthropic')).toBeInTheDocument()- })-it('should render custom model actions for workspace managers', () => {const customConfigProvider = {...mockProvider,configurate_methods: [ConfigurationMethodEnum.customizableModel],} as unknown as ModelProvider- const { rerender } = render(<ProviderAddedCard provider={customConfigProvider} />)+ const { unmount } = renderWithQueryClient(<ProviderAddedCard provider={customConfigProvider} />)expect(screen.getByTestId('manage-custom-model')).toBeInTheDocument()expect(screen.getByTestId('add-custom-model')).toBeInTheDocument()+ unmount()mockIsCurrentWorkspaceManager = false- rerender(<ProviderAddedCard provider={customConfigProvider} />)+ renderWithQueryClient(<ProviderAddedCard provider={customConfigProvider} />)expect(screen.queryByTestId('manage-custom-model')).not.toBeInTheDocument()})-- it('should render credential panel when showCredential is true', () => {- // Arrange: use ConfigurationMethodEnum.predefinedModel ('predefined-model') so showCredential=true- const predefinedProvider = {- ...mockProvider,- configurate_methods: [ConfigurationMethodEnum.predefinedModel],- } as unknown as ModelProvider-- mockIsCurrentWorkspaceManager = true-- // Act- render(<ProviderAddedCard provider={predefinedProvider} />)-- // Assert: credential-panel is rendered (showCredential = true branch)- expect(screen.getByTestId('credential-panel')).toBeInTheDocument()- })-- it('should not render credential panel when user is not workspace manager', () => {- // Arrange: predefined-model but manager=false so showCredential=false- const predefinedProvider = {- ...mockProvider,- configurate_methods: [ConfigurationMethodEnum.predefinedModel],- } as unknown as ModelProvider-- mockIsCurrentWorkspaceManager = false-- // Act- render(<ProviderAddedCard provider={predefinedProvider} />)-- // Assert: credential-panel is not rendered (showCredential = false)- expect(screen.queryByTestId('credential-panel')).not.toBeInTheDocument()- })})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsxindex 2bac7863911..e42106aaf1f 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/model-list-item.spec.tsx@@ -1,9 +1,17 @@import type { ModelItem, ModelProvider } from '../../declarations'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { disableModel, enableModel } from '@/service/common'import { ModelStatusEnum } from '../../declarations'import ModelListItem from '../model-list-item'+function createWrapper() {+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })+ return ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ )+}+let mockModelLoadBalancingEnabled = falselet mockPlanType: string = 'pro'@@ -71,6 +79,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={false}/>,+ { wrapper: createWrapper() },)expect(screen.getByTestId('model-icon')).toBeInTheDocument()expect(screen.getByTestId('model-name')).toBeInTheDocument()@@ -85,6 +94,7 @@ describe('ModelListItem', () => {isConfigurable={false}onChange={onChange}/>,+ { wrapper: createWrapper() },)fireEvent.click(screen.getByRole('switch'))@@ -104,6 +114,7 @@ describe('ModelListItem', () => {isConfigurable={false}onChange={onChange}/>,+ { wrapper: createWrapper() },)fireEvent.click(screen.getByRole('switch'))@@ -124,6 +135,7 @@ describe('ModelListItem', () => {isConfigurable={false}onModifyLoadBalancing={onModifyLoadBalancing}/>,+ { wrapper: createWrapper() },)fireEvent.click(screen.getByRole('button', { name: 'modify load balancing' }))@@ -143,6 +155,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={false}/>,+ { wrapper: createWrapper() },)// Assert@@ -168,6 +181,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={false}/>,+ { wrapper: createWrapper() },)// Assert - Badge component should render@@ -188,6 +202,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={false}/>,+ { wrapper: createWrapper() },)// Assert - ConfigModel should show because plan.type === 'sandbox'@@ -207,6 +222,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={false}/>,+ { wrapper: createWrapper() },)// Assert - ConfigModel should NOT show because plan.type !== 'sandbox' and load balancing is disabled@@ -226,6 +242,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={false}/>,+ { wrapper: createWrapper() },)// Assert - ConfigModel should not render because status is not active/disabled@@ -247,6 +264,7 @@ describe('ModelListItem', () => {provider={mockProvider}isConfigurable={true}/>,+ { wrapper: createWrapper() },)// Assertdiff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsxindex d5ed91fb39d..a3e527680f2 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/__tests__/quota-panel.spec.tsx@@ -1,30 +1,45 @@import type { ModelProvider } from '../../declarations'import { fireEvent, render, screen, waitFor } from '@testing-library/react'-import userEvent from '@testing-library/user-event'import QuotaPanel from '../quota-panel'-let mockWorkspace = {+let mockWorkspaceData: {+ trial_credits: number+ trial_credits_used: number+ next_credit_reset_date: string+} | undefined = {trial_credits: 100,trial_credits_used: 30,next_credit_reset_date: '2024-12-31',}-let mockTrialModels: string[] = ['langgenius/openai/openai']+let mockWorkspaceIsPending = false+let mockTrialModels: string[] | undefined = ['langgenius/openai/openai']let mockPlugins = [{plugin_id: 'langgenius/openai',latest_package_identifier: '[email protected]',}]-vi.mock('@/context/app-context', () => ({- useAppContext: () => ({- currentWorkspace: mockWorkspace,+vi.mock('@/app/components/base/icons/src/public/llm', () => {+ const Icon = ({ label }: { label: string }) => <span>{label}</span>+ return {+ OpenaiSmall: () => <Icon label="openai" />,+ AnthropicShortLight: () => <Icon label="anthropic" />,+ Gemini: () => <Icon label="gemini" />,+ Grok: () => <Icon label="x" />,+ Deepseek: () => <Icon label="deepseek" />,+ Tongyi: () => <Icon label="tongyi" />,+ }+})++vi.mock('@/service/use-common', () => ({+ useCurrentWorkspace: () => ({+ data: mockWorkspaceData,+ isPending: mockWorkspaceIsPending,}),}))vi.mock('@/context/global-public-context', () => ({- useGlobalPublicStore: (selector: (state: { systemFeatures: { trial_models: string[] } }) => unknown) => selector({- systemFeatures: {- trial_models: mockTrialModels,- },+ useSystemFeaturesQuery: () => ({+ data: mockTrialModels ? { trial_models: mockTrialModels } : undefined,}),}))@@ -60,34 +75,21 @@ describe('QuotaPanel', () => {beforeEach(() => {vi.clearAllMocks()- mockWorkspace = {+ mockWorkspaceData = {trial_credits: 100,trial_credits_used: 30,next_credit_reset_date: '2024-12-31',}+ mockWorkspaceIsPending = falsemockTrialModels = ['langgenius/openai/openai']mockPlugins = [{ plugin_id: 'langgenius/openai', latest_package_identifier: '[email protected]' }]})- const getTrialProviderIconTrigger = (container: HTMLElement) => {- const providerIcon = container.querySelector('svg.h-6.w-6.rounded-lg')- expect(providerIcon).toBeInTheDocument()- const trigger = providerIcon?.closest('[data-state]') as HTMLDivElement | null- expect(trigger).toBeInTheDocument()- return trigger as HTMLDivElement- }-- const clickFirstTrialProviderIcon = (container: HTMLElement) => {- fireEvent.click(getTrialProviderIconTrigger(container))- }-it('should render loading state', () => {- render(- <QuotaPanel- providers={mockProviders}- isLoading- />,- )+ mockWorkspaceData = undefined+ mockWorkspaceIsPending = true++ render(<QuotaPanel providers={mockProviders} />)expect(screen.getByRole('status')).toBeInTheDocument()})@@ -103,8 +105,17 @@ describe('QuotaPanel', () => {expect(screen.getByText(/modelProvider\.resetDate/)).toBeInTheDocument()})+ it('should keep quota content during background refetch when cached workspace exists', () => {+ mockWorkspaceIsPending = true++ render(<QuotaPanel providers={mockProviders} />)++ expect(screen.queryByRole('status')).not.toBeInTheDocument()+ expect(screen.getByText('70')).toBeInTheDocument()+ })+it('should floor credits at zero when usage is higher than quota', () => {- mockWorkspace = {+ mockWorkspaceData = {trial_credits: 10,trial_credits_used: 999,next_credit_reset_date: '',@@ -112,22 +123,22 @@ describe('QuotaPanel', () => {render(<QuotaPanel providers={mockProviders} />)- expect(screen.getByText('0')).toBeInTheDocument()+ expect(screen.getByText(/modelProvider\.card\.quotaExhausted/)).toBeInTheDocument()expect(screen.queryByText(/modelProvider\.resetDate/)).not.toBeInTheDocument()})it('should open install modal when clicking an unsupported trial provider', () => {- const { container } = render(<QuotaPanel providers={[]} />)+ render(<QuotaPanel providers={[]} />)- clickFirstTrialProviderIcon(container)+ fireEvent.click(screen.getByText('openai'))expect(screen.getByText('install modal')).toBeInTheDocument()})it('should close install modal when provider becomes installed', async () => {- const { rerender, container } = render(<QuotaPanel providers={[]} />)+ const { rerender } = render(<QuotaPanel providers={[]} />)- clickFirstTrialProviderIcon(container)+ fireEvent.click(screen.getByText('openai'))expect(screen.getByText('install modal')).toBeInTheDocument()rerender(<QuotaPanel providers={mockProviders} />)@@ -137,60 +148,36 @@ describe('QuotaPanel', () => {})})- it('should not open install modal when clicking an already installed provider', () => {- const { container } = render(<QuotaPanel providers={mockProviders} />)-- clickFirstTrialProviderIcon(container)-- expect(screen.queryByText('install modal')).not.toBeInTheDocument()- })-- it('should not open install modal when plugin is not found in marketplace', () => {- mockPlugins = []- const { container } = render(<QuotaPanel providers={[]} />)+ it('should tolerate missing trial model configuration', () => {+ mockTrialModels = undefined- clickFirstTrialProviderIcon(container)+ render(<QuotaPanel providers={mockProviders} />)- expect(screen.queryByText('install modal')).not.toBeInTheDocument()+ expect(screen.queryByText('openai')).not.toBeInTheDocument()})- it('should show destructive border when credits are zero or negative', () => {- mockWorkspace = {- trial_credits: 0,- trial_credits_used: 0,- next_credit_reset_date: '',- }-- const { container } = render(<QuotaPanel providers={mockProviders} />)-- expect(container.querySelector('.border-state-destructive-border')).toBeInTheDocument()- })+ it('should render installed custom providers without opening the install modal', () => {+ render(<QuotaPanel providers={mockProviders} />)- it('should show modelAPI tooltip for configured provider with custom preference', async () => {- const user = userEvent.setup()- const { container } = render(<QuotaPanel providers={mockProviders} />)+ expect(screen.getByLabelText(/modelAPI/)).toBeInTheDocument()- const trigger = getTrialProviderIconTrigger(container)- await user.hover(trigger as HTMLElement)+ fireEvent.click(screen.getByText('openai'))- expect(await screen.findByText(/common\.modelProvider\.card\.modelAPI/)).toHaveTextContent('OpenAI')+ expect(screen.queryByText('install modal')).not.toBeInTheDocument()})- it('should show modelSupported tooltip for installed provider without custom config', async () => {- const user = userEvent.setup()- const systemProviders = [- {- provider: 'langgenius/openai/openai',- preferred_provider_type: 'system',- custom_configuration: { available_credentials: [] },- },- ] as unknown as ModelProvider[]-- const { container } = render(<QuotaPanel providers={systemProviders} />)-- const trigger = getTrialProviderIconTrigger(container)- await user.hover(trigger as HTMLElement)+ it('should show the supported-model tooltip for installed non-custom providers', () => {+ render(+ <QuotaPanel providers={[+ {+ provider: 'langgenius/openai/openai',+ preferred_provider_type: 'system',+ custom_configuration: { available_credentials: [] },+ },+ ] as unknown as ModelProvider[]}+ />,+ )- expect(await screen.findByText(/common\.modelProvider\.card\.modelSupported/)).toHaveTextContent('OpenAI')+ expect(screen.getByLabelText(/modelSupported/)).toBeInTheDocument()})})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/add-model-button.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/add-model-button.tsxdeleted file mode 100644index eac6567ac80..00000000000--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/add-model-button.tsx+++ /dev/null@@ -1,27 +0,0 @@-import type { FC } from 'react'-import { useTranslation } from 'react-i18next'-import { PlusCircle } from '@/app/components/base/icons/src/vender/solid/general'-import { cn } from '@/utils/classnames'--type AddModelButtonProps = {- className?: string- onClick: () => void-}-const AddModelButton: FC<AddModelButtonProps> = ({- className,- onClick,-}) => {- const { t } = useTranslation()-- return (- <span- className={cn('system-xs-medium flex h-6 shrink-0 cursor-pointer items-center rounded-md px-1.5 text-text-tertiary hover:bg-components-button-ghost-bg-hover hover:text-components-button-ghost-text', className)}- onClick={onClick}- >- <PlusCircle className="mr-1 h-3 w-3" />- {t('modelProvider.addModel', { ns: 'common' })}- </span>- )-}--export default AddModelButtondiff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/credential-panel.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/credential-panel.tsxindex efa768e7f58..67a30740e6d 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/credential-panel.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/credential-panel.tsx@@ -1,151 +1,105 @@-import type {- ModelProvider,-} from '../declarations'-import { useMemo } from 'react'+import type { ModelProvider } from '../declarations'+import type { CardVariant } from './use-credential-panel-state'+import { memo } from 'react'import { useTranslation } from 'react-i18next'-import { useToastContext } from '@/app/components/base/toast/context'-import { ConfigProvider } from '@/app/components/header/account-setting/model-provider-page/model-auth'-import { useCredentialStatus } from '@/app/components/header/account-setting/model-provider-page/model-auth/hooks'+import Warning from '@/app/components/base/icons/src/vender/line/alertsAndFeedback/Warning'import Indicator from '@/app/components/header/indicator'-import { IS_CLOUD_EDITION } from '@/config'-import { useEventEmitterContextContext } from '@/context/event-emitter'-import { changeModelProviderPriority } from '@/service/common'-import { cn } from '@/utils/classnames'-import {- ConfigurationMethodEnum,- CustomConfigurationStatusEnum,- PreferredProviderTypeEnum,-} from '../declarations'-import {- useUpdateModelList,- useUpdateModelProviders,-} from '../hooks'-import { UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST } from './index'-import PrioritySelector from './priority-selector'-import PriorityUseTip from './priority-use-tip'+import ModelAuthDropdown from './model-auth-dropdown'+import SystemQuotaCard from './system-quota-card'+import { useChangeProviderPriority } from './use-change-provider-priority'+import { isDestructiveVariant, useCredentialPanelState } from './use-credential-panel-state'type CredentialPanelProps = {provider: ModelProvider}+const TEXT_LABEL_VARIANTS = new Set<CardVariant>([+ 'credits-active',+ 'credits-fallback',+ 'credits-exhausted',+ 'no-usage',+ 'api-required-add',+ 'api-required-configure',+])+const CredentialPanel = ({provider,}: CredentialPanelProps) => {- const { t } = useTranslation()- const { notify } = useToastContext()- const { eventEmitter } = useEventEmitterContextContext()- const updateModelList = useUpdateModelList()- const updateModelProviders = useUpdateModelProviders()- const customConfig = provider.custom_configuration- const systemConfig = provider.system_configuration- const priorityUseType = provider.preferred_provider_type- const isCustomConfigured = customConfig.status === CustomConfigurationStatusEnum.active- const configurateMethods = provider.configurate_methods- const {- hasCredential,- authorized,- authRemoved,- current_credential_name,- notAllowedToUse,- } = useCredentialStatus(provider)+ const state = useCredentialPanelState(provider)+ const { isChangingPriority, handleChangePriority } = useChangeProviderPriority(provider)- const showPrioritySelector = systemConfig.enabled && isCustomConfigured && IS_CLOUD_EDITION+ const { variant, credentialName } = state+ const isDestructive = isDestructiveVariant(variant)+ const isTextLabel = TEXT_LABEL_VARIANTS.has(variant)+ const needsGap = !isTextLabel || variant === 'credits-fallback'- const handleChangePriority = async (key: PreferredProviderTypeEnum) => {- const res = await changeModelProviderPriority({- url: `/workspaces/current/model-providers/${provider.provider}/preferred-provider-type`,- body: {- preferred_provider_type: key,- },- })- if (res.result === 'success') {- notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })- updateModelProviders()+ return (+ <SystemQuotaCard variant={isDestructive ? 'destructive' : 'default'}>+ <SystemQuotaCard.Label className={needsGap ? 'gap-1' : undefined}>+ {isTextLabel+ ? <TextLabel variant={variant} />+ : <StatusLabel variant={variant} credentialName={credentialName} />}+ </SystemQuotaCard.Label>+ <SystemQuotaCard.Actions>+ <ModelAuthDropdown+ provider={provider}+ state={state}+ isChangingPriority={isChangingPriority}+ onChangePriority={handleChangePriority}+ />+ </SystemQuotaCard.Actions>+ </SystemQuotaCard>+ )+}- configurateMethods.forEach((method) => {- if (method === ConfigurationMethodEnum.predefinedModel)- provider.supported_model_types.forEach(modelType => updateModelList(modelType))- })+const TEXT_LABEL_KEYS = {+ 'credits-active': 'modelProvider.card.aiCreditsInUse',+ 'credits-fallback': 'modelProvider.card.aiCreditsInUse',+ 'credits-exhausted': 'modelProvider.card.quotaExhausted',+ 'no-usage': 'modelProvider.card.noAvailableUsage',+ 'api-required-add': 'modelProvider.card.apiKeyRequired',+ 'api-required-configure': 'modelProvider.card.apiKeyRequired',+} as const satisfies Partial<Record<CardVariant, string>>- eventEmitter?.emit({- type: UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST,- payload: provider.provider,- } as any)- }- }- const credentialLabel = useMemo(() => {- if (!hasCredential)- return t('modelProvider.auth.unAuthorized', { ns: 'common' })- if (authorized)- return current_credential_name- if (authRemoved)- return t('modelProvider.auth.authRemoved', { ns: 'common' })+function TextLabel({ variant }: { variant: CardVariant }) {+ const { t } = useTranslation()+ const isDestructive = isDestructiveVariant(variant)+ const labelKey = TEXT_LABEL_KEYS[variant as keyof typeof TEXT_LABEL_KEYS]- return ''- }, [authorized, authRemoved, current_credential_name, hasCredential])+ return (+ <>+ <span className={isDestructive ? 'text-text-destructive' : 'text-text-secondary'}>+ {t(labelKey, { ns: 'common' })}+ </span>+ {variant === 'credits-fallback' && (+ <Warning className="h-3 w-3 shrink-0 text-text-warning" />+ )}+ </>+ )+}- const color = useMemo(() => {- if (authRemoved || !hasCredential)- return 'red'- if (notAllowedToUse)- return 'gray'- return 'green'- }, [authRemoved, notAllowedToUse, hasCredential])+function StatusLabel({ variant, credentialName }: {+ variant: CardVariant+ credentialName: string | undefined+}) {+ const isDestructive = isDestructiveVariant(variant)+ const dotColor = isDestructive ? 'red' : 'green'+ const showWarning = variant === 'api-fallback'return (<>- {- provider.provider_credential_schema && (- <div className={cn(- 'relative ml-1 w-[120px] shrink-0 rounded-lg border-[0.5px] border-components-panel-border bg-white/[0.18] p-1',- authRemoved && 'border-state-destructive-border bg-state-destructive-hover',- )}- >- <div className="system-xs-medium mb-1 flex h-5 items-center justify-between pl-2 pr-[7px] pt-1 text-text-tertiary">- <div- className={cn(- 'grow truncate',- authRemoved && 'text-text-destructive',- )}- title={credentialLabel}- >- {credentialLabel}- </div>- <Indicator className="shrink-0" color={color} />- </div>- <div className="flex items-center gap-0.5">- <ConfigProvider- provider={provider}- />- {- showPrioritySelector && (- <PrioritySelector- value={priorityUseType}- onSelect={handleChangePriority}- />- )- }- </div>- {- priorityUseType === PreferredProviderTypeEnum.custom && systemConfig.enabled && (- <PriorityUseTip />- )- }- </div>- )- }- {- showPrioritySelector && !provider.provider_credential_schema && (- <div className="ml-1">- <PrioritySelector- value={priorityUseType}- onSelect={handleChangePriority}- />- </div>- )- }+ <Indicator className="shrink-0" color={dotColor} />+ <span+ className={`truncate ${isDestructive ? 'text-text-destructive' : 'text-text-secondary'}`}+ title={credentialName}+ >+ {credentialName}+ </span>+ {showWarning && (+ <Warning className="ml-auto h-3 w-3 shrink-0 text-text-warning" />+ )}</>)}-export default CredentialPanel+export default memo(CredentialPanel)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsxindex 3243e5ac861..183b15be336 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx@@ -1,11 +1,12 @@import type { FC } from 'react'import type {- ModelItem,ModelProvider,} from '../declarations'import type { ModelProviderQuotaGetPaid } from '../utils'+import type { PluginDetail } from '@/app/components/plugins/types'-import { useState } from 'react'+import { useQuery } from '@tanstack/react-query'+import { memo, useCallback } from 'react'import { useTranslation } from 'react-i18next'import {AddCustomModel,@@ -13,9 +14,10 @@ import {} from '@/app/components/header/account-setting/model-provider-page/model-auth'import { IS_CE_EDITION } from '@/config'import { useAppContext } from '@/context/app-context'-import { useEventEmitterContextContext } from '@/context/event-emitter'-import { fetchModelProviderModelList } from '@/service/common'+import { useProviderContextSelector } from '@/context/provider-context'+import { consoleQuery } from '@/service/client'import { cn } from '@/utils/classnames'+import { useModelProviderListExpanded, useSetModelProviderListExpanded } from '../atoms'import { ConfigurationMethodEnum } from '../declarations'import ModelBadge from '../model-badge'import ProviderIcon from '../provider-icon'@@ -25,121 +27,123 @@ import {} from '../utils'import CredentialPanel from './credential-panel'import ModelList from './model-list'+import ProviderCardActions from './provider-card-actions'-export const UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST = 'UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST'type ProviderAddedCardProps = {notConfigured?: booleanprovider: ModelProvider+ pluginDetail?: PluginDetail}const ProviderAddedCard: FC<ProviderAddedCardProps> = ({notConfigured,provider,+ pluginDetail,}) => {const { t } = useTranslation()- const { eventEmitter } = useEventEmitterContextContext()- const [fetched, setFetched] = useState(false)- const [loading, setLoading] = useState(false)- const [collapsed, setCollapsed] = useState(true)- const [modelList, setModelList] = useState<ModelItem[]>([])- const configurationMethods = provider.configurate_methods.filter(method => method !== ConfigurationMethodEnum.fetchFromRemote)+ const refreshModelProviders = useProviderContextSelector(state => state.refreshModelProviders)+ const currentProviderName = provider.provider+ const expanded = useModelProviderListExpanded(currentProviderName)+ const setExpanded = useSetModelProviderListExpanded(currentProviderName)+ const supportsPredefinedModel = provider.configurate_methods.includes(ConfigurationMethodEnum.predefinedModel)+ const supportsCustomizableModel = provider.configurate_methods.includes(ConfigurationMethodEnum.customizableModel)const systemConfig = provider.system_configuration- const hasModelList = fetched && !!modelList.length+ const {+ data: modelList = [],+ isFetching: loading,+ isSuccess: hasFetchedModelList,+ refetch: refetchModelList,+ } = useQuery(consoleQuery.modelProviders.models.queryOptions({+ input: { params: { provider: currentProviderName } },+ enabled: expanded,+ refetchOnWindowFocus: false,+ select: response => response.data,+ }))+ const hasModelList = hasFetchedModelList && !!modelList.length+ const showCollapsedSection = !expanded || !hasFetchedModelListconst { isCurrentWorkspaceManager } = useAppContext()- const showModelProvider = systemConfig.enabled && MODEL_PROVIDER_QUOTA_GET_PAID.includes(provider.provider as ModelProviderQuotaGetPaid) && !IS_CE_EDITION- const showCredential = configurationMethods.includes(ConfigurationMethodEnum.predefinedModel) && isCurrentWorkspaceManager+ const showModelProvider = systemConfig.enabled && MODEL_PROVIDER_QUOTA_GET_PAID.includes(currentProviderName as ModelProviderQuotaGetPaid) && !IS_CE_EDITION+ const showCredential = supportsPredefinedModel && isCurrentWorkspaceManager+ const showCustomModelActions = supportsCustomizableModel && isCurrentWorkspaceManager- const getModelList = async (providerName: string) => {+ const refreshModelList = useCallback((targetProviderName: string) => {+ if (targetProviderName !== currentProviderName)+ return++ if (!expanded)+ setExpanded(true)++ refetchModelList().catch(() => {})+ }, [currentProviderName, expanded, refetchModelList, setExpanded])++ const handleOpenModelList = useCallback(() => {if (loading)return- try {- setLoading(true)- const modelsData = await fetchModelProviderModelList(`/workspaces/current/model-providers/${providerName}/models`)- setModelList(modelsData.data)- setCollapsed(false)- setFetched(true)- }- finally {- setLoading(false)- }- }- const handleOpenModelList = () => {- if (fetched) {- setCollapsed(false)++ if (!expanded) {+ setExpanded(true)return}- getModelList(provider.provider)- }-- eventEmitter?.useSubscription((v: any) => {- if (v?.type === UPDATE_MODEL_PROVIDER_CUSTOM_MODEL_LIST && v.payload === provider.provider)- getModelList(v.payload)- })+ refetchModelList().catch(() => {})+ }, [expanded, loading, refetchModelList, setExpanded])return (<divdata-testid="provider-added-card"className={cn('mb-2 rounded-xl border-[0.5px] border-divider-regular bg-third-party-model-bg-default shadow-xs',- provider.provider === 'langgenius/openai/openai' && 'bg-third-party-model-bg-openai',- provider.provider === 'langgenius/anthropic/anthropic' && 'bg-third-party-model-bg-anthropic',+ currentProviderName === 'langgenius/openai/openai' && 'bg-third-party-model-bg-openai',+ currentProviderName === 'langgenius/anthropic/anthropic' && 'bg-third-party-model-bg-anthropic',)}><div className="flex rounded-t-xl py-2 pl-3 pr-2"><div className="grow px-1 pb-0.5 pt-1">- <ProviderIcon- className="mb-2"- provider={provider}- />+ <div className="mb-2 flex items-center gap-1">+ <ProviderIcon provider={provider} />+ {pluginDetail && (+ <ProviderCardActions+ detail={pluginDetail}+ onUpdate={refreshModelProviders}+ />+ )}+ </div><div className="flex gap-0.5">- {- provider.supported_model_types.map(modelType => (- <ModelBadge key={modelType}>- {modelTypeFormat(modelType)}- </ModelBadge>- ))- }+ {provider.supported_model_types.map(modelType => (+ <ModelBadge key={modelType}>+ {modelTypeFormat(modelType)}+ </ModelBadge>+ ))}</div></div>- {- showCredential && (- <CredentialPanel- provider={provider}- />- )- }+ {showCredential && (+ <CredentialPanel+ provider={provider}+ />+ )}</div>{- collapsed && (+ showCollapsedSection && (<div className="group flex items-center justify-between border-t border-t-divider-subtle py-1.5 pl-2 pr-[11px] text-text-tertiary system-xs-medium">{(showModelProvider || !notConfigured) && (- <>- <div className="flex h-6 items-center pl-1 pr-1.5 leading-6 group-hover:hidden">- {- hasModelList- ? t('modelProvider.modelsNum', { ns: 'common', num: modelList.length })- : t('modelProvider.showModels', { ns: 'common' })- }- {!loading && <div className="i-ri-arrow-right-s-line h-4 w-4" />}- </div>- <div- data-testid="show-models-button"- className="hidden h-6 cursor-pointer items-center rounded-lg pl-1 pr-1.5 hover:bg-components-button-ghost-bg-hover group-hover:flex"- onClick={handleOpenModelList}- >- {- hasModelList- ? t('modelProvider.showModelsNum', { ns: 'common', num: modelList.length })- : t('modelProvider.showModels', { ns: 'common' })- }- {!loading && <div className="i-ri-arrow-right-s-line h-4 w-4" />}- {- loading && (- <div className="i-ri-loader-2-line ml-0.5 h-3 w-3 animate-spin" />- )- }- </div>- </>+ <button+ type="button"+ data-testid="show-models-button"+ className="flex h-6 items-center rounded-lg pl-1 pr-1.5 hover:bg-components-button-ghost-bg-hover"+ aria-label={t('modelProvider.showModels', { ns: 'common' })}+ onClick={handleOpenModelList}+ >+ {+ hasModelList+ ? t('modelProvider.modelsNum', { ns: 'common', num: modelList.length })+ : t('modelProvider.showModels', { ns: 'common' })+ }+ {!loading && <div className="i-ri-arrow-right-s-line h-4 w-4" />}+ {+ loading && (+ <div className="i-ri-loader-2-line ml-0.5 h-3 w-3 animate-spin" />+ )+ }+ </button>)}{!showModelProvider && notConfigured && (<div className="flex h-6 items-center pl-1 pr-1.5">@@ -148,7 +152,7 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({</div>)}{- configurationMethods.includes(ConfigurationMethodEnum.customizableModel) && isCurrentWorkspaceManager && (+ showCustomModelActions && (<div className="flex grow justify-end"><ManageCustomModelCredentialsprovider={provider}@@ -166,12 +170,12 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({)}{- !collapsed && (+ !showCollapsedSection && (<ModelListprovider={provider}models={modelList}- onCollapse={() => setCollapsed(true)}- onChange={(provider: string) => getModelList(provider)}+ onCollapse={() => setExpanded(false)}+ onChange={refreshModelList}/>)}@@ -179,4 +183,4 @@ const ProviderAddedCard: FC<ProviderAddedCardProps> = ({)}-export default ProviderAddedCard+export default memo(ProviderAddedCard)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.spec.tsxnew file mode 100644index 00000000000..95724df0293--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.spec.tsx@@ -0,0 +1,142 @@+import type { Credential, ModelProvider } from '../../declarations'+import { fireEvent, render, screen } from '@testing-library/react'+import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../declarations'+import ApiKeySection from './api-key-section'++const createCredential = (overrides: Partial<Credential> = {}): Credential => ({+ credential_id: 'cred-1',+ credential_name: 'Test API Key',+ ...overrides,+})++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'test-provider',+ allow_custom_token: true,+ 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)++describe('ApiKeySection', () => {+ const handlers = {+ onItemClick: vi.fn(),+ onEdit: vi.fn(),+ onDelete: vi.fn(),+ onAdd: vi.fn(),+ }++ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Empty state+ describe('Empty state (no credentials)', () => {+ it('should show empty state message', () => {+ render(+ <ApiKeySection+ provider={createProvider()}+ credentials={[]}+ selectedCredentialId={undefined}+ {...handlers}+ />,+ )++ expect(screen.getByText(/noApiKeysTitle/)).toBeInTheDocument()+ expect(screen.getByText(/noApiKeysDescription/)).toBeInTheDocument()+ })++ it('should show Add API Key button', () => {+ render(+ <ApiKeySection+ provider={createProvider()}+ credentials={[]}+ selectedCredentialId={undefined}+ {...handlers}+ />,+ )++ expect(screen.getByRole('button', { name: /addApiKey/ })).toBeInTheDocument()+ })++ it('should call onAdd when Add API Key is clicked', () => {+ render(+ <ApiKeySection+ provider={createProvider()}+ credentials={[]}+ selectedCredentialId={undefined}+ {...handlers}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /addApiKey/ }))++ expect(handlers.onAdd).toHaveBeenCalledTimes(1)+ })++ it('should hide Add API Key button when allow_custom_token is false', () => {+ render(+ <ApiKeySection+ provider={createProvider({ allow_custom_token: false })}+ credentials={[]}+ selectedCredentialId={undefined}+ {...handlers}+ />,+ )++ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()+ })+ })++ // With credentials+ describe('With credentials', () => {+ const credentials = [+ createCredential({ credential_id: 'cred-1', credential_name: 'Key Alpha' }),+ createCredential({ credential_id: 'cred-2', credential_name: 'Key Beta' }),+ ]++ it('should render credential list with header', () => {+ render(+ <ApiKeySection+ provider={createProvider()}+ credentials={credentials}+ selectedCredentialId="cred-1"+ {...handlers}+ />,+ )++ expect(screen.getByText(/apiKeys/)).toBeInTheDocument()+ expect(screen.getByText('Key Alpha')).toBeInTheDocument()+ expect(screen.getByText('Key Beta')).toBeInTheDocument()+ })++ it('should show Add API Key button in footer', () => {+ render(+ <ApiKeySection+ provider={createProvider()}+ credentials={credentials}+ selectedCredentialId="cred-1"+ {...handlers}+ />,+ )++ expect(screen.getByRole('button', { name: /addApiKey/ })).toBeInTheDocument()+ })++ it('should hide Add API Key when allow_custom_token is false', () => {+ render(+ <ApiKeySection+ provider={createProvider({ allow_custom_token: false })}+ credentials={credentials}+ selectedCredentialId="cred-1"+ {...handlers}+ />,+ )++ expect(screen.queryByRole('button', { name: /addApiKey/ })).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsxnew file mode 100644index 00000000000..79b53b2eb91--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/api-key-section.tsx@@ -0,0 +1,91 @@+import type { Credential, CustomModel, ModelProvider } from '../../declarations'+import { memo } from 'react'+import { useTranslation } from 'react-i18next'+import Button from '@/app/components/base/button'+import CredentialItem from '../../model-auth/authorized/credential-item'++type ApiKeySectionProps = {+ provider: ModelProvider+ credentials: Credential[]+ selectedCredentialId: string | undefined+ isActivating?: boolean+ onItemClick: (credential: Credential, model?: CustomModel) => void+ onEdit: (credential?: Credential) => void+ onDelete: (credential?: Credential) => void+ onAdd: () => void+}++function ApiKeySection({+ provider,+ credentials,+ selectedCredentialId,+ isActivating,+ onItemClick,+ onEdit,+ onDelete,+ onAdd,+}: ApiKeySectionProps) {+ const { t } = useTranslation()+ const notAllowCustomCredential = provider.allow_custom_token === false++ if (!credentials.length) {+ return (+ <div className="flex flex-col gap-2 p-2">+ <div className="rounded-[10px] bg-gradient-to-r from-state-base-hover to-transparent p-4">+ <div className="flex flex-col gap-1">+ <div className="text-text-secondary system-sm-medium">+ {t('modelProvider.card.noApiKeysTitle', { ns: 'common' })}+ </div>+ <div className="text-text-tertiary system-xs-regular">+ {t('modelProvider.card.noApiKeysDescription', { ns: 'common' })}+ </div>+ </div>+ </div>+ {!notAllowCustomCredential && (+ <Button+ onClick={onAdd}+ className="w-full"+ >+ {t('modelProvider.auth.addApiKey', { ns: 'common' })}+ </Button>+ )}+ </div>+ )+ }++ return (+ <div className="border-t border-t-divider-subtle">+ <div className="px-1">+ <div className="pb-1 pl-7 pr-2 pt-3 text-text-tertiary system-xs-medium-uppercase">+ {t('modelProvider.auth.apiKeys', { ns: 'common' })}+ </div>+ <div className="max-h-[200px] overflow-y-auto">+ {credentials.map(credential => (+ <CredentialItem+ key={credential.credential_id}+ credential={credential}+ disabled={isActivating}+ showSelectedIcon+ selectedCredentialId={selectedCredentialId}+ onItemClick={onItemClick}+ onEdit={onEdit}+ onDelete={onDelete}+ />+ ))}+ </div>+ </div>+ {!notAllowCustomCredential && (+ <div className="p-2">+ <Button+ onClick={onAdd}+ className="w-full"+ >+ {t('modelProvider.auth.addApiKey', { ns: 'common' })}+ </Button>+ </div>+ )}+ </div>+ )+}++export default memo(ApiKeySection)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.spec.tsxnew file mode 100644index 00000000000..c1c5d33cf4e--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.spec.tsx@@ -0,0 +1,104 @@+import type { ReactNode } from 'react'+import { fireEvent, render, screen } from '@testing-library/react'+import CreditsExhaustedAlert from './credits-exhausted-alert'++const mockTrialCredits = { credits: 0, totalCredits: 10_000, isExhausted: true, isLoading: false, nextCreditResetDate: undefined }+const mockSetShowPricingModal = vi.fn()++vi.mock('react-i18next', async (importOriginal) => {+ const actual = await importOriginal<typeof import('react-i18next')>()+ return {+ ...actual,+ Trans: ({+ i18nKey,+ components,+ }: {+ i18nKey?: string+ components: { upgradeLink: ReactNode }+ }) => (+ <>+ {i18nKey}+ {components.upgradeLink}+ </>+ ),+ }+})++vi.mock('../use-trial-credits', () => ({+ useTrialCredits: () => mockTrialCredits,+}))++vi.mock('@/context/modal-context', () => ({+ useModalContextSelector: () => mockSetShowPricingModal,+}))++describe('CreditsExhaustedAlert', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ Object.assign(mockTrialCredits, { credits: 0, totalCredits: 10_000 })+ })++ // Without API key fallback+ describe('Without API key fallback', () => {+ it('should show exhausted message', () => {+ render(<CreditsExhaustedAlert hasApiKeyFallback={false} />)++ expect(screen.getByText(/creditsExhaustedMessage/)).toBeInTheDocument()+ })++ it('should show description with upgrade link', () => {+ render(<CreditsExhaustedAlert hasApiKeyFallback={false} />)++ expect(screen.getByText(/creditsExhaustedDescription/)).toBeInTheDocument()+ })+ })++ // With API key fallback+ describe('With API key fallback', () => {+ it('should show fallback message', () => {+ render(<CreditsExhaustedAlert hasApiKeyFallback />)++ expect(screen.getByText(/creditsExhaustedFallback(?!Description)/)).toBeInTheDocument()+ })++ it('should show fallback description', () => {+ render(<CreditsExhaustedAlert hasApiKeyFallback />)++ expect(screen.getByText(/creditsExhaustedFallbackDescription/)).toBeInTheDocument()+ })+ })++ // Usage display+ describe('Usage display', () => {+ it('should show usage label', () => {+ render(<CreditsExhaustedAlert hasApiKeyFallback={false} />)++ expect(screen.getByText(/usageLabel/)).toBeInTheDocument()+ })++ it('should show usage amounts', () => {+ mockTrialCredits.credits = 200++ render(<CreditsExhaustedAlert hasApiKeyFallback={false} />)++ expect(screen.getByText(/9,800/)).toBeInTheDocument()+ expect(screen.getByText(/10,000/)).toBeInTheDocument()+ })++ it('should cap progress at 100 percent when total credits are zero', () => {+ Object.assign(mockTrialCredits, { credits: 0, totalCredits: 0 })++ const { container } = render(<CreditsExhaustedAlert hasApiKeyFallback={false} />)++ expect(container.querySelector('.bg-components-progress-error-progress')).toHaveStyle({ width: '100%' })+ })++ it('should open the pricing modal when the upgrade link is clicked', () => {+ const { container } = render(<CreditsExhaustedAlert hasApiKeyFallback={false} />)++ fireEvent.click(container.querySelector('button') as HTMLButtonElement)++ expect(mockSetShowPricingModal).toHaveBeenCalledTimes(1)+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.stories.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.stories.tsxnew file mode 100644index 00000000000..904617fdef5--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.stories.tsx@@ -0,0 +1,78 @@+import type { Meta, StoryObj } from '@storybook/nextjs-vite'+import type { ICurrentWorkspace } from '@/models/common'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import CreditsExhaustedAlert from './credits-exhausted-alert'++const baseWorkspace: ICurrentWorkspace = {+ id: 'ws-1',+ name: 'Test Workspace',+ plan: 'sandbox',+ status: 'normal',+ created_at: Date.now(),+ role: 'owner',+ providers: [],+ trial_credits: 200,+ trial_credits_used: 200,+ next_credit_reset_date: Date.now() + 86400000,+}++function createSeededQueryClient(overrides?: Partial<ICurrentWorkspace>) {+ const qc = new QueryClient({+ defaultOptions: { queries: { refetchOnWindowFocus: false, retry: false } },+ })+ qc.setQueryData(['common', 'current-workspace'], { ...baseWorkspace, ...overrides })+ return qc+}++const meta = {+ title: 'ModelProvider/CreditsExhaustedAlert',+ component: CreditsExhaustedAlert,+ parameters: {+ layout: 'centered',+ docs: {+ description: {+ component: 'Alert shown when trial credits are exhausted, with usage progress bar and upgrade link.',+ },+ },+ },+ tags: ['autodocs'],+ decorators: [+ (Story) => {+ return (+ <QueryClientProvider client={createSeededQueryClient()}>+ <div className="w-[320px]">+ <Story />+ </div>+ </QueryClientProvider>+ )+ },+ ],+ args: {+ hasApiKeyFallback: false,+ },+} satisfies Meta<typeof CreditsExhaustedAlert>++export default meta+type Story = StoryObj<typeof meta>++export const Default: Story = {}++export const WithApiKeyFallback: Story = {+ args: {+ hasApiKeyFallback: true,+ },+}++export const PartialUsage: Story = {+ decorators: [+ (Story) => {+ return (+ <QueryClientProvider client={createSeededQueryClient({ trial_credits: 500, trial_credits_used: 480 })}>+ <div className="w-[320px]">+ <Story />+ </div>+ </QueryClientProvider>+ )+ },+ ],+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsxnew file mode 100644index 00000000000..802afd931bb--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-exhausted-alert.tsx@@ -0,0 +1,71 @@+import { Trans, useTranslation } from 'react-i18next'+import { CreditsCoin } from '@/app/components/base/icons/src/vender/line/financeAndECommerce'+import { useModalContextSelector } from '@/context/modal-context'+import { formatNumber } from '@/utils/format'+import { useTrialCredits } from '../use-trial-credits'++type CreditsExhaustedAlertProps = {+ hasApiKeyFallback: boolean+}++export default function CreditsExhaustedAlert({ hasApiKeyFallback }: CreditsExhaustedAlertProps) {+ const { t } = useTranslation()+ const setShowPricingModal = useModalContextSelector(s => s.setShowPricingModal)+ const { credits, totalCredits } = useTrialCredits()++ const titleKey = hasApiKeyFallback+ ? 'modelProvider.card.creditsExhaustedFallback'+ : 'modelProvider.card.creditsExhaustedMessage'+ const descriptionKey = hasApiKeyFallback+ ? 'modelProvider.card.creditsExhaustedFallbackDescription'+ : 'modelProvider.card.creditsExhaustedDescription'++ const usedCredits = totalCredits - credits+ const usagePercent = totalCredits > 0 ? Math.min((usedCredits / totalCredits) * 100, 100) : 100++ return (+ <div className="mx-2 mb-1 mt-0.5 rounded-lg bg-background-section-burn p-3">+ <div className="flex flex-col gap-1">+ <div className="text-text-primary system-sm-medium">+ {t(titleKey, { ns: 'common' })}+ </div>+ <div className="text-text-tertiary system-xs-regular">+ <Trans+ i18nKey={descriptionKey}+ ns="common"+ components={{+ upgradeLink: (+ <button+ type="button"+ className="cursor-pointer border-0 bg-transparent p-0 text-left text-text-accent system-xs-medium"+ onClick={() => setShowPricingModal()}+ />+ ),+ }}+ />+ </div>+ </div>+ <div className="mt-3 flex flex-col gap-1">+ <div className="flex items-center justify-between">+ <span className="text-text-tertiary system-xs-medium">+ {t('modelProvider.card.usageLabel', { ns: 'common' })}+ </span>+ <div className="flex items-center gap-0.5 text-text-tertiary system-xs-regular">+ <CreditsCoin className="h-3 w-3" />+ <span>+ {formatNumber(usedCredits)}+ /+ {formatNumber(totalCredits)}+ </span>+ </div>+ </div>+ <div className="h-1 overflow-hidden rounded-[6px] bg-components-progress-error-bg">+ <div+ className="h-full rounded-l-[6px] bg-components-progress-error-progress"+ style={{ width: `${usagePercent}%` }}+ />+ </div>+ </div>+ </div>+ )+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-fallback-alert.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-fallback-alert.tsxnew file mode 100644index 00000000000..bc7feb33977--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/credits-fallback-alert.tsx@@ -0,0 +1,28 @@+import { useTranslation } from 'react-i18next'++type CreditsFallbackAlertProps = {+ hasCredentials: boolean+}++export default function CreditsFallbackAlert({ hasCredentials }: CreditsFallbackAlertProps) {+ const { t } = useTranslation()++ const titleKey = hasCredentials+ ? 'modelProvider.card.apiKeyUnavailableFallback'+ : 'modelProvider.card.noApiKeysFallback'++ return (+ <div className="mx-2 mb-1 mt-0.5 rounded-lg bg-background-section-burn p-3">+ <div className="flex flex-col gap-1">+ <div className="text-text-primary system-sm-medium">+ {t(titleKey, { ns: 'common' })}+ </div>+ {hasCredentials && (+ <div className="text-text-tertiary system-xs-regular">+ {t('modelProvider.card.apiKeyUnavailableFallbackDescription', { ns: 'common' })}+ </div>+ )}+ </div>+ </div>+ )+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dialog.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dialog.spec.tsxnew file mode 100644index 00000000000..f13125bb4d2--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dialog.spec.tsx@@ -0,0 +1,152 @@+import type { ReactNode } from 'react'+import type { ModelProvider } from '../../declarations'+import type { CredentialPanelState } from '../use-credential-panel-state'+import { act, fireEvent, render, screen } from '@testing-library/react'+import DropdownContent from './dropdown-content'++type AlertDialogProps = {+ children: ReactNode+ onOpenChange?: (open: boolean) => void+}++let latestOnOpenChange: AlertDialogProps['onOpenChange']+const mockOpenConfirmDelete = vi.fn()+const mockCloseConfirmDelete = vi.fn()+const mockHandleConfirmDelete = vi.fn()+const mockHandleOpenModal = vi.fn()++vi.mock('../../model-auth/hooks', () => ({+ useAuth: () => ({+ openConfirmDelete: mockOpenConfirmDelete,+ closeConfirmDelete: mockCloseConfirmDelete,+ doingAction: false,+ handleConfirmDelete: mockHandleConfirmDelete,+ deleteCredentialId: 'cred-1',+ handleOpenModal: mockHandleOpenModal,+ }),+}))++vi.mock('./use-activate-credential', () => ({+ useActivateCredential: () => ({+ selectedCredentialId: 'cred-1',+ isActivating: false,+ activate: vi.fn(),+ }),+}))++vi.mock('@/app/components/base/ui/alert-dialog', () => ({+ AlertDialog: ({ children, onOpenChange }: AlertDialogProps) => {+ latestOnOpenChange = onOpenChange+ return <div>{children}</div>+ },+ AlertDialogActions: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ AlertDialogCancelButton: ({ children }: { children: ReactNode }) => <button type="button">{children}</button>,+ AlertDialogConfirmButton: ({ children, onClick }: { children: ReactNode, onClick?: () => void }) => <button type="button" onClick={onClick}>{children}</button>,+ AlertDialogContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ AlertDialogDescription: () => <div />,+ AlertDialogTitle: ({ children }: { children: ReactNode }) => <div>{children}</div>,+}))++vi.mock('./api-key-section', () => ({+ default: ({ credentials, onDelete }: { credentials: unknown[], onDelete: (credential?: unknown) => void }) => (+ <div>+ <span>{`credentials:${credentials.length}`}</span>+ <button type="button" onClick={() => onDelete(undefined)}>delete-undefined</button>+ </div>+ ),+}))++vi.mock('./credits-exhausted-alert', () => ({+ default: () => <div>credits alert</div>,+}))++vi.mock('./credits-fallback-alert', () => ({+ default: () => <div>fallback alert</div>,+}))++vi.mock('./usage-priority-section', () => ({+ default: () => <div>priority section</div>,+}))++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'test',+ custom_configuration: {+ available_credentials: undefined,+ },+ system_configuration: {+ enabled: true,+ quota_configurations: [],+ current_quota_type: 'trial',+ },+ configurate_methods: [],+ supported_model_types: [],+ ...overrides,+} as unknown as ModelProvider)++const createState = (overrides: Partial<CredentialPanelState> = {}): CredentialPanelState => ({+ variant: 'api-active',+ priority: 'apiKey',+ supportsCredits: true,+ showPrioritySwitcher: false,+ hasCredentials: false,+ isCreditsExhausted: false,+ credentialName: undefined,+ credits: 0,+ ...overrides,+})++describe('DropdownContent dialog branches', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ latestOnOpenChange = undefined+ })++ it('should fall back to an empty credential list when the provider has no credentials', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={vi.fn()}+ onClose={vi.fn()}+ />,+ )++ expect(screen.getByText('credentials:0')).toBeInTheDocument()+ })++ it('should ignore delete requests without a credential payload', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={vi.fn()}+ onClose={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: 'delete-undefined' }))++ expect(mockOpenConfirmDelete).not.toHaveBeenCalled()+ })++ it('should only close the confirm dialog when the alert dialog reports closed', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={vi.fn()}+ onClose={vi.fn()}+ />,+ )++ act(() => {+ latestOnOpenChange?.(true)+ latestOnOpenChange?.(false)+ })++ expect(mockCloseConfirmDelete).toHaveBeenCalledTimes(1)+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dropdown-content.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dropdown-content.spec.tsxnew file mode 100644index 00000000000..c1bdd518e5a--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dropdown-content.spec.tsx@@ -0,0 +1,435 @@+import type { ModelProvider } from '../../declarations'+import type { CredentialPanelState } from '../use-credential-panel-state'+import { fireEvent, render, screen } from '@testing-library/react'+import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../declarations'+import DropdownContent from './dropdown-content'++const mockHandleOpenModal = vi.fn()+const mockActivate = vi.fn()+const mockOpenConfirmDelete = vi.fn()+const mockCloseConfirmDelete = vi.fn()+const mockHandleConfirmDelete = vi.fn()+let mockDeleteCredentialId: string | null = null++vi.mock('../use-trial-credits', () => ({+ useTrialCredits: () => ({ credits: 0, totalCredits: 10_000, isExhausted: true, isLoading: false }),+}))++vi.mock('./use-activate-credential', () => ({+ useActivateCredential: () => ({+ selectedCredentialId: 'cred-1',+ isActivating: false,+ activate: mockActivate,+ }),+}))++vi.mock('../../model-auth/hooks', () => ({+ useAuth: () => ({+ openConfirmDelete: mockOpenConfirmDelete,+ closeConfirmDelete: mockCloseConfirmDelete,+ doingAction: false,+ handleConfirmDelete: mockHandleConfirmDelete,+ deleteCredentialId: mockDeleteCredentialId,+ handleOpenModal: mockHandleOpenModal,+ }),+}))++vi.mock('../../model-auth/authorized/credential-item', () => ({+ default: ({ credential, onItemClick, onEdit, onDelete }: {+ credential: { credential_id: string, credential_name: string }+ onItemClick?: (c: unknown) => void+ onEdit?: (c: unknown) => void+ onDelete?: (c: unknown) => void+ }) => (+ <div data-testid={`credential-${credential.credential_id}`}>+ <span>{credential.credential_name}</span>+ <button data-testid={`click-${credential.credential_id}`} onClick={() => onItemClick?.(credential)}>select</button>+ <button data-testid={`edit-${credential.credential_id}`} onClick={() => onEdit?.(credential)}>edit</button>+ <button data-testid={`delete-${credential.credential_id}`} onClick={() => onDelete?.(credential)}>delete</button>+ </div>+ ),+}))++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'test',+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: 'cred-1',+ current_credential_name: 'My Key',+ available_credentials: [+ { credential_id: 'cred-1', credential_name: 'My Key' },+ { credential_id: 'cred-2', credential_name: 'Other Key' },+ ],+ },+ system_configuration: { enabled: true, current_quota_type: 'trial', quota_configurations: [] },+ preferred_provider_type: PreferredProviderTypeEnum.system,+ configurate_methods: ['predefined-model'],+ supported_model_types: ['llm'],+ ...overrides,+} as unknown as ModelProvider)++const createState = (overrides: Partial<CredentialPanelState> = {}): CredentialPanelState => ({+ variant: 'api-active',+ priority: 'apiKey',+ supportsCredits: true,+ showPrioritySwitcher: true,+ hasCredentials: true,+ isCreditsExhausted: false,+ credentialName: 'My Key',+ credits: 100,+ ...overrides,+})++describe('DropdownContent', () => {+ const onChangePriority = vi.fn()+ const onClose = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ mockDeleteCredentialId = null+ })++ describe('UsagePrioritySection visibility', () => {+ it('should show when showPrioritySwitcher is true', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({ showPrioritySwitcher: true })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getByText(/usagePriority/)).toBeInTheDocument()+ })++ it('should hide when showPrioritySwitcher is false', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({ showPrioritySwitcher: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.queryByText(/usagePriority/)).not.toBeInTheDocument()+ })+ })++ describe('CreditsExhaustedAlert', () => {+ it('should show when credits exhausted and supports credits', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({ isCreditsExhausted: true, supportsCredits: true })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getAllByText(/creditsExhausted/).length).toBeGreaterThan(0)+ })++ it('should hide when credits not exhausted', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({ isCreditsExhausted: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.queryByText(/creditsExhausted/)).not.toBeInTheDocument()+ })++ it('should hide when credits exhausted but supportsCredits is false', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({ isCreditsExhausted: true, supportsCredits: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.queryByText(/creditsExhausted/)).not.toBeInTheDocument()+ })++ it('should show fallback message when api-fallback variant with exhausted credits', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({+ variant: 'api-fallback',+ isCreditsExhausted: true,+ supportsCredits: true,+ priority: 'credits',+ })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getAllByText(/creditsExhaustedFallback/).length).toBeGreaterThan(0)+ })++ it('should show non-fallback message when credits-exhausted variant', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({+ variant: 'credits-exhausted',+ isCreditsExhausted: true,+ supportsCredits: true,+ hasCredentials: false,+ priority: 'credits',+ })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getByText(/creditsExhaustedMessage/)).toBeInTheDocument()+ })+ })++ describe('CreditsFallbackAlert', () => {+ it('should show when priority is apiKey, supports credits, not exhausted, and variant is not api-active', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({+ variant: 'api-required-add',+ priority: 'apiKey',+ supportsCredits: true,+ isCreditsExhausted: false,+ hasCredentials: false,+ })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getByText(/noApiKeysFallback/)).toBeInTheDocument()+ })++ it('should show unavailable message when priority is apiKey with credentials but not api-active', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({+ variant: 'api-unavailable',+ priority: 'apiKey',+ supportsCredits: true,+ isCreditsExhausted: false,+ hasCredentials: true,+ })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getAllByText(/apiKeyUnavailableFallback/).length).toBeGreaterThan(0)+ })++ it('should NOT show when variant is api-active', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({+ variant: 'api-active',+ priority: 'apiKey',+ supportsCredits: true,+ isCreditsExhausted: false,+ })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.queryByText(/noApiKeysFallback/)).not.toBeInTheDocument()+ expect(screen.queryByText(/apiKeyUnavailableFallback/)).not.toBeInTheDocument()+ })++ it('should NOT show when priority is credits', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState({+ variant: 'credits-active',+ priority: 'credits',+ supportsCredits: true,+ isCreditsExhausted: false,+ })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.queryByText(/noApiKeysFallback/)).not.toBeInTheDocument()+ expect(screen.queryByText(/apiKeyUnavailableFallback/)).not.toBeInTheDocument()+ })+ })++ describe('API key section', () => {+ it('should render all credential items', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getByText('My Key')).toBeInTheDocument()+ expect(screen.getByText('Other Key')).toBeInTheDocument()+ })++ it('should show empty state when no credentials', () => {+ render(+ <DropdownContent+ provider={createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ })}+ state={createState({ hasCredentials: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getByText(/noApiKeysTitle/)).toBeInTheDocument()+ expect(screen.getByText(/noApiKeysDescription/)).toBeInTheDocument()+ })++ it('should call activate without closing on credential item click', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )++ fireEvent.click(screen.getByTestId('click-cred-2'))++ expect(mockActivate).toHaveBeenCalledWith(+ expect.objectContaining({ credential_id: 'cred-2' }),+ )+ expect(onClose).not.toHaveBeenCalled()+ })++ it('should call handleOpenModal and close on edit credential', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )++ fireEvent.click(screen.getByTestId('edit-cred-2'))++ expect(mockHandleOpenModal).toHaveBeenCalledWith(+ expect.objectContaining({ credential_id: 'cred-2' }),+ )+ expect(onClose).toHaveBeenCalled()+ })++ it('should call openConfirmDelete on delete credential', () => {+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )++ fireEvent.click(screen.getByTestId('delete-cred-2'))++ expect(mockOpenConfirmDelete).toHaveBeenCalledWith(+ expect.objectContaining({ credential_id: 'cred-2' }),+ )+ })+ })++ describe('Add API Key', () => {+ it('should call handleOpenModal with no args and close on add', () => {+ render(+ <DropdownContent+ provider={createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ })}+ state={createState({ hasCredentials: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /addApiKey/ }))++ expect(mockHandleOpenModal).toHaveBeenCalledWith()+ expect(onClose).toHaveBeenCalled()+ })+ })++ describe('AlertDialog for delete confirmation', () => {+ it('should show confirm dialog when deleteCredentialId is set', () => {+ mockDeleteCredentialId = 'cred-1'+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.getByText(/confirmDelete/)).toBeInTheDocument()+ })++ it('should not show confirm dialog when deleteCredentialId is null', () => {+ mockDeleteCredentialId = null+ render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(screen.queryByText(/confirmDelete/)).not.toBeInTheDocument()+ })+ })++ describe('Layout', () => {+ it('should have 320px width container', () => {+ const { container } = render(+ <DropdownContent+ provider={createProvider()}+ state={createState()}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ onClose={onClose}+ />,+ )+ expect(container.querySelector('.w-\\[320px\\]')).toBeTruthy()+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dropdown-content.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dropdown-content.tsxnew file mode 100644index 00000000000..526cdf1dc93--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/dropdown-content.tsx@@ -0,0 +1,131 @@+import type { Credential, ModelProvider, PreferredProviderTypeEnum } from '../../declarations'+import type { CredentialPanelState } from '../use-credential-panel-state'+import { memo, useCallback } from 'react'+import { useTranslation } from 'react-i18next'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@/app/components/base/ui/alert-dialog'+import { ConfigurationMethodEnum } from '../../declarations'+import { useAuth } from '../../model-auth/hooks'+import ApiKeySection from './api-key-section'+import CreditsExhaustedAlert from './credits-exhausted-alert'+import CreditsFallbackAlert from './credits-fallback-alert'+import UsagePrioritySection from './usage-priority-section'+import { useActivateCredential } from './use-activate-credential'++const EMPTY_CREDENTIALS: Credential[] = []++type DropdownContentProps = {+ provider: ModelProvider+ state: CredentialPanelState+ isChangingPriority: boolean+ onChangePriority: (key: PreferredProviderTypeEnum) => void+ onClose: () => void+}++function DropdownContent({+ provider,+ state,+ isChangingPriority,+ onChangePriority,+ onClose,+}: DropdownContentProps) {+ const { t } = useTranslation()+ const { available_credentials } = provider.custom_configuration++ const {+ openConfirmDelete,+ closeConfirmDelete,+ doingAction,+ handleConfirmDelete,+ deleteCredentialId,+ handleOpenModal,+ } = useAuth(provider, ConfigurationMethodEnum.predefinedModel)++ const { selectedCredentialId, isActivating, activate } = useActivateCredential(provider)++ const handleEdit = useCallback((credential?: Credential) => {+ handleOpenModal(credential)+ onClose()+ }, [handleOpenModal, onClose])++ const handleDelete = useCallback((credential?: Credential) => {+ if (credential)+ openConfirmDelete(credential)+ }, [openConfirmDelete])++ const handleAdd = useCallback(() => {+ handleOpenModal()+ onClose()+ }, [handleOpenModal, onClose])++ const showCreditsExhaustedAlert = state.isCreditsExhausted && state.supportsCredits+ const hasApiKeyFallback = state.variant === 'api-fallback'+ || (state.variant === 'api-active' && state.priority === 'apiKey')+ const showCreditsFallbackAlert = state.priority === 'apiKey'+ && state.supportsCredits+ && !state.isCreditsExhausted+ && state.variant !== 'api-active'++ return (+ <>+ <div className="w-[320px]">+ {state.showPrioritySwitcher && (+ <UsagePrioritySection+ value={state.priority}+ disabled={isChangingPriority}+ onSelect={onChangePriority}+ />+ )}+ {showCreditsFallbackAlert && (+ <CreditsFallbackAlert hasCredentials={state.hasCredentials} />+ )}+ {showCreditsExhaustedAlert && (+ <CreditsExhaustedAlert hasApiKeyFallback={hasApiKeyFallback} />+ )}+ <ApiKeySection+ provider={provider}+ credentials={available_credentials ?? EMPTY_CREDENTIALS}+ selectedCredentialId={selectedCredentialId}+ isActivating={isActivating}+ onItemClick={activate}+ onEdit={handleEdit}+ onDelete={handleDelete}+ onAdd={handleAdd}+ />+ </div>+ <AlertDialog+ open={!!deleteCredentialId}+ onOpenChange={(open) => {+ if (!open)+ closeConfirmDelete()+ }}+ >+ <AlertDialogContent>+ <div className="p-6 pb-0">+ <AlertDialogTitle className="text-text-primary system-xl-semibold">+ {t('modelProvider.confirmDelete', { ns: 'common' })}+ </AlertDialogTitle>+ <AlertDialogDescription className="mt-1 text-text-secondary system-sm-regular" />+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton disabled={doingAction}>+ {t('operation.cancel', { ns: 'common' })}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton disabled={doingAction} onClick={handleConfirmDelete}>+ {t('operation.delete', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>+ </>+ )+}++export default memo(DropdownContent)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.spec.tsxnew file mode 100644index 00000000000..e1bec972f04--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.spec.tsx@@ -0,0 +1,211 @@+import type { ModelProvider } from '../../declarations'+import type { CredentialPanelState } from '../use-credential-panel-state'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { CustomConfigurationStatusEnum, PreferredProviderTypeEnum } from '../../declarations'+import ModelAuthDropdown from './index'++vi.mock('../../model-auth/hooks', () => ({+ useAuth: () => ({+ openConfirmDelete: vi.fn(),+ closeConfirmDelete: vi.fn(),+ doingAction: false,+ handleConfirmDelete: vi.fn(),+ deleteCredentialId: null,+ handleOpenModal: vi.fn(),+ }),+}))++vi.mock('./use-activate-credential', () => ({+ useActivateCredential: () => ({+ selectedCredentialId: undefined,+ isActivating: false,+ activate: vi.fn(),+ }),+}))++vi.mock('../use-trial-credits', () => ({+ useTrialCredits: () => ({ credits: 0, totalCredits: 10_000, isExhausted: true, isLoading: false }),+}))++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ 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',+ supportsCredits: true,+ showPrioritySwitcher: false,+ hasCredentials: false,+ isCreditsExhausted: false,+ credentialName: undefined,+ credits: 100,+ ...overrides,+})++describe('ModelAuthDropdown', () => {+ const onChangePriority = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Button text', () => {+ it('should show "Add API Key" when no credentials for credits-active', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ hasCredentials: false, variant: 'credits-active' })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /addApiKey/ })).toBeInTheDocument()+ })++ it('should show "Configure" when has credentials for api-active', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ hasCredentials: true, variant: 'api-active' })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /config/i })).toBeInTheDocument()+ })++ it('should show "Add API Key" for api-required-add variant', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'api-required-add', hasCredentials: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /addApiKey/ })).toBeInTheDocument()+ })++ it('should show "Configure" for api-required-configure variant', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'api-required-configure', hasCredentials: true })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /config/i })).toBeInTheDocument()+ })++ it('should show "Configure" for credits-active when has credentials', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ hasCredentials: true, variant: 'credits-active' })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /config/i })).toBeInTheDocument()+ })++ it('should show "Add API Key" for credits-exhausted (no credentials)', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'credits-exhausted', hasCredentials: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /addApiKey/ })).toBeInTheDocument()+ })++ it('should show "Configure" for api-unavailable (has credentials)', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'api-unavailable', hasCredentials: true })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /config/i })).toBeInTheDocument()+ })++ it('should show "Configure" for api-fallback (has credentials)', () => {+ render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'api-fallback', hasCredentials: true })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ expect(screen.getByRole('button', { name: /config/i })).toBeInTheDocument()+ })+ })++ describe('Button variant styling', () => {+ it('should use primary for api-required-add', () => {+ const { container } = render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'api-required-add', hasCredentials: false })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ const button = container.querySelector('button')+ expect(button?.getAttribute('data-variant') ?? button?.className).toMatch(/primary/)+ })++ it('should use secondary-accent for api-required-configure', () => {+ const { container } = render(+ <ModelAuthDropdown+ provider={createProvider()}+ state={createState({ variant: 'api-required-configure', hasCredentials: true })}+ isChangingPriority={false}+ onChangePriority={onChangePriority}+ />,+ )+ const button = container.querySelector('button')+ expect(button?.getAttribute('data-variant') ?? button?.className).toMatch(/accent/)+ })+ })++ describe('Popover behavior', () => {+ it('should open popover on button click and show dropdown content', async () => {+ 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}+ />,+ )++ fireEvent.click(screen.getByRole('button', { name: /config/i }))++ await waitFor(() => {+ expect(screen.getByText('Key 1')).toBeInTheDocument()+ })+ })+ })+})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.tsxnew file mode 100644index 00000000000..da7394a407f--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/index.tsx@@ -0,0 +1,85 @@+import type { ModelProvider, PreferredProviderTypeEnum } from '../../declarations'+import type { CardVariant, CredentialPanelState } from '../use-credential-panel-state'+import { memo, useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Button from '@/app/components/base/button'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'+import DropdownContent from './dropdown-content'++type ModelAuthDropdownProps = {+ provider: ModelProvider+ state: CredentialPanelState+ isChangingPriority: boolean+ onChangePriority: (key: PreferredProviderTypeEnum) => void+}++function getButtonConfig(variant: CardVariant, hasCredentials: boolean, t: (key: string, opts?: Record<string, string>) => string) {+ if (variant === 'api-required-add') {+ return {+ text: t('modelProvider.auth.addApiKey', { ns: 'common' }),+ variant: 'primary' as const,+ }+ }++ if (variant === 'api-required-configure') {+ return {+ text: t('operation.config', { ns: 'common' }),+ variant: 'secondary-accent' as const,+ }+ }++ const text = hasCredentials+ ? t('operation.config', { ns: 'common' })+ : t('modelProvider.auth.addApiKey', { ns: 'common' })++ return { text, variant: 'secondary' as const }+}++function ModelAuthDropdown({+ provider,+ state,+ isChangingPriority,+ onChangePriority,+}: ModelAuthDropdownProps) {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)++ const handleClose = useCallback(() => setOpen(false), [])++ const buttonConfig = getButtonConfig(state.variant, state.hasCredentials, t)++ return (+ <Popover open={open} onOpenChange={setOpen}>+ <PopoverTrigger+ render={(+ <Button+ className="flex grow"+ size="small"+ variant={buttonConfig.variant}+ title={buttonConfig.text}+ >+ <span className="i-ri-equalizer-2-line mr-1 h-3.5 w-3.5 shrink-0" />+ <span className="w-0 grow truncate text-left">+ {buttonConfig.text}+ </span>+ </Button>+ )}+ />+ <PopoverContent placement="bottom-end">+ <DropdownContent+ provider={provider}+ state={state}+ isChangingPriority={isChangingPriority}+ onChangePriority={onChangePriority}+ onClose={handleClose}+ />+ </PopoverContent>+ </Popover>+ )+}++export default memo(ModelAuthDropdown)diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/usage-priority-section.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/usage-priority-section.spec.tsxnew file mode 100644index 00000000000..9b5c4689e9b--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/usage-priority-section.spec.tsx@@ -0,0 +1,66 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { PreferredProviderTypeEnum } from '../../declarations'+import UsagePrioritySection from './usage-priority-section'++describe('UsagePrioritySection', () => {+ const onSelect = vi.fn()++ beforeEach(() => {+ vi.clearAllMocks()+ })++ // Rendering+ describe('Rendering', () => {+ it('should render title and both option buttons', () => {+ render(<UsagePrioritySection value="credits" onSelect={onSelect} />)++ expect(screen.getByText(/usagePriority/)).toBeInTheDocument()+ expect(screen.getAllByRole('button')).toHaveLength(2)+ })+ })++ // Selection state+ describe('Selection state', () => {+ it('should highlight AI credits option when value is credits', () => {+ render(<UsagePrioritySection value="credits" onSelect={onSelect} />)++ const buttons = screen.getAllByRole('button')+ expect(buttons[0].className).toContain('border-components-option-card-option-selected-border')+ expect(buttons[1].className).not.toContain('border-components-option-card-option-selected-border')+ })++ it('should highlight API key option when value is apiKey', () => {+ render(<UsagePrioritySection value="apiKey" onSelect={onSelect} />)++ const buttons = screen.getAllByRole('button')+ expect(buttons[0].className).not.toContain('border-components-option-card-option-selected-border')+ expect(buttons[1].className).toContain('border-components-option-card-option-selected-border')+ })++ it('should highlight API key option when value is apiKeyOnly', () => {+ render(<UsagePrioritySection value="apiKeyOnly" onSelect={onSelect} />)++ const buttons = screen.getAllByRole('button')+ expect(buttons[1].className).toContain('border-components-option-card-option-selected-border')+ })+ })++ // User interactions+ describe('User interactions', () => {+ it('should call onSelect with system when clicking AI credits option', () => {+ render(<UsagePrioritySection value="apiKey" onSelect={onSelect} />)++ fireEvent.click(screen.getAllByRole('button')[0])++ expect(onSelect).toHaveBeenCalledWith(PreferredProviderTypeEnum.system)+ })++ it('should call onSelect with custom when clicking API key option', () => {+ render(<UsagePrioritySection value="credits" onSelect={onSelect} />)++ fireEvent.click(screen.getAllByRole('button')[1])++ expect(onSelect).toHaveBeenCalledWith(PreferredProviderTypeEnum.custom)+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/usage-priority-section.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/usage-priority-section.tsxnew file mode 100644index 00000000000..97b5e0aebb7--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/usage-priority-section.tsx@@ -0,0 +1,70 @@+import type { UsagePriority } from '../use-credential-panel-state'+import { useTranslation } from 'react-i18next'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'+import { cn } from '@/utils/classnames'+import { PreferredProviderTypeEnum } from '../../declarations'++type UsagePrioritySectionProps = {+ value: UsagePriority+ disabled?: boolean+ onSelect: (key: PreferredProviderTypeEnum) => void+}++const options = [+ { key: PreferredProviderTypeEnum.system, labelKey: 'modelProvider.card.aiCreditsOption' },+ { key: PreferredProviderTypeEnum.custom, labelKey: 'modelProvider.card.apiKeyOption' },+] as const++export default function UsagePrioritySection({ value, disabled, onSelect }: UsagePrioritySectionProps) {+ const { t } = useTranslation()+ const selectedKey = value === 'credits'+ ? PreferredProviderTypeEnum.system+ : PreferredProviderTypeEnum.custom++ return (+ <div className="p-1">+ <div className="flex items-center gap-1 rounded-lg p-1">+ <div className="shrink-0 px-0.5 py-1">+ <span className="i-ri-arrow-up-double-line block h-4 w-4 text-text-tertiary" />+ </div>+ <div className="flex min-w-0 flex-1 items-center gap-0.5 py-0.5">+ <span className="truncate text-text-secondary system-sm-medium">+ {t('modelProvider.card.usagePriority', { ns: 'common' })}+ </span>+ <Tooltip>+ <TooltipTrigger+ aria-label={t('modelProvider.card.usagePriorityTip', { ns: 'common' })}+ delay={0}+ render={(+ <span className="flex h-4 w-4 shrink-0 items-center justify-center">+ <span aria-hidden className="i-ri-question-line h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary" />+ </span>+ )}+ />+ <TooltipContent>+ {t('modelProvider.card.usagePriorityTip', { ns: 'common' })}+ </TooltipContent>+ </Tooltip>+ </div>+ <div className="flex shrink-0 items-center gap-1">+ {options.map(option => (+ <button+ key={option.key}+ type="button"+ className={cn(+ 'shrink-0 whitespace-nowrap rounded-md px-2 py-1 text-center transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-components-button-primary-border disabled:opacity-50',+ selectedKey === option.key+ ? 'border-[1.5px] border-components-option-card-option-selected-border bg-components-panel-bg text-text-primary shadow-xs system-xs-medium'+ : 'border border-components-option-card-option-border bg-components-option-card-option-bg text-text-secondary system-xs-regular hover:bg-components-option-card-option-bg-hover',+ )}+ disabled={disabled}+ onClick={() => onSelect(option.key)}+ >+ {t(option.labelKey, { ns: 'common' })}+ </button>+ ))}+ </div>+ </div>+ </div>+ )+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.spec.tsxnew file mode 100644index 00000000000..3a2e28720c3--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.spec.tsx@@ -0,0 +1,127 @@+import type { Credential, ModelProvider } from '../../declarations'+import { act, renderHook } from '@testing-library/react'+import Toast from '@/app/components/base/toast'+import { useActivateCredential } from './use-activate-credential'++const mockMutate = vi.fn()+const mockUpdateModelProviders = vi.fn()+const mockUpdateModelList = vi.fn()+let mockIsPending = false++vi.mock('@/service/use-models', () => ({+ useActiveProviderCredential: () => ({+ mutate: mockMutate,+ isPending: mockIsPending,+ }),+}))++vi.mock('../../hooks', () => ({+ useUpdateModelProviders: () => mockUpdateModelProviders,+ useUpdateModelList: () => mockUpdateModelList,+}))++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'langgenius/openai/openai',+ supported_model_types: ['llm', 'text-embedding'],+ custom_configuration: {+ current_credential_id: 'cred-1',+ available_credentials: [+ { credential_id: 'cred-1', credential_name: 'Primary' },+ { credential_id: 'cred-2', credential_name: 'Backup' },+ ],+ },+ ...overrides,+} as unknown as ModelProvider)++const createCredential = (overrides: Partial<Credential> = {}): Credential => ({+ credential_id: 'cred-2',+ credential_name: 'Backup',+ ...overrides,+} as Credential)++describe('useActivateCredential', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockIsPending = false+ vi.spyOn(Toast, 'notify').mockImplementation(() => ({ clear: vi.fn() }))+ })++ it('should expose the current credential id by default', () => {+ const { result } = renderHook(() => useActivateCredential(createProvider()))++ expect(result.current.selectedCredentialId).toBe('cred-1')+ expect(result.current.isActivating).toBe(false)+ })++ it('should expose the pending mutation state', () => {+ mockIsPending = true++ const { result } = renderHook(() => useActivateCredential(createProvider()))++ expect(result.current.isActivating).toBe(true)+ })++ it('should skip mutation when the selected credential is already active', () => {+ const { result } = renderHook(() => useActivateCredential(createProvider()))++ act(() => {+ result.current.activate(createCredential({ credential_id: 'cred-1' }))+ })++ expect(mockMutate).not.toHaveBeenCalled()+ expect(result.current.selectedCredentialId).toBe('cred-1')+ })++ it('should optimistically select the credential and refresh provider data on success', () => {+ const { result } = renderHook(() => useActivateCredential(createProvider()))++ act(() => {+ result.current.activate(createCredential())+ })++ expect(result.current.selectedCredentialId).toBe('cred-2')+ expect(mockMutate).toHaveBeenCalledWith(+ { credential_id: 'cred-2' },+ expect.objectContaining({+ onSuccess: expect.any(Function),+ onError: expect.any(Function),+ }),+ )++ const [, callbacks] = mockMutate.mock.calls[0]++ act(() => {+ callbacks.onSuccess()+ })++ expect(Toast.notify).toHaveBeenCalledWith({+ type: 'success',+ message: 'common.api.actionSuccess',+ })+ expect(mockUpdateModelProviders).toHaveBeenCalledTimes(1)+ expect(mockUpdateModelList).toHaveBeenNthCalledWith(1, 'llm')+ expect(mockUpdateModelList).toHaveBeenNthCalledWith(2, 'text-embedding')+ })++ it('should reset the optimistic selection and show an error toast when activation fails', () => {+ const { result } = renderHook(() => useActivateCredential(createProvider()))++ act(() => {+ result.current.activate(createCredential())+ })++ expect(result.current.selectedCredentialId).toBe('cred-2')++ const [, callbacks] = mockMutate.mock.calls[0]++ act(() => {+ callbacks.onError()+ })++ expect(result.current.selectedCredentialId).toBe('cred-1')+ expect(Toast.notify).toHaveBeenCalledWith({+ type: 'error',+ message: 'common.actionMsg.modifiedUnsuccessfully',+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.tsnew file mode 100644index 00000000000..f7f3f74779b--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts@@ -0,0 +1,52 @@+import type { Credential, ModelProvider } from '../../declarations'+import { useCallback, useRef, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Toast from '@/app/components/base/toast'+import { useActiveProviderCredential } from '@/service/use-models'+import {+ useUpdateModelList,+ useUpdateModelProviders,+} from '../../hooks'++export function useActivateCredential(provider: ModelProvider) {+ const { t } = useTranslation()+ const updateModelProviders = useUpdateModelProviders()+ const updateModelList = useUpdateModelList()+ const { mutate, isPending } = useActiveProviderCredential(provider.provider)+ const [optimisticId, setOptimisticId] = useState<string>()++ const currentId = provider.custom_configuration.current_credential_id+ const selectedCredentialId = optimisticId ?? currentId++ const selectedIdRef = useRef(selectedCredentialId)+ selectedIdRef.current = selectedCredentialId++ const supportedModelTypesRef = useRef(provider.supported_model_types)+ supportedModelTypesRef.current = provider.supported_model_types++ const activate = useCallback((credential: Credential) => {+ if (credential.credential_id === selectedIdRef.current)+ return+ setOptimisticId(credential.credential_id)+ mutate(+ { credential_id: credential.credential_id },+ {+ onSuccess: () => {+ Toast.notify({ type: 'success', message: t('api.actionSuccess', { ns: 'common' }) })+ updateModelProviders()+ supportedModelTypesRef.current.forEach(type => updateModelList(type))+ },+ onError: () => {+ setOptimisticId(undefined)+ Toast.notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ },+ },+ )+ }, [mutate, t, updateModelProviders, updateModelList])++ return {+ selectedCredentialId,+ isActivating: isPending,+ activate,+ }+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsxindex 908d2f0e6c6..595525d0142 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx@@ -1,4 +1,5 @@import type { ModelItem, ModelProvider } from '../declarations'+import { useQueryClient } from '@tanstack/react-query'import { useDebounceFn } from 'ahooks'import { memo, useCallback } from 'react'import { useTranslation } from 'react-i18next'@@ -9,6 +10,7 @@ import Tooltip from '@/app/components/base/tooltip'import { Plan } from '@/app/components/billing/type'import { useAppContext } from '@/context/app-context'import { useProviderContext, useProviderContextSelector } from '@/context/provider-context'+import { consoleQuery } from '@/service/client'import { disableModel, enableModel } from '@/service/common'import { cn } from '@/utils/classnames'import { ModelStatusEnum } from '../declarations'@@ -30,16 +32,30 @@ const ModelListItem = ({ model, provider, isConfigurable, onChange, onModifyLoadconst { plan } = useProviderContext()const modelLoadBalancingEnabled = useProviderContextSelector(state => state.modelLoadBalancingEnabled)const { isCurrentWorkspaceManager } = useAppContext()+ const queryClient = useQueryClient()const updateModelList = useUpdateModelList()+ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: provider.provider,+ },+ },+ })const toggleModelEnablingStatus = useCallback(async (enabled: boolean) => {if (enabled)await enableModel(`/workspaces/current/model-providers/${provider.provider}/models/enable`, { model: model.model, model_type: model.model_type })elseawait disableModel(`/workspaces/current/model-providers/${provider.provider}/models/disable`, { model: model.model, model_type: model.model_type })++ queryClient.invalidateQueries({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'none',+ })updateModelList(model.model_type)onChange?.(provider.provider)- }, [model.model, model.model_type, onChange, provider.provider, updateModelList])+ }, [model.model, model.model_type, modelProviderModelListQueryKey, onChange, provider.provider, queryClient, updateModelList])const { run: debouncedToggleModelEnablingStatus } = useDebounceFn(toggleModelEnablingStatus, { wait: 500 })@@ -58,7 +74,7 @@ const ModelListItem = ({ model, provider, isConfigurable, onChange, onModifyLoadmodelName={model.model}/><ModelName- className="system-md-regular grow text-text-secondary"+ className="grow text-text-secondary system-md-regular"modelItem={model}showModelTypeshowModediff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.spec.tsxnew file mode 100644index 00000000000..30c477f3ebc--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.spec.tsx@@ -0,0 +1,264 @@+import type { ReactNode } from 'react'+import type { PluginDetail } from '@/app/components/plugins/types'+import { fireEvent, render, screen } from '@testing-library/react'+import { PluginSource } from '@/app/components/plugins/types'+import ProviderCardActions from './provider-card-actions'++const mockHandleUpdate = vi.fn()+const mockHandleUpdatedFromMarketplace = vi.fn()+const mockHandleDelete = vi.fn()+const mockGetMarketplaceUrl = vi.fn()+const mockShowPluginInfo = vi.fn()+const mockShowDeleteConfirm = vi.fn()+const mockSetTargetVersion = vi.fn()+const mockSetVersionPickerOpen = vi.fn()++let mockHeaderState = {+ modalStates: {+ showPluginInfo: mockShowPluginInfo,+ showDeleteConfirm: mockShowDeleteConfirm,+ },+ versionPicker: {+ isShow: false,+ setIsShow: mockSetVersionPickerOpen,+ setTargetVersion: mockSetTargetVersion,+ targetVersion: undefined,+ isDowngrade: false,+ },+ hasNewVersion: true,+ isAutoUpgradeEnabled: false,+ isFromMarketplace: true,+ isFromGitHub: false,+}++vi.mock('@/app/components/plugins/plugin-detail-panel/detail-header/hooks', () => ({+ useDetailHeaderState: () => mockHeaderState,+ usePluginOperations: () => ({+ handleUpdate: mockHandleUpdate,+ handleUpdatedFromMarketplace: mockHandleUpdatedFromMarketplace,+ handleDelete: mockHandleDelete,+ }),+}))++vi.mock('@/app/components/plugins/plugin-detail-panel/detail-header/components', () => ({+ HeaderModals: ({ targetVersion, isDowngrade, isAutoUpgradeEnabled }: {+ targetVersion?: { version: string, unique_identifier: string }+ isDowngrade: boolean+ isAutoUpgradeEnabled: boolean+ }) => (+ <div+ data-testid="header-modals"+ data-target-version={targetVersion?.version ?? ''}+ data-is-downgrade={String(isDowngrade)}+ data-auto-upgrade={String(isAutoUpgradeEnabled)}+ />+ ),+}))++vi.mock('@/app/components/plugins/plugin-detail-panel/operation-dropdown', () => ({+ default: ({ detailUrl, onInfo, onCheckVersion, onRemove }: {+ detailUrl: string+ onInfo: () => void+ onCheckVersion: () => void+ onRemove: () => void+ }) => (+ <div data-testid="operation-dropdown" data-detail-url={detailUrl}>+ <button type="button" onClick={onInfo}>info</button>+ <button type="button" onClick={onCheckVersion}>check version</button>+ <button type="button" onClick={onRemove}>remove</button>+ </div>+ ),+}))++vi.mock('@/app/components/plugins/update-plugin/plugin-version-picker', () => ({+ default: ({ trigger, onSelect, disabled }: {+ trigger: ReactNode+ onSelect: (state: { version: string, unique_identifier: string, isDowngrade?: boolean }) => void+ disabled?: boolean+ }) => (+ <div data-testid="plugin-version-picker" data-disabled={String(Boolean(disabled))}>+ {trigger}+ <button+ type="button"+ onClick={() => onSelect({ version: '2.0.0', unique_identifier: '[email protected]', isDowngrade: true })}+ >+ select version+ </button>+ </div>+ ),+}))++vi.mock('@/context/i18n', () => ({+ useLocale: () => 'en-US',+}))++vi.mock('@/hooks/use-theme', () => ({+ default: () => ({ theme: 'light' }),+}))++vi.mock('@/utils/var', () => ({+ getMarketplaceUrl: (...args: unknown[]) => mockGetMarketplaceUrl(...args),+}))++const createDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({+ plugin_id: 'plugin-id',+ plugin_unique_identifier: '[email protected]',+ name: 'provider-plugin',+ source: PluginSource.marketplace,+ version: '1.0.0',+ latest_version: '2.0.0',+ latest_unique_identifier: '[email protected]',+ declaration: {+ author: 'langgenius',+ name: 'provider-plugin',+ },+ meta: undefined,+ ...overrides,+} as PluginDetail)++describe('ProviderCardActions', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockHeaderState = {+ modalStates: {+ showPluginInfo: mockShowPluginInfo,+ showDeleteConfirm: mockShowDeleteConfirm,+ },+ versionPicker: {+ isShow: false,+ setIsShow: mockSetVersionPickerOpen,+ setTargetVersion: mockSetTargetVersion,+ targetVersion: undefined,+ isDowngrade: false,+ },+ hasNewVersion: true,+ isAutoUpgradeEnabled: false,+ isFromMarketplace: true,+ isFromGitHub: false,+ }+ mockGetMarketplaceUrl.mockReturnValue('https://marketplace.example.com/plugins/langgenius/provider-plugin')+ })++ it('should render version controls for marketplace plugins and handle manual version selection', () => {+ render(<ProviderCardActions detail={createDetail()} />)++ expect(screen.getByText('1.0.0')).toBeInTheDocument()+ expect(screen.getByTestId('plugin-version-picker')).toHaveAttribute('data-disabled', 'false')++ fireEvent.click(screen.getByRole('button', { name: 'select version' }))++ expect(mockSetTargetVersion).toHaveBeenCalledWith({+ version: '2.0.0',+ unique_identifier: '[email protected]',+ isDowngrade: true,+ })+ expect(mockHandleUpdate).toHaveBeenCalledWith(true)+ })++ it('should trigger the latest marketplace update when clicking the update button', () => {+ render(<ProviderCardActions detail={createDetail()} />)++ fireEvent.click(screen.getByRole('button', { name: 'plugin.detailPanel.operation.update' }))++ expect(mockSetTargetVersion).toHaveBeenCalledWith({+ version: '2.0.0',+ unique_identifier: '[email protected]',+ })+ expect(mockHandleUpdate).toHaveBeenCalledWith()+ })++ it('should pass the marketplace detail url to the operation dropdown', () => {+ render(<ProviderCardActions detail={createDetail()} />)++ expect(mockGetMarketplaceUrl).toHaveBeenCalledWith('/plugins/langgenius/provider-plugin', {+ language: 'en-US',+ theme: 'light',+ })+ expect(screen.getByTestId('operation-dropdown')).toHaveAttribute(+ 'data-detail-url',+ 'https://marketplace.example.com/plugins/langgenius/provider-plugin',+ )+ })++ it('should relay operation dropdown actions', () => {+ render(<ProviderCardActions detail={createDetail()} />)++ fireEvent.click(screen.getByRole('button', { name: 'info' }))+ fireEvent.click(screen.getByRole('button', { name: 'check version' }))+ fireEvent.click(screen.getByRole('button', { name: 'remove' }))++ expect(mockShowPluginInfo).toHaveBeenCalledTimes(1)+ expect(mockHandleUpdate).toHaveBeenCalledTimes(1)+ expect(mockShowDeleteConfirm).toHaveBeenCalledTimes(1)+ })++ it('should use the GitHub repo url and skip marketplace version preselection for GitHub plugins', () => {+ mockHeaderState = {+ ...mockHeaderState,+ hasNewVersion: false,+ isFromMarketplace: false,+ isFromGitHub: true,+ }++ render(+ <ProviderCardActions detail={createDetail({+ source: PluginSource.github,+ meta: {+ repo: 'langgenius/provider-plugin',+ version: '1.0.0',+ package: 'provider-plugin.difypkg',+ },+ })}+ />,+ )++ expect(screen.getByTestId('plugin-version-picker')).toHaveAttribute('data-disabled', 'true')+ expect(screen.getByTestId('operation-dropdown')).toHaveAttribute(+ 'data-detail-url',+ 'https://github.com/langgenius/provider-plugin',+ )++ fireEvent.click(screen.getByRole('button', { name: 'plugin.detailPanel.operation.update' }))++ expect(mockSetTargetVersion).not.toHaveBeenCalled()+ expect(mockHandleUpdate).toHaveBeenCalledWith()+ })++ it('should fall back to the detail name when declaration metadata is missing', () => {+ render(+ <ProviderCardActions+ detail={createDetail({+ declaration: undefined,+ })}+ />,+ )++ expect(mockGetMarketplaceUrl).toHaveBeenCalledWith('/plugins//provider-plugin', {+ language: 'en-US',+ theme: 'light',+ })+ })++ it('should leave the detail url empty when a GitHub plugin has no repo or the source is unsupported', () => {+ const { rerender } = render(+ <ProviderCardActions+ detail={createDetail({+ source: PluginSource.github,+ meta: undefined,+ })}+ />,+ )++ expect(screen.getByTestId('operation-dropdown')).toHaveAttribute('data-detail-url', '')++ rerender(+ <ProviderCardActions+ detail={createDetail({+ source: PluginSource.local,+ })}+ />,+ )++ expect(screen.getByTestId('operation-dropdown')).toHaveAttribute('data-detail-url', '')+ })+})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.tsxnew file mode 100644index 00000000000..38cfb028356--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/provider-card-actions.tsx@@ -0,0 +1,149 @@+import type { FC } from 'react'+import type { PluginDetail } from '@/app/components/plugins/types'+import { useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import Badge from '@/app/components/base/badge'+import Button from '@/app/components/base/button'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'+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 { PluginSource } from '@/app/components/plugins/types'+import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'+import { useLocale } from '@/context/i18n'+import useTheme from '@/hooks/use-theme'+import { cn } from '@/utils/classnames'+import { getMarketplaceUrl } from '@/utils/var'++type Props = {+ detail: PluginDetail+ onUpdate?: () => void+}++const ProviderCardActions: FC<Props> = ({ detail, onUpdate }) => {+ const { t } = useTranslation()+ const { theme } = useTheme()+ const locale = useLocale()++ const { source, version, latest_version, latest_unique_identifier, meta } = detail+ const author = detail.declaration?.author ?? ''+ const name = detail.declaration?.name ?? detail.name++ const {+ modalStates,+ versionPicker,+ hasNewVersion,+ isAutoUpgradeEnabled,+ isFromMarketplace,+ isFromGitHub,+ } = useDetailHeaderState(detail)++ const {+ handleUpdate,+ handleUpdatedFromMarketplace,+ handleDelete,+ } = usePluginOperations({+ detail,+ modalStates,+ versionPicker,+ isFromMarketplace,+ onUpdate,+ })++ const handleVersionSelect = (state: { version: string, unique_identifier: string, isDowngrade?: boolean }) => {+ versionPicker.setTargetVersion(state)+ handleUpdate(state.isDowngrade)+ }++ const handleTriggerLatestUpdate = () => {+ if (isFromMarketplace) {+ versionPicker.setTargetVersion({+ version: latest_version,+ unique_identifier: latest_unique_identifier,+ })+ }+ handleUpdate()+ }++ 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}+ isShow={versionPicker.isShow}+ onShowChange={versionPicker.setIsShow}+ pluginID={detail.plugin_id}+ currentVersion={version}+ onSelect={handleVersionSelect}+ sideOffset={4}+ alignOffset={0}+ trigger={(+ <Badge+ className={cn(+ isFromMarketplace && 'cursor-pointer hover:bg-state-base-hover',+ )}+ uppercase={false}+ text={(+ <>+ <span>{version}</span>+ {isFromMarketplace && <span className="i-ri-arrow-left-right-line ml-1 h-3 w-3" />}+ </>+ )}+ hasRedCornerMark={hasNewVersion}+ />+ )}+ />+ )}++ {(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>+ )}++ <OperationDropdown+ source={source}+ onInfo={modalStates.showPluginInfo}+ onCheckVersion={() => handleUpdate()}+ onRemove={modalStates.showDeleteConfirm}+ detailUrl={detailUrl}+ placement="bottom-start"+ />++ <HeaderModals+ detail={detail}+ modalStates={modalStates}+ targetVersion={versionPicker.targetVersion}+ isDowngrade={versionPicker.isDowngrade}+ isAutoUpgradeEnabled={isAutoUpgradeEnabled}+ onUpdatedFromMarketplace={handleUpdatedFromMarketplace}+ onDelete={handleDelete}+ />+ </>+ )+}++export default ProviderCardActionsdiff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.module.css b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.module.cssnew file mode 100644index 00000000000..47d2c4cead2--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.module.css@@ -0,0 +1,8 @@+.gridBg {+ background-size: 4px 4px;+ background-image:+ linear-gradient(to right, var(--color-divider-subtle) 0.5px, transparent 0.5px),+ linear-gradient(to bottom, var(--color-divider-subtle) 0.5px, transparent 0.5px);+ -webkit-mask-image: radial-gradient(ellipse at center, rgba(0, 0, 0, 0.6), transparent 70%);+ mask-image: radial-gradient(ellipse at center, rgba(0, 0, 0, 0.6), transparent 70%);+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsxindex d44c201e0e7..2fa5243d889 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx@@ -1,63 +1,39 @@-import type { ComponentType, FC } from 'react'+import type { FC } from 'react'import type { ModelProvider } from '../declarations'import type { Plugin } from '@/app/components/plugins/types'+import type { ModelProviderQuotaGetPaid } from '@/types/model-provider'import { useBoolean } from 'ahooks'import * as React from 'react'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import { AnthropicShortLight, Deepseek, Gemini, Grok, OpenaiSmall, Tongyi } from '@/app/components/base/icons/src/public/llm'import Loading from '@/app/components/base/loading'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'-import { useAppContext } from '@/context/app-context'-import { useGlobalPublicStore } from '@/context/global-public-context'+import { useSystemFeaturesQuery } from '@/context/global-public-context'import useTimestamp from '@/hooks/use-timestamp'-import { ModelProviderQuotaGetPaid } from '@/types/model-provider'import { cn } from '@/utils/classnames'import { formatNumber } from '@/utils/format'import { PreferredProviderTypeEnum } from '../declarations'import { useMarketplaceAllPlugins } from '../hooks'-import { MODEL_PROVIDER_QUOTA_GET_PAID, modelNameMap } from '../utils'+import { MODEL_PROVIDER_QUOTA_GET_PAID, modelNameMap, providerIconMap, providerKeyToPluginId } from '../utils'+import styles from './quota-panel.module.css'+import { useTrialCredits } from './use-trial-credits'-// Icon map for each provider - single source of truth for provider icons-const providerIconMap: Record<ModelProviderQuotaGetPaid, ComponentType<{ className?: string }>> = {- [ModelProviderQuotaGetPaid.OPENAI]: OpenaiSmall,- [ModelProviderQuotaGetPaid.ANTHROPIC]: AnthropicShortLight,- [ModelProviderQuotaGetPaid.GEMINI]: Gemini,- [ModelProviderQuotaGetPaid.X]: Grok,- [ModelProviderQuotaGetPaid.DEEPSEEK]: Deepseek,- [ModelProviderQuotaGetPaid.TONGYI]: Tongyi,-}--// Derive allProviders from the shared constantconst allProviders = MODEL_PROVIDER_QUOTA_GET_PAID.map(key => ({key,Icon: providerIconMap[key],}))-// Map provider key to plugin ID-// provider key format: langgenius/provider/model, plugin ID format: langgenius/provider-const providerKeyToPluginId: Record<ModelProviderQuotaGetPaid, string> = {- [ModelProviderQuotaGetPaid.OPENAI]: 'langgenius/openai',- [ModelProviderQuotaGetPaid.ANTHROPIC]: 'langgenius/anthropic',- [ModelProviderQuotaGetPaid.GEMINI]: 'langgenius/gemini',- [ModelProviderQuotaGetPaid.X]: 'langgenius/x',- [ModelProviderQuotaGetPaid.DEEPSEEK]: 'langgenius/deepseek',- [ModelProviderQuotaGetPaid.TONGYI]: 'langgenius/tongyi',-}-type QuotaPanelProps = {providers: ModelProvider[]- isLoading?: boolean}const QuotaPanel: FC<QuotaPanelProps> = ({providers,- isLoading = false,}) => {const { t } = useTranslation()- const { currentWorkspace } = useAppContext()- const { trial_models } = useGlobalPublicStore(s => s.systemFeatures)- const credits = Math.max((currentWorkspace.trial_credits - currentWorkspace.trial_credits_used) || 0, 0)+ const { credits, isExhausted, isLoading, nextCreditResetDate } = useTrialCredits()+ const { data: systemFeatures } = useSystemFeaturesQuery()+ const trialModels = systemFeatures?.trial_models ?? []const providerMap = useMemo(() => new Map(providers.map(p => [p.provider, p.preferred_provider_type]),), [providers])@@ -98,6 +74,11 @@ const QuotaPanel: FC<QuotaPanelProps> = ({}}, [providers, isShowInstallModal, hideInstallFromMarketplace])+ const tipText = t('modelProvider.card.tip', {+ ns: 'common',+ modelNames: trialModels.map(key => modelNameMap[key as keyof typeof modelNameMap]).filter(Boolean).join(', '),+ })+if (isLoading) {return (<div className="my-2 flex min-h-[72px] items-center justify-center rounded-xl border-[0.5px] border-components-panel-border bg-third-party-model-bg-default shadow-xs">@@ -107,59 +88,88 @@ const QuotaPanel: FC<QuotaPanelProps> = ({}return (- <div className={cn('my-2 min-w-[72px] shrink-0 rounded-xl border-[0.5px] pb-2.5 pl-4 pr-2.5 pt-3 shadow-xs', credits <= 0 ? 'border-state-destructive-border hover:bg-state-destructive-hover' : 'border-components-panel-border bg-third-party-model-bg-default')}>- <div className="system-xs-medium-uppercase mb-2 flex h-4 items-center text-text-tertiary">- {t('modelProvider.quota', { ns: 'common' })}- <Tooltip popupContent={t('modelProvider.card.tip', { ns: 'common', modelNames: trial_models.map(key => modelNameMap[key as keyof typeof modelNameMap]).filter(Boolean).join(', ') })} />- </div>- <div className="flex items-center justify-between">- <div className="flex items-center gap-1 text-xs text-text-tertiary">- <span className="system-md-semibold-uppercase mr-0.5 text-text-secondary">{formatNumber(credits)}</span>- <span>{t('modelProvider.credits', { ns: 'common' })}</span>- {currentWorkspace.next_credit_reset_date- ? (- <>- <span>·</span>- <span>- {t('modelProvider.resetDate', {- ns: 'common',- date: formatTime(currentWorkspace.next_credit_reset_date, t('dateFormat', { ns: 'appLog' })),- interpolation: { escapeValue: false },- })}- </span>- </>- )- : null}+ <div className={cn(+ 'relative my-2 min-w-[72px] shrink-0 overflow-hidden rounded-xl border-[0.5px] pb-2.5 pl-4 pr-2.5 pt-3 shadow-xs',+ isExhausted+ ? 'border-state-destructive-border hover:bg-state-destructive-hover'+ : 'border-components-panel-border bg-third-party-model-bg-default',+ )}+ >+ <div className={cn('pointer-events-none absolute inset-0', styles.gridBg)} />+ <div className="relative">+ <div className="mb-2 flex h-4 items-center text-text-tertiary system-xs-medium-uppercase">+ {t('modelProvider.quota', { ns: 'common' })}+ <Tooltip>+ <TooltipTrigger+ aria-label={tipText}+ delay={0}+ render={(+ <span className="ml-0.5 flex h-4 w-4 shrink-0 items-center justify-center">+ <span aria-hidden className="i-ri-question-line h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary" />+ </span>+ )}+ />+ <TooltipContent>+ {tipText}+ </TooltipContent>+ </Tooltip></div>- <div className="flex items-center gap-1">- {allProviders.filter(({ key }) => trial_models.includes(key)).map(({ key, Icon }) => {- const providerType = providerMap.get(key)- const isConfigured = (installedProvidersMap.get(key)?.length ?? 0) > 0 // means the provider is configured API key- const getTooltipKey = () => {- // if provider type is not set, it means the provider is not installed- if (!providerType)- return 'modelProvider.card.modelNotSupported'- if (isConfigured && providerType === PreferredProviderTypeEnum.custom)- return 'modelProvider.card.modelAPI'- return 'modelProvider.card.modelSupported'- }- return (- <Tooltip- key={key}- popupContent={t(getTooltipKey(), { modelName: modelNameMap[key], ns: 'common' })}- >- <div- className={cn('relative h-6 w-6', !providerType && 'cursor-pointer hover:opacity-80')}- onClick={() => handleIconClick(key)}- >- <Icon className="h-6 w-6 rounded-lg" />- {!providerType && (- <div className="absolute inset-0 rounded-lg border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge opacity-30" />- )}- </div>- </Tooltip>- )- })}+ <div className="flex items-center justify-between">+ <div className="flex items-center gap-1 text-xs text-text-tertiary">+ {credits > 0+ ? <span className="mr-0.5 text-text-secondary system-xl-semibold">{formatNumber(credits)}</span>+ : <span className="mr-0.5 text-text-destructive system-xl-semibold">{t('modelProvider.card.quotaExhausted', { ns: 'common' })}</span>}+ {nextCreditResetDate+ ? (+ <>+ <span>·</span>+ <span>+ {t('modelProvider.resetDate', {+ ns: 'common',+ date: formatTime(nextCreditResetDate, t('dateFormat', { ns: 'appLog' })),+ interpolation: { escapeValue: false },+ })}+ </span>+ </>+ )+ : null}+ </div>+ <div className="flex items-center gap-1">+ {allProviders.filter(({ key }) => trialModels.includes(key)).map(({ key, Icon }) => {+ const providerType = providerMap.get(key)+ const isConfigured = (installedProvidersMap.get(key)?.length ?? 0) > 0+ const getTooltipKey = () => {+ if (!providerType)+ return 'modelProvider.card.modelNotSupported'+ if (isConfigured && providerType === PreferredProviderTypeEnum.custom)+ return 'modelProvider.card.modelAPI'+ return 'modelProvider.card.modelSupported'+ }+ const tooltipText = t(getTooltipKey(), { modelName: modelNameMap[key], ns: 'common' })+ return (+ <Tooltip key={key}>+ <TooltipTrigger+ aria-label={tooltipText}+ delay={0}+ render={(+ <div+ className={cn('relative h-6 w-6', !providerType && 'cursor-pointer hover:opacity-80')}+ onClick={() => handleIconClick(key)}+ >+ <Icon className="h-6 w-6 rounded-lg" />+ {!providerType && (+ <div className="absolute inset-0 rounded-lg border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge opacity-30" />+ )}+ </div>+ )}+ />+ <TooltipContent>+ {tooltipText}+ </TooltipContent>+ </Tooltip>+ )+ })}+ </div></div></div>{isShowInstallModal && selectedPlugin && (diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/system-quota-card.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/system-quota-card.spec.tsxnew file mode 100644index 00000000000..9f0b963a7a4--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/system-quota-card.spec.tsx@@ -0,0 +1,89 @@+import { render, screen } from '@testing-library/react'+import SystemQuotaCard from './system-quota-card'++describe('SystemQuotaCard', () => {+ // Renders container with children+ describe('Rendering', () => {+ it('should render children', () => {+ render(+ <SystemQuotaCard>+ <span>content</span>+ </SystemQuotaCard>,+ )++ expect(screen.getByText('content')).toBeInTheDocument()+ })++ it('should apply default variant styles', () => {+ const { container } = render(+ <SystemQuotaCard>+ <span>test</span>+ </SystemQuotaCard>,+ )++ const card = container.firstElementChild!+ expect(card.className).toContain('bg-white')+ })++ it('should apply destructive variant styles', () => {+ const { container } = render(+ <SystemQuotaCard variant="destructive">+ <span>test</span>+ </SystemQuotaCard>,+ )++ const card = container.firstElementChild!+ expect(card.className).toContain('border-state-destructive-border')+ })+ })++ // Label sub-component+ describe('Label', () => {+ it('should apply default variant text color when no className provided', () => {+ render(+ <SystemQuotaCard>+ <SystemQuotaCard.Label>Default label</SystemQuotaCard.Label>+ </SystemQuotaCard>,+ )++ expect(screen.getByText('Default label').className).toContain('text-text-secondary')+ })++ it('should apply destructive variant text color when no className provided', () => {+ render(+ <SystemQuotaCard variant="destructive">+ <SystemQuotaCard.Label>Error label</SystemQuotaCard.Label>+ </SystemQuotaCard>,+ )++ expect(screen.getByText('Error label').className).toContain('text-text-destructive')+ })++ it('should override variant color with custom className', () => {+ render(+ <SystemQuotaCard variant="destructive">+ <SystemQuotaCard.Label className="gap-1">Custom label</SystemQuotaCard.Label>+ </SystemQuotaCard>,+ )++ const label = screen.getByText('Custom label')+ expect(label.className).toContain('gap-1')+ expect(label.className).not.toContain('text-text-destructive')+ })+ })++ // Actions sub-component+ describe('Actions', () => {+ it('should render action children', () => {+ render(+ <SystemQuotaCard>+ <SystemQuotaCard.Actions>+ <button>Click me</button>+ </SystemQuotaCard.Actions>+ </SystemQuotaCard>,+ )++ expect(screen.getByRole('button', { name: /click me/i })).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/system-quota-card.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/system-quota-card.tsxnew file mode 100644index 00000000000..9a11f38116f--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/system-quota-card.tsx@@ -0,0 +1,67 @@+import type { ReactNode } from 'react'+import { createContext, useContext } from 'react'+import { cn } from '@/utils/classnames'+import styles from './quota-panel.module.css'++type Variant = 'default' | 'destructive'++const VariantContext = createContext<Variant>('default')++const containerVariants: Record<Variant, string> = {+ default: 'border-components-panel-border bg-white/[0.18]',+ destructive: 'border-state-destructive-border bg-state-destructive-hover',+}++const labelVariants: Record<Variant, string> = {+ default: 'text-text-secondary',+ destructive: 'text-text-destructive',+}++type SystemQuotaCardProps = {+ variant?: Variant+ children: ReactNode+}++const SystemQuotaCard = ({+ variant = 'default',+ children,+}: SystemQuotaCardProps) => {+ return (+ <VariantContext.Provider value={variant}>+ <div className={cn(+ 'relative isolate ml-1 flex w-[128px] shrink-0 flex-col justify-between rounded-lg border-[0.5px] p-1 shadow-xs',+ containerVariants[variant],+ )}+ >+ <div className={cn('pointer-events-none absolute inset-0 rounded-[7px]', styles.gridBg)} />+ {children}+ </div>+ </VariantContext.Provider>+ )+}++const Label = ({ children, className }: { children: ReactNode, className?: string }) => {+ const variant = useContext(VariantContext)+ return (+ <div className={cn(+ 'relative z-[1] flex items-center gap-1 truncate px-1.5 pt-1 system-xs-medium',+ className ?? labelVariants[variant],+ )}+ >+ {children}+ </div>+ )+}++const Actions = ({ children }: { children: ReactNode }) => {+ return (+ <div className="relative z-[1] flex items-center gap-0.5">+ {children}+ </div>+ )+}++SystemQuotaCard.Label = Label+SystemQuotaCard.Actions = Actions++export default SystemQuotaCarddiff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.spec.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.spec.tsnew file mode 100644index 00000000000..45fb6e18033--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.spec.ts@@ -0,0 +1,208 @@+import type { ReactNode } from 'react'+import type { ModelProvider } from '../declarations'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'+import { act, renderHook, waitFor } from '@testing-library/react'+import * as React from 'react'+import { ConfigurationMethodEnum, ModelTypeEnum, PreferredProviderTypeEnum } from '../declarations'+import { useChangeProviderPriority } from './use-change-provider-priority'++const mockUpdateModelList = vi.fn()+const mockUpdateModelProviders = vi.fn()+const mockNotify = vi.fn()+const mockQueryKey = vi.fn(({ input }: { input: { params: { provider: string } } }) => ['model-providers', 'models', input.params.provider])+const mockChangePreferredProviderType = vi.fn()+const mockMutationOptions = vi.fn((options: Record<string, unknown>) => ({+ mutationFn: (variables: unknown) => mockChangePreferredProviderType(variables),+ ...options,+}))++vi.mock('@/app/components/base/toast', () => ({+ default: {+ notify: (...args: unknown[]) => mockNotify(...args),+ },+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ modelProviders: {+ models: {+ queryKey: (options: { input: { params: { provider: string } } }) => mockQueryKey(options),+ },+ changePreferredProviderType: {+ mutationOptions: (options: Record<string, unknown>) => mockMutationOptions(options),+ },+ },+ },+}))++vi.mock('../hooks', () => ({+ useUpdateModelList: () => mockUpdateModelList,+ useUpdateModelProviders: () => mockUpdateModelProviders,+}))++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'langgenius/openai/openai',+ configurate_methods: [+ ConfigurationMethodEnum.customizableModel,+ ConfigurationMethodEnum.predefinedModel,+ ],+ supported_model_types: [ModelTypeEnum.textGeneration, ModelTypeEnum.textEmbedding],+ label: { en_US: 'OpenAI' },+ icon_small: { en_US: 'https://example.com/icon.png' },+ provider_credential_schema: { credential_form_schemas: [] },+ model_credential_schema: {+ model: {+ label: { en_US: 'Model' },+ placeholder: { en_US: 'Select model' },+ },+ credential_form_schemas: [],+ },+ ...overrides,+} as ModelProvider)++const createTestQueryClient = () => new QueryClient({+ defaultOptions: {+ queries: { retry: false, gcTime: 0 },+ mutations: { retry: false },+ },+})++const createWrapper = (queryClient: QueryClient) => {+ return ({ children }: { children: ReactNode }) => (+ React.createElement(QueryClientProvider, { client: queryClient }, children)+ )+}++describe('useChangeProviderPriority', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockChangePreferredProviderType.mockResolvedValue(undefined)+ })++ describe('when changing provider priority', () => {+ it('should submit the selected preferred provider type for the current provider', async () => {+ const queryClient = createTestQueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined)+ const provider = createProvider()+ const { result } = renderHook(() => useChangeProviderPriority(provider), {+ wrapper: createWrapper(queryClient),+ })++ act(() => {+ result.current.handleChangePriority(PreferredProviderTypeEnum.custom)+ })++ await waitFor(() => {+ expect(mockChangePreferredProviderType).toHaveBeenCalledWith({+ params: { provider: 'langgenius/openai/openai' },+ body: { preferred_provider_type: PreferredProviderTypeEnum.custom },+ })+ })++ expect(mockQueryKey).toHaveBeenCalledWith({+ input: {+ params: {+ provider: 'langgenius/openai/openai',+ },+ },+ })+ expect(mockMutationOptions).toHaveBeenCalled()+ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: ['model-providers', 'models', 'langgenius/openai/openai'],+ exact: true,+ refetchType: 'none',+ })+ expect(mockUpdateModelProviders).toHaveBeenCalledTimes(1)+ expect(mockUpdateModelList).toHaveBeenCalledTimes(2)+ expect(mockUpdateModelList).toHaveBeenNthCalledWith(1, ModelTypeEnum.textGeneration)+ expect(mockUpdateModelList).toHaveBeenNthCalledWith(2, ModelTypeEnum.textEmbedding)+ expect(mockNotify).toHaveBeenCalledWith({+ type: 'success',+ message: 'common.actionMsg.modifiedSuccessfully',+ })+ expect(result.current.isChangingPriority).toBe(false)+ })++ it('should tolerate an undefined provider and still submit a request without refreshing model lists', async () => {+ const queryClient = createTestQueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined)+ const { result } = renderHook(() => useChangeProviderPriority(undefined), {+ wrapper: createWrapper(queryClient),+ })++ act(() => {+ result.current.handleChangePriority(PreferredProviderTypeEnum.system)+ })++ await waitFor(() => {+ expect(mockChangePreferredProviderType).toHaveBeenCalledWith({+ params: { provider: '' },+ body: { preferred_provider_type: PreferredProviderTypeEnum.system },+ })+ })++ expect(invalidateQueries).toHaveBeenCalledWith({+ queryKey: ['model-providers', 'models', ''],+ exact: true,+ refetchType: 'none',+ })+ expect(mockUpdateModelProviders).toHaveBeenCalledTimes(1)+ expect(mockUpdateModelList).not.toHaveBeenCalled()+ })+ })++ describe('when the mutation is not successful immediately', () => {+ it('should show an error toast when the mutation fails', async () => {+ const queryClient = createTestQueryClient()+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue(undefined)+ mockChangePreferredProviderType.mockRejectedValueOnce(new Error('network error'))+ const { result } = renderHook(() => useChangeProviderPriority(createProvider()), {+ wrapper: createWrapper(queryClient),+ })++ act(() => {+ result.current.handleChangePriority(PreferredProviderTypeEnum.custom)+ })++ await waitFor(() => {+ expect(mockNotify).toHaveBeenCalledWith({+ type: 'error',+ message: 'common.actionMsg.modifiedUnsuccessfully',+ })+ })++ expect(invalidateQueries).not.toHaveBeenCalled()+ expect(mockUpdateModelProviders).not.toHaveBeenCalled()+ expect(mockUpdateModelList).not.toHaveBeenCalled()+ expect(result.current.isChangingPriority).toBe(false)+ })++ it('should expose the pending mutation state while the request is in flight', async () => {+ let resolveMutation: (() => void) | undefined+ mockChangePreferredProviderType.mockImplementationOnce(() => new Promise<void>((resolve) => {+ resolveMutation = resolve+ }))++ const queryClient = createTestQueryClient()+ const { result } = renderHook(() => useChangeProviderPriority(createProvider()), {+ wrapper: createWrapper(queryClient),+ })++ act(() => {+ result.current.handleChangePriority(PreferredProviderTypeEnum.custom)+ })++ await waitFor(() => {+ expect(result.current.isChangingPriority).toBe(true)+ })++ await act(async () => {+ resolveMutation?.()+ })++ await waitFor(() => {+ expect(result.current.isChangingPriority).toBe(false)+ })+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.tsnew file mode 100644index 00000000000..9762f47d74e--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts@@ -0,0 +1,53 @@+import type { ModelProvider, PreferredProviderTypeEnum } from '../declarations'+import { useMutation, useQueryClient } from '@tanstack/react-query'+import { useTranslation } from 'react-i18next'+import Toast from '@/app/components/base/toast'+import { consoleQuery } from '@/service/client'+import { ConfigurationMethodEnum } from '../declarations'+import { useUpdateModelList, useUpdateModelProviders } from '../hooks'++export function useChangeProviderPriority(provider: ModelProvider | undefined) {+ const { t } = useTranslation()+ const queryClient = useQueryClient()+ const updateModelList = useUpdateModelList()+ const updateModelProviders = useUpdateModelProviders()+ const providerName = provider?.provider ?? ''++ const modelProviderModelListQueryKey = consoleQuery.modelProviders.models.queryKey({+ input: {+ params: {+ provider: providerName,+ },+ },+ })++ const { mutate: changePriority, isPending: isChangingPriority } = useMutation(+ consoleQuery.modelProviders.changePreferredProviderType.mutationOptions({+ onSuccess: () => {+ Toast.notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })+ queryClient.invalidateQueries({+ queryKey: modelProviderModelListQueryKey,+ exact: true,+ refetchType: 'none',+ })+ updateModelProviders()+ provider?.configurate_methods.forEach((method) => {+ if (method === ConfigurationMethodEnum.predefinedModel)+ provider?.supported_model_types.forEach(modelType => updateModelList(modelType))+ })+ },+ onError: () => {+ Toast.notify({ type: 'error', message: t('actionMsg.modifiedUnsuccessfully', { ns: 'common' }) })+ },+ }),+ )++ const handleChangePriority = (key: PreferredProviderTypeEnum) => {+ changePriority({+ params: { provider: providerName },+ body: { preferred_provider_type: key },+ })+ }++ return { isChangingPriority, handleChangePriority }+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.spec.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.spec.tsnew file mode 100644index 00000000000..361501b15d1--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.spec.ts@@ -0,0 +1,295 @@+import type { ModelProvider } from '../declarations'+import { renderHook } from '@testing-library/react'+import {+ ConfigurationMethodEnum,+ CurrentSystemQuotaTypeEnum,+ CustomConfigurationStatusEnum,+ PreferredProviderTypeEnum,+} from '../declarations'+import { isDestructiveVariant, useCredentialPanelState } from './use-credential-panel-state'++const mockTrialCredits = { credits: 100, totalCredits: 10_000, isExhausted: false, isLoading: false, nextCreditResetDate: undefined }+const mockTrialModels = ['langgenius/openai/openai', 'langgenius/anthropic/anthropic']++vi.mock('./use-trial-credits', () => ({+ useTrialCredits: () => mockTrialCredits,+}))++vi.mock('@/context/global-public-context', () => ({+ useSystemFeaturesQuery: () => ({ data: { trial_models: mockTrialModels } }),+}))++vi.mock('@/config', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/config')>()+ return { ...actual, IS_CLOUD_EDITION: true }+})++const createProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'langgenius/openai/openai',+ provider_credential_schema: { credential_form_schemas: [] },+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: 'cred-1',+ current_credential_name: 'My Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'My Key' }],+ },+ system_configuration: { enabled: true, current_quota_type: 'trial', quota_configurations: [] },+ preferred_provider_type: PreferredProviderTypeEnum.system,+ configurate_methods: [ConfigurationMethodEnum.predefinedModel],+ supported_model_types: ['llm'],+ ...overrides,+} as unknown as ModelProvider)++describe('useCredentialPanelState', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ Object.assign(mockTrialCredits, { credits: 100, totalCredits: 10_000, isExhausted: false, isLoading: false })+ })++ // Credits priority variants+ describe('Credits priority variants', () => {+ it('should return credits-active when credits available', () => {+ const { result } = renderHook(() => useCredentialPanelState(createProvider()))++ expect(result.current.variant).toBe('credits-active')+ expect(result.current.priority).toBe('credits')+ expect(result.current.supportsCredits).toBe(true)+ })++ it('should return api-fallback when credits exhausted but API key authorized', () => {+ mockTrialCredits.isExhausted = true+ mockTrialCredits.credits = 0++ const { result } = renderHook(() => useCredentialPanelState(createProvider()))++ expect(result.current.variant).toBe('api-fallback')+ })++ it('should return no-usage when credits exhausted and API key unauthorized', () => {+ mockTrialCredits.isExhausted = true+ const provider = createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'My Key' }],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('no-usage')+ })++ it('should return credits-exhausted when credits exhausted and no credentials', () => {+ mockTrialCredits.isExhausted = true+ const provider = createProvider({+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('credits-exhausted')+ })+ })++ // API key priority variants+ describe('API key priority variants', () => {+ it('should return api-active when API key authorized', () => {+ const provider = createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('api-active')+ expect(result.current.priority).toBe('apiKey')+ })++ it('should return credits-fallback when API key unauthorized and credits available', () => {+ const provider = createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'My Key' }],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('credits-fallback')+ })++ it('should return credits-fallback when no credentials and credits available', () => {+ const provider = createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('credits-fallback')+ })++ it('should return no-usage when no credentials and credits exhausted', () => {+ mockTrialCredits.isExhausted = true+ mockTrialCredits.credits = 0+ const provider = createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.noConfigure,+ available_credentials: [],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('no-usage')+ })++ it('should return api-unavailable when credential with name unauthorized and credits exhausted', () => {+ mockTrialCredits.isExhausted = true+ mockTrialCredits.credits = 0+ const provider = createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: undefined,+ current_credential_name: 'Bad Key',+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Bad Key' }],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('api-unavailable')+ })++ it('should return api-required-configure when credentials exist but the current credential is incomplete', () => {+ mockTrialCredits.isExhausted = true+ mockTrialCredits.credits = 0+ const provider = createProvider({+ preferred_provider_type: PreferredProviderTypeEnum.custom,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ current_credential_id: 'cred-1',+ current_credential_name: undefined,+ available_credentials: [{ credential_id: 'cred-1', credential_name: 'Bad Key' }],+ },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.variant).toBe('api-required-configure')+ })+ })++ // apiKeyOnly priority+ describe('apiKeyOnly priority (non-cloud / system disabled / not in trial_models)', () => {+ it('should return apiKeyOnly when system config disabled', () => {+ const provider = createProvider({+ system_configuration: { enabled: false, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.priority).toBe('apiKeyOnly')+ expect(result.current.supportsCredits).toBe(false)+ })++ it('should return apiKeyOnly when provider not in trial_models even if system enabled', () => {+ const provider = createProvider({+ provider: 'langgenius/minimax/minimax',+ system_configuration: { enabled: true, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },+ preferred_provider_type: PreferredProviderTypeEnum.system,+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.priority).toBe('apiKeyOnly')+ expect(result.current.supportsCredits).toBe(false)+ expect(result.current.showPrioritySwitcher).toBe(false)+ })+ })++ // Undefined provider+ describe('Undefined provider', () => {+ it('should return safe defaults when provider is undefined', () => {+ const { result } = renderHook(() => useCredentialPanelState(undefined))++ expect(result.current.priority).toBe('apiKeyOnly')+ expect(result.current.supportsCredits).toBe(false)+ expect(result.current.hasCredentials).toBe(false)+ expect(result.current.credentialName).toBeUndefined()+ })+ })++ // Derived metadata+ describe('Derived metadata', () => {+ it('should show priority switcher when credits supported and custom config active', () => {+ const provider = createProvider()++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.showPrioritySwitcher).toBe(true)+ })++ it('should hide priority switcher when system config disabled', () => {+ const provider = createProvider({+ system_configuration: { enabled: false, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.showPrioritySwitcher).toBe(false)+ })++ it('should hide priority switcher when provider not in trial_models', () => {+ const provider = createProvider({+ provider: 'langgenius/zhipuai/zhipuai',+ system_configuration: { enabled: true, current_quota_type: CurrentSystemQuotaTypeEnum.trial, quota_configurations: [] },+ })++ const { result } = renderHook(() => useCredentialPanelState(provider))++ expect(result.current.showPrioritySwitcher).toBe(false)+ })++ it('should expose credential name from provider', () => {+ const { result } = renderHook(() => useCredentialPanelState(createProvider()))++ expect(result.current.credentialName).toBe('My Key')+ })++ it('should expose credits amount', () => {+ mockTrialCredits.credits = 500++ const { result } = renderHook(() => useCredentialPanelState(createProvider()))++ expect(result.current.credits).toBe(500)+ })+ })+})++describe('isDestructiveVariant', () => {+ it.each([+ ['credits-exhausted', true],+ ['no-usage', true],+ ['api-unavailable', true],+ ['credits-active', false],+ ['api-fallback', false],+ ['api-active', false],+ ['api-required-add', false],+ ['api-required-configure', false],+ ] as const)('should return %s for variant %s', (variant, expected) => {+ expect(isDestructiveVariant(variant)).toBe(expected)+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.tsnew file mode 100644index 00000000000..c9ca9d105fa--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state.ts@@ -0,0 +1,109 @@+import type { ModelProvider } from '../declarations'+import { useCredentialStatus } from '@/app/components/header/account-setting/model-provider-page/model-auth/hooks'+import { useSystemFeaturesQuery } from '@/context/global-public-context'+import {+ PreferredProviderTypeEnum,+} from '../declarations'+import { providerSupportsCredits } from '../supports-credits'+import { useTrialCredits } from './use-trial-credits'++export type UsagePriority = 'credits' | 'apiKey' | 'apiKeyOnly'++export type CardVariant+ = | 'credits-active'+ | 'credits-fallback'+ | 'credits-exhausted'+ | 'no-usage'+ | 'api-fallback'+ | 'api-active'+ | 'api-required-add'+ | 'api-required-configure'+ | 'api-unavailable'++export type CredentialPanelState = {+ variant: CardVariant+ priority: UsagePriority+ supportsCredits: boolean+ showPrioritySwitcher: boolean+ hasCredentials: boolean+ isCreditsExhausted: boolean+ credentialName: string | undefined+ credits: number+}++const DESTRUCTIVE_VARIANTS = new Set<CardVariant>([+ 'credits-exhausted',+ 'no-usage',+ 'api-unavailable',+])++export const isDestructiveVariant = (variant: CardVariant) =>+ DESTRUCTIVE_VARIANTS.has(variant)++function deriveVariant(+ priority: UsagePriority,+ isExhausted: boolean,+ hasCredential: boolean,+ authorized: boolean | undefined,+ credentialName: string | undefined,+): CardVariant {+ if (priority === 'credits') {+ if (!isExhausted)+ return 'credits-active'+ if (hasCredential && authorized)+ return 'api-fallback'+ if (hasCredential && !authorized)+ return 'no-usage'+ return 'credits-exhausted'+ }++ if (hasCredential && authorized)+ return 'api-active'++ if (priority === 'apiKey' && !isExhausted)+ return 'credits-fallback'++ if (priority === 'apiKey' && !hasCredential)+ return 'no-usage'++ if (hasCredential && !authorized)+ return credentialName ? 'api-unavailable' : 'api-required-configure'+ return 'api-required-add'+}++export function useCredentialPanelState(provider: ModelProvider | undefined): CredentialPanelState {+ const { isExhausted, credits } = useTrialCredits()+ const {+ hasCredential,+ authorized,+ current_credential_name,+ } = useCredentialStatus(provider)++ const { data: systemFeatures } = useSystemFeaturesQuery()+ const trialModels = systemFeatures?.trial_models++ const preferredType = provider?.preferred_provider_type++ const supportsCredits = providerSupportsCredits(provider, trialModels)++ const priority: UsagePriority = !supportsCredits+ ? 'apiKeyOnly'+ : preferredType === PreferredProviderTypeEnum.system+ ? 'credits'+ : 'apiKey'++ const showPrioritySwitcher = supportsCredits++ const variant = deriveVariant(priority, isExhausted, hasCredential, !!authorized, current_credential_name)++ return {+ variant,+ priority,+ supportsCredits,+ showPrioritySwitcher,+ hasCredentials: hasCredential,+ isCreditsExhausted: isExhausted,+ credentialName: current_credential_name,+ credits,+ }+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits.spec.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits.spec.tsnew file mode 100644index 00000000000..fd7cc6d4299--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits.spec.ts@@ -0,0 +1,88 @@+import { renderHook } from '@testing-library/react'+import { useTrialCredits } from './use-trial-credits'++const mockUseCurrentWorkspace = vi.fn()++vi.mock('@/service/use-common', () => ({+ useCurrentWorkspace: () => mockUseCurrentWorkspace(),+}))++describe('useTrialCredits', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseCurrentWorkspace.mockReturnValue({+ data: {+ trial_credits: 100,+ trial_credits_used: 40,+ next_credit_reset_date: '2026-04-01',+ },+ isPending: false,+ })+ })++ describe('when workspace data is available', () => {+ it('should return the remaining credits and reset date', () => {+ const { result } = renderHook(() => useTrialCredits())++ expect(result.current).toEqual({+ credits: 60,+ totalCredits: 100,+ isExhausted: false,+ isLoading: false,+ nextCreditResetDate: '2026-04-01',+ })+ })++ it('should keep the hook out of loading state during a background refetch', () => {+ mockUseCurrentWorkspace.mockReturnValue({+ data: {+ trial_credits: 80,+ trial_credits_used: 20,+ next_credit_reset_date: '2026-05-01',+ },+ isPending: true,+ })++ const { result } = renderHook(() => useTrialCredits())++ expect(result.current.isLoading).toBe(false)+ expect(result.current.credits).toBe(60)+ expect(result.current.isExhausted).toBe(false)+ })+ })++ describe('when workspace data is missing or exhausted', () => {+ it('should report loading while the first workspace request is pending', () => {+ mockUseCurrentWorkspace.mockReturnValue({+ data: undefined,+ isPending: true,+ })++ const { result } = renderHook(() => useTrialCredits())++ expect(result.current).toEqual({+ credits: 0,+ totalCredits: 0,+ isExhausted: true,+ isLoading: true,+ nextCreditResetDate: undefined,+ })+ })++ it('should clamp negative remaining credits to zero', () => {+ mockUseCurrentWorkspace.mockReturnValue({+ data: {+ trial_credits: 10,+ trial_credits_used: 99,+ next_credit_reset_date: undefined,+ },+ isPending: false,+ })++ const { result } = renderHook(() => useTrialCredits())++ expect(result.current.credits).toBe(0)+ expect(result.current.isExhausted).toBe(true)+ })+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits.ts b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits.tsnew file mode 100644index 00000000000..91ff7b88204--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/use-trial-credits.ts@@ -0,0 +1,15 @@+import { useCurrentWorkspace } from '@/service/use-common'++export const useTrialCredits = () => {+ const { data: currentWorkspace, isPending } = useCurrentWorkspace()+ const totalCredits = currentWorkspace?.trial_credits ?? 0+ const credits = Math.max(totalCredits - (currentWorkspace?.trial_credits_used ?? 0), 0)++ return {+ credits,+ totalCredits,+ isExhausted: credits <= 0,+ isLoading: isPending && !currentWorkspace,+ nextCreditResetDate: currentWorkspace?.next_credit_reset_date,+ }+}diff --git a/web/app/components/header/account-setting/model-provider-page/provider-icon/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/provider-icon/__tests__/index.spec.tsxindex 0427e80d0a0..f2871b170a2 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-icon/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-icon/__tests__/index.spec.tsx@@ -74,6 +74,26 @@ describe('ProviderIcon', () => {expect(screen.getByTestId('openai-icon')).toBeInTheDocument()})+ it('should apply custom className to special provider wrappers', () => {+ const { rerender, container } = render(+ <ProviderIcon+ provider={createProvider({ provider: 'langgenius/anthropic/anthropic' })}+ className="custom-wrapper"+ />,+ )++ expect(container.firstChild).toHaveClass('custom-wrapper')++ rerender(+ <ProviderIcon+ provider={createProvider({ provider: 'langgenius/openai/openai' })}+ className="custom-wrapper"+ />,+ )++ expect(container.firstChild).toHaveClass('custom-wrapper')+ })+it('should render generic provider with image and label', () => {const provider = createProvider({ label: { en_US: 'Custom', zh_Hans: '自定义' } })render(<ProviderIcon provider={provider} />)@@ -94,4 +114,19 @@ describe('ProviderIcon', () => {const img = screen.getByAltText('provider-icon') as HTMLImageElementexpect(img.src).toBe('https://example.com/dark.png')})++ it('should fall back to localized labels when available', () => {+ const mockLang = vi.mocked(useLanguage)+ mockLang.mockReturnValue('zh_Hans')++ render(+ <ProviderIcon+ provider={createProvider({+ label: { en_US: 'Custom', zh_Hans: '自定义' },+ })}+ />,+ )++ expect(screen.getByText('自定义')).toBeInTheDocument()+ })})diff --git a/web/app/components/header/account-setting/model-provider-page/provider-icon/index.tsx b/web/app/components/header/account-setting/model-provider-page/provider-icon/index.tsxindex 199e6c931c1..3a764643077 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-icon/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-icon/index.tsx@@ -21,7 +21,7 @@ const ProviderIcon: FC<ProviderIconProps> = ({if (provider.provider === 'langgenius/anthropic/anthropic') {return (- <div className="mb-2 py-[7px]">+ <div className={cn('py-[7px]', className)}>{theme === Theme.dark && <AnthropicLight className="h-2.5 w-[90px]" />}{theme === Theme.light && <AnthropicDark className="h-2.5 w-[90px]" />}</div>@@ -30,7 +30,7 @@ const ProviderIcon: FC<ProviderIconProps> = ({if (provider.provider === 'langgenius/openai/openai') {return (- <div className="mb-2">+ <div className={className}><Openai className="h-6 w-auto text-text-inverted-dimmed" /></div>)@@ -48,7 +48,7 @@ const ProviderIcon: FC<ProviderIconProps> = ({)}className="h-6 w-6"/>- <div className="system-md-semibold text-text-primary">+ <div className="text-text-primary system-md-semibold">{renderI18nObject(provider.label, language)}</div></div>diff --git a/web/app/components/header/account-setting/model-provider-page/status-mapping.ts b/web/app/components/header/account-setting/model-provider-page/status-mapping.tsnew file mode 100644index 00000000000..2de2876e202--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/status-mapping.ts@@ -0,0 +1,9 @@+import { ModelStatusEnum } from './declarations'++export const MODEL_STATUS_I18N_KEY: Partial<Record<ModelStatusEnum, string>> = {+ [ModelStatusEnum.quotaExceeded]: 'modelProvider.selector.creditsExhausted',+ [ModelStatusEnum.noConfigure]: 'modelProvider.selector.configureRequired',+ [ModelStatusEnum.noPermission]: 'modelProvider.selector.incompatible',+ [ModelStatusEnum.disabled]: 'modelProvider.selector.disabled',+ [ModelStatusEnum.credentialRemoved]: 'modelProvider.selector.apiKeyUnavailable',+}diff --git a/web/app/components/header/account-setting/model-provider-page/supports-credits.spec.ts b/web/app/components/header/account-setting/model-provider-page/supports-credits.spec.tsnew file mode 100644index 00000000000..ef2e79c79b6--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/supports-credits.spec.ts@@ -0,0 +1,42 @@+import type { ModelProvider } from './declarations'+import { CurrentSystemQuotaTypeEnum } from './declarations'+import { providerSupportsCredits } from './supports-credits'++vi.mock('@/config', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/config')>()+ return { ...actual, IS_CLOUD_EDITION: true }+})++const makeProvider = (overrides: Partial<ModelProvider> = {}): ModelProvider => ({+ provider: 'langgenius/openai/openai',+ system_configuration: {+ enabled: true,+ current_quota_type: CurrentSystemQuotaTypeEnum.trial,+ quota_configurations: [],+ },+ ...overrides,+} as ModelProvider)++describe('providerSupportsCredits', () => {+ it('returns true when the provider is system-enabled and listed in trial_models', () => {+ expect(providerSupportsCredits(makeProvider(), ['langgenius/openai/openai'])).toBe(true)+ })++ it('returns false when the provider is not listed in trial_models', () => {+ expect(providerSupportsCredits(makeProvider(), ['langgenius/anthropic/anthropic'])).toBe(false)+ })++ it('returns false when system hosting is disabled', () => {+ expect(providerSupportsCredits(makeProvider({+ system_configuration: {+ enabled: false,+ current_quota_type: CurrentSystemQuotaTypeEnum.trial,+ quota_configurations: [],+ },+ }), ['langgenius/openai/openai'])).toBe(false)+ })++ it('returns false for an undefined provider', () => {+ expect(providerSupportsCredits(undefined, ['langgenius/openai/openai'])).toBe(false)+ })+})diff --git a/web/app/components/header/account-setting/model-provider-page/supports-credits.ts b/web/app/components/header/account-setting/model-provider-page/supports-credits.tsnew file mode 100644index 00000000000..2e9fcea12c3--- /dev/null+++ b/web/app/components/header/account-setting/model-provider-page/supports-credits.ts@@ -0,0 +1,14 @@+import type { ModelProvider } from './declarations'+import { IS_CLOUD_EDITION } from '@/config'++type CreditAwareProvider = Pick<ModelProvider, 'provider' | 'system_configuration'>++export const providerSupportsCredits = (+ provider: CreditAwareProvider | undefined,+ trialModels: readonly string[] | undefined,+): boolean => {+ if (!IS_CLOUD_EDITION || !provider?.system_configuration.enabled)+ return false++ return !!provider.provider && !!trialModels?.includes(provider.provider)+}diff --git a/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsx b/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsxindex 6fa8fd0cbb6..fd3577a7cf0 100644--- a/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsx+++ b/web/app/components/header/account-setting/model-provider-page/system-model-selector/__tests__/index.spec.tsx@@ -1,7 +1,6 @@import type { DefaultModelResponse } from '../../declarations'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { vi } from 'vitest'-import { ToastContext } from '@/app/components/base/toast/context'import { ModelTypeEnum } from '../../declarations'import SystemModel from '../index'@@ -27,6 +26,7 @@ vi.mock('react-i18next', async () => {const mockNotify = vi.hoisted(() => vi.fn())const mockUpdateModelList = vi.hoisted(() => vi.fn())+const mockInvalidateDefaultModel = vi.hoisted(() => vi.fn())const mockUpdateDefaultModel = vi.hoisted(() => vi.fn(() => Promise.resolve({ result: 'success' })))let mockIsCurrentWorkspaceManager = true@@ -43,15 +43,11 @@ vi.mock('@/context/provider-context', () => ({}),}))-vi.mock('@/app/components/base/toast/context', async (importOriginal) => {- const actual = await importOriginal<typeof import('@/app/components/base/toast/context')>()- return {- ...actual,- useToastContext: () => ({- notify: mockNotify,- }),- }-})+vi.mock('@/app/components/base/toast/context', () => ({+ useToastContext: () => ({+ notify: mockNotify,+ }),+}))vi.mock('../../hooks', () => ({useModelList: () => ({@@ -62,6 +58,7 @@ vi.mock('../../hooks', () => ({vi.fn(),],useUpdateModelList: () => mockUpdateModelList,+ useInvalidateDefaultModel: () => mockInvalidateDefaultModel,}))vi.mock('@/service/common', () => ({@@ -94,24 +91,18 @@ const defaultProps = {}describe('SystemModel', () => {- const renderSystemModel = (props: typeof defaultProps) => render(- <ToastContext.Provider value={{ notify: mockNotify, close: vi.fn() }}>- <SystemModel {...props} />- </ToastContext.Provider>,- )-beforeEach(() => {vi.clearAllMocks()mockIsCurrentWorkspaceManager = true})it('should render settings button', () => {- renderSystemModel(defaultProps)+ render(<SystemModel {...defaultProps} />)expect(screen.getByRole('button', { name: /system model settings/i })).toBeInTheDocument()})- it('should open modal when button is clicked', async () => {- renderSystemModel(defaultProps)+ it('should open dialog when button is clicked', async () => {+ render(<SystemModel {...defaultProps} />)const button = screen.getByRole('button', { name: /system model settings/i })fireEvent.click(button)await waitFor(() => {@@ -120,12 +111,18 @@ describe('SystemModel', () => {})it('should disable button when loading', () => {- renderSystemModel({ ...defaultProps, isLoading: true })+ render(<SystemModel {...defaultProps} isLoading />)expect(screen.getByRole('button', { name: /system model settings/i })).toBeDisabled()})- it('should close modal when cancel is clicked', async () => {- renderSystemModel(defaultProps)+ it('should render the primary button variant when configuration is required', () => {+ render(<SystemModel {...defaultProps} notConfigured />)++ expect(screen.getByRole('button', { name: /system model settings/i })).toHaveClass('btn-primary')+ })++ it('should close dialog when cancel is clicked', async () => {+ render(<SystemModel {...defaultProps} />)fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))await waitFor(() => {expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument()@@ -137,7 +134,7 @@ describe('SystemModel', () => {})it('should save selected models and show success feedback', async () => {- renderSystemModel(defaultProps)+ render(<SystemModel {...defaultProps} />)fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))await waitFor(() => {@@ -155,109 +152,39 @@ describe('SystemModel', () => {type: 'success',message: 'Modified successfully',})+ expect(mockInvalidateDefaultModel).toHaveBeenCalledTimes(5)expect(mockUpdateModelList).toHaveBeenCalledTimes(5)})})- it('should disable save when user is not workspace manager', async () => {- mockIsCurrentWorkspaceManager = false- renderSystemModel(defaultProps)+ it('should keep the dialog open when saving does not succeed', async () => {+ mockUpdateDefaultModel.mockResolvedValueOnce({ result: 'failed' })- fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))- await waitFor(() => {- expect(screen.getByRole('button', { name: /save/i })).toBeDisabled()- })- })-- it('should render primary variant button when notConfigured is true', () => {- renderSystemModel({ ...defaultProps, notConfigured: true })- const button = screen.getByRole('button', { name: /system model settings/i })- expect(button.className).toContain('btn-primary')- })-- it('should keep modal open when save returns non-success result', async () => {- mockUpdateDefaultModel.mockResolvedValueOnce({ result: 'error' })- renderSystemModel(defaultProps)+ render(<SystemModel {...defaultProps} />)fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))await waitFor(() => {expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument()})- const selectorButtons = screen.getAllByRole('button', { name: 'Mock Model Selector' })- selectorButtons.forEach(button => fireEvent.click(button))-fireEvent.click(screen.getByRole('button', { name: /save/i }))await waitFor(() => {expect(mockUpdateDefaultModel).toHaveBeenCalledTimes(1)- expect(mockNotify).not.toHaveBeenCalled()})-- // Modal should still be open after failed saveexpect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument()- expect(screen.getByRole('button', { name: /cancel/i })).toBeInTheDocument()- })-- it('should not add duplicate model type to changedModelTypes when same type is selected twice', async () => {- renderSystemModel(defaultProps)-- fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))- await waitFor(() => {- expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument()- })-- // Click the first selector twice (textGeneration type)- const selectorButtons = screen.getAllByRole('button', { name: 'Mock Model Selector' })- fireEvent.click(selectorButtons[0])- fireEvent.click(selectorButtons[0])-- fireEvent.click(screen.getByRole('button', { name: /save/i }))-- await waitFor(() => {- expect(mockUpdateDefaultModel).toHaveBeenCalledTimes(1)- // textGeneration was changed, so updateModelList is called once for it- expect(mockUpdateModelList).toHaveBeenCalledTimes(1)- })+ expect(mockNotify).not.toHaveBeenCalled()+ expect(mockInvalidateDefaultModel).not.toHaveBeenCalled()+ expect(mockUpdateModelList).not.toHaveBeenCalled()})- it('should call updateModelList for speech2text and tts types on save', async () => {- renderSystemModel(defaultProps)-- fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))- await waitFor(() => {- expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument()- })-- // Click speech2text (index 3) and tts (index 4) selectors- const selectorButtons = screen.getAllByRole('button', { name: 'Mock Model Selector' })- fireEvent.click(selectorButtons[3])- fireEvent.click(selectorButtons[4])-- fireEvent.click(screen.getByRole('button', { name: /save/i }))-- await waitFor(() => {- expect(mockUpdateModelList).toHaveBeenCalledTimes(2)- })- })-- it('should call updateModelList for each unique changed model type on save', async () => {- renderSystemModel(defaultProps)+ it('should disable save when user is not workspace manager', async () => {+ mockIsCurrentWorkspaceManager = false+ render(<SystemModel {...defaultProps} />)fireEvent.click(screen.getByRole('button', { name: /system model settings/i }))await waitFor(() => {- expect(screen.getByRole('button', { name: /save/i })).toBeInTheDocument()- })-- // Click embedding and rerank selectors (indices 1 and 2)- const selectorButtons = screen.getAllByRole('button', { name: 'Mock Model Selector' })- fireEvent.click(selectorButtons[1])- fireEvent.click(selectorButtons[2])-- fireEvent.click(screen.getByRole('button', { name: /save/i }))-- await waitFor(() => {- expect(mockUpdateModelList).toHaveBeenCalledTimes(2)+ expect(screen.getByRole('button', { name: /save/i })).toBeDisabled()})})})diff --git a/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx b/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsxindex 5df062789b1..a103cafd91a 100644--- a/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx+++ b/web/app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx@@ -3,22 +3,27 @@ import type {DefaultModel,DefaultModelResponse,} from '../declarations'-import { RiEqualizer2Line, RiLoader2Line } from '@remixicon/react'import { useState } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'-import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'import { useToastContext } from '@/app/components/base/toast/context'-import Tooltip from '@/app/components/base/tooltip'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogTitle,+} from '@/app/components/base/ui/dialog'+import {+ Tooltip,+ TooltipContent,+ TooltipTrigger,+} from '@/app/components/base/ui/tooltip'import { useAppContext } from '@/context/app-context'import { useProviderContext } from '@/context/provider-context'import { updateDefaultModel } from '@/service/common'import { ModelTypeEnum } from '../declarations'import {+ useInvalidateDefaultModel,useModelList,useSystemDefaultModelAndModelList,useUpdateModelList,@@ -34,6 +39,21 @@ type SystemModelSelectorProps = {notConfigured: booleanisLoading?: boolean}++type SystemModelLabelKey+ = | 'modelProvider.systemReasoningModel.key'+ | 'modelProvider.embeddingModel.key'+ | 'modelProvider.rerankModel.key'+ | 'modelProvider.speechToTextModel.key'+ | 'modelProvider.ttsModel.key'++type SystemModelTipKey+ = | 'modelProvider.systemReasoningModel.tip'+ | 'modelProvider.embeddingModel.tip'+ | 'modelProvider.rerankModel.tip'+ | 'modelProvider.speechToTextModel.tip'+ | 'modelProvider.ttsModel.tip'+const SystemModel: FC<SystemModelSelectorProps> = ({textGenerationDefaultModel,embeddingsDefaultModel,@@ -48,6 +68,7 @@ const SystemModel: FC<SystemModelSelectorProps> = ({const { isCurrentWorkspaceManager } = useAppContext()const { textGenerationModelList } = useProviderContext()const updateModelList = useUpdateModelList()+ const invalidateDefaultModel = useInvalidateDefaultModel()const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)const { data: speech2textModelList } = useModelList(ModelTypeEnum.speech2text)@@ -106,154 +127,124 @@ const SystemModel: FC<SystemModelSelectorProps> = ({notify({ type: 'success', message: t('actionMsg.modifiedSuccessfully', { ns: 'common' }) })setOpen(false)- changedModelTypes.forEach((modelType) => {- if (modelType === ModelTypeEnum.textGeneration)- updateModelList(modelType)- else if (modelType === ModelTypeEnum.textEmbedding)- updateModelList(modelType)- else if (modelType === ModelTypeEnum.rerank)- updateModelList(modelType)- else if (modelType === ModelTypeEnum.speech2text)- updateModelList(modelType)- else if (modelType === ModelTypeEnum.tts)- updateModelList(modelType)- })+ const allModelTypes = [ModelTypeEnum.textGeneration, ModelTypeEnum.textEmbedding, ModelTypeEnum.rerank, ModelTypeEnum.speech2text, ModelTypeEnum.tts]+ allModelTypes.forEach(type => invalidateDefaultModel(type))+ changedModelTypes.forEach(type => updateModelList(type))}}+ const renderModelLabel = (labelKey: SystemModelLabelKey, tipKey: SystemModelTipKey) => {+ const tipText = t(tipKey, { ns: 'common' })++ return (+ <div className="flex min-h-6 items-center text-[13px] font-medium text-text-secondary">+ {t(labelKey, { ns: 'common' })}+ <Tooltip>+ <TooltipTrigger+ aria-label={tipText}+ delay={0}+ render={(+ <span className="ml-0.5 flex h-4 w-4 shrink-0 items-center justify-center">+ <span aria-hidden className="i-ri-question-line h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary" />+ </span>+ )}+ />+ <TooltipContent>+ <div className="w-[261px] text-text-tertiary">+ {tipText}+ </div>+ </TooltipContent>+ </Tooltip>+ </div>+ )+ }+return (- <PortalToFollowElem- open={open}- onOpenChange={setOpen}- placement="bottom-end"- offset={{- mainAxis: 4,- crossAxis: 8,- }}- >- <PortalToFollowElemTrigger asChild onClick={() => setOpen(v => !v)}>- <Button- className="relative"- variant={notConfigured ? 'primary' : 'secondary'}- size="small"- disabled={isLoading}+ <>+ <Button+ className="relative"+ variant={notConfigured ? 'primary' : 'secondary'}+ size="small"+ disabled={isLoading}+ onClick={() => setOpen(true)}+ >+ {isLoading+ ? <span className="i-ri-loader-2-line mr-1 h-3.5 w-3.5 animate-spin" />+ : <span className="i-ri-equalizer-2-line mr-1 h-3.5 w-3.5" />}+ {t('modelProvider.systemModelSettings', { ns: 'common' })}+ </Button>+ <Dialog open={open} onOpenChange={setOpen}>+ <DialogContent+ backdropProps={{ forceRender: true }}+ className="w-[480px] max-w-[480px] overflow-hidden p-0">- {isLoading- ? <RiLoader2Line className="mr-1 h-3.5 w-3.5 animate-spin" />- : <RiEqualizer2Line className="mr-1 h-3.5 w-3.5" />}- {t('modelProvider.systemModelSettings', { ns: 'common' })}- </Button>- </PortalToFollowElemTrigger>- <PortalToFollowElemContent className="z-[60]">- <div className="w-[360px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg pt-4 shadow-xl">- <div className="px-6 py-1">- <div className="flex h-8 items-center text-[13px] font-medium text-text-primary">- {t('modelProvider.systemReasoningModel.key', { ns: 'common' })}- <Tooltip- popupContent={(- <div className="w-[261px] text-text-tertiary">- {t('modelProvider.systemReasoningModel.tip', { ns: 'common' })}- </div>- )}- triggerClassName="ml-0.5 w-4 h-4 shrink-0"- />- </div>- <div>- <ModelSelector- defaultModel={currentTextGenerationDefaultModel}- modelList={textGenerationModelList}- onSelect={model => handleChangeDefaultModel(ModelTypeEnum.textGeneration, model)}- />- </div>+ <DialogCloseButton className="right-5 top-5" />+ <div className="px-6 pb-3 pr-14 pt-6">+ <DialogTitle className="text-text-primary title-2xl-semi-bold">+ {t('modelProvider.systemModelSettings', { ns: 'common' })}+ </DialogTitle></div>- <div className="px-6 py-1">- <div className="flex h-8 items-center text-[13px] font-medium text-text-primary">- {t('modelProvider.embeddingModel.key', { ns: 'common' })}- <Tooltip- popupContent={(- <div className="w-[261px] text-text-tertiary">- {t('modelProvider.embeddingModel.tip', { ns: 'common' })}- </div>- )}- triggerClassName="ml-0.5 w-4 h-4 shrink-0"- />+ <div className="flex flex-col gap-4 px-6 py-3">+ <div className="flex flex-col gap-1">+ {renderModelLabel('modelProvider.systemReasoningModel.key', 'modelProvider.systemReasoningModel.tip')}+ <div>+ <ModelSelector+ defaultModel={currentTextGenerationDefaultModel}+ modelList={textGenerationModelList}+ onSelect={model => handleChangeDefaultModel(ModelTypeEnum.textGeneration, model)}+ />+ </div></div>- <div>- <ModelSelector- defaultModel={currentEmbeddingsDefaultModel}- modelList={embeddingModelList}- onSelect={model => handleChangeDefaultModel(ModelTypeEnum.textEmbedding, model)}- />- </div>- </div>- <div className="px-6 py-1">- <div className="flex h-8 items-center text-[13px] font-medium text-text-primary">- {t('modelProvider.rerankModel.key', { ns: 'common' })}- <Tooltip- popupContent={(- <div className="w-[261px] text-text-tertiary">- {t('modelProvider.rerankModel.tip', { ns: 'common' })}- </div>- )}- triggerClassName="ml-0.5 w-4 h-4 shrink-0"- />+ <div className="flex flex-col gap-1">+ {renderModelLabel('modelProvider.embeddingModel.key', 'modelProvider.embeddingModel.tip')}+ <div>+ <ModelSelector+ defaultModel={currentEmbeddingsDefaultModel}+ modelList={embeddingModelList}+ onSelect={model => handleChangeDefaultModel(ModelTypeEnum.textEmbedding, model)}+ />+ </div></div>- <div>- <ModelSelector- defaultModel={currentRerankDefaultModel}- modelList={rerankModelList}- onSelect={model => handleChangeDefaultModel(ModelTypeEnum.rerank, model)}- />+ <div className="flex flex-col gap-1">+ {renderModelLabel('modelProvider.rerankModel.key', 'modelProvider.rerankModel.tip')}+ <div>+ <ModelSelector+ defaultModel={currentRerankDefaultModel}+ modelList={rerankModelList}+ onSelect={model => handleChangeDefaultModel(ModelTypeEnum.rerank, model)}+ />+ </div></div>- </div>- <div className="px-6 py-1">- <div className="flex h-8 items-center text-[13px] font-medium text-text-primary">- {t('modelProvider.speechToTextModel.key', { ns: 'common' })}- <Tooltip- popupContent={(- <div className="w-[261px] text-text-tertiary">- {t('modelProvider.speechToTextModel.tip', { ns: 'common' })}- </div>- )}- triggerClassName="ml-0.5 w-4 h-4 shrink-0"- />- </div>- <div>- <ModelSelector- defaultModel={currentSpeech2textDefaultModel}- modelList={speech2textModelList}- onSelect={model => handleChangeDefaultModel(ModelTypeEnum.speech2text, model)}- />- </div>- </div>- <div className="px-6 py-1">- <div className="flex h-8 items-center text-[13px] font-medium text-text-primary">- {t('modelProvider.ttsModel.key', { ns: 'common' })}- <Tooltip- popupContent={(- <div className="w-[261px] text-text-tertiary">- {t('modelProvider.ttsModel.tip', { ns: 'common' })}- </div>- )}- triggerClassName="ml-0.5 w-4 h-4 shrink-0"- />+ <div className="flex flex-col gap-1">+ {renderModelLabel('modelProvider.speechToTextModel.key', 'modelProvider.speechToTextModel.tip')}+ <div>+ <ModelSelector+ defaultModel={currentSpeech2textDefaultModel}+ modelList={speech2textModelList}+ onSelect={model => handleChangeDefaultModel(ModelTypeEnum.speech2text, model)}+ />+ </div></div>- <div>- <ModelSelector- defaultModel={currentTTSDefaultModel}- modelList={ttsModelList}- onSelect={model => handleChangeDefaultModel(ModelTypeEnum.tts, model)}- />+ <div className="flex flex-col gap-1">+ {renderModelLabel('modelProvider.ttsModel.key', 'modelProvider.ttsModel.tip')}+ <div>+ <ModelSelector+ defaultModel={currentTTSDefaultModel}+ modelList={ttsModelList}+ onSelect={model => handleChangeDefaultModel(ModelTypeEnum.tts, model)}+ />+ </div></div></div>- <div className="flex items-center justify-end px-6 py-4">+ <div className="flex items-center justify-end gap-2 px-6 pb-6 pt-5"><Button+ className="min-w-[72px]"onClick={() => setOpen(false)}>{t('operation.cancel', { ns: 'common' })}</Button><Button- className="ml-2"+ className="min-w-[72px]"variant="primary"onClick={handleSave}disabled={!isCurrentWorkspaceManager}@@ -261,9 +252,9 @@ const SystemModel: FC<SystemModelSelectorProps> = ({{t('operation.save', { ns: 'common' })}</Button></div>- </div>- </PortalToFollowElemContent>- </PortalToFollowElem>+ </DialogContent>+ </Dialog>+ </>)}diff --git a/web/app/components/header/account-setting/model-provider-page/utils.ts b/web/app/components/header/account-setting/model-provider-page/utils.tsindex d8fcfad4656..f9478065104 100644--- a/web/app/components/header/account-setting/model-provider-page/utils.ts+++ b/web/app/components/header/account-setting/model-provider-page/utils.ts@@ -1,9 +1,11 @@+import type { ComponentType } from 'react'import type {CredentialFormSchemaSelect,CredentialFormSchemaTextInput,FormValue,ModelLoadBalancingConfig,} from './declarations'+import { AnthropicShortLight, Deepseek, Gemini, Grok, OpenaiSmall, Tongyi } from '@/app/components/base/icons/src/public/llm'import {deleteModelProvider,setModelProvider,@@ -21,8 +23,31 @@ import {export { ModelProviderQuotaGetPaid } from '@/types/model-provider'+export const providerToPluginId = (providerKey: string): string => {+ const lastSlash = providerKey.lastIndexOf('/')+ return lastSlash > 0 ? providerKey.slice(0, lastSlash) : ''+}+export const MODEL_PROVIDER_QUOTA_GET_PAID = [ModelProviderQuotaGetPaid.OPENAI, ModelProviderQuotaGetPaid.ANTHROPIC, ModelProviderQuotaGetPaid.GEMINI, ModelProviderQuotaGetPaid.X, ModelProviderQuotaGetPaid.DEEPSEEK, ModelProviderQuotaGetPaid.TONGYI]+export const providerIconMap: Record<ModelProviderQuotaGetPaid, ComponentType<{ className?: string }>> = {+ [ModelProviderQuotaGetPaid.OPENAI]: OpenaiSmall,+ [ModelProviderQuotaGetPaid.ANTHROPIC]: AnthropicShortLight,+ [ModelProviderQuotaGetPaid.GEMINI]: Gemini,+ [ModelProviderQuotaGetPaid.X]: Grok,+ [ModelProviderQuotaGetPaid.DEEPSEEK]: Deepseek,+ [ModelProviderQuotaGetPaid.TONGYI]: Tongyi,+}++export const providerKeyToPluginId: Record<ModelProviderQuotaGetPaid, string> = {+ [ModelProviderQuotaGetPaid.OPENAI]: 'langgenius/openai',+ [ModelProviderQuotaGetPaid.ANTHROPIC]: 'langgenius/anthropic',+ [ModelProviderQuotaGetPaid.GEMINI]: 'langgenius/gemini',+ [ModelProviderQuotaGetPaid.X]: 'langgenius/x',+ [ModelProviderQuotaGetPaid.DEEPSEEK]: 'langgenius/deepseek',+ [ModelProviderQuotaGetPaid.TONGYI]: 'langgenius/tongyi',+}+export const modelNameMap = {[ModelProviderQuotaGetPaid.OPENAI]: 'OpenAI',[ModelProviderQuotaGetPaid.ANTHROPIC]: 'Anthropic',diff --git a/web/app/components/header/index.tsx b/web/app/components/header/index.tsxindex 64498a82f83..0b86a6259b2 100644--- a/web/app/components/header/index.tsx+++ b/web/app/components/header/index.tsx@@ -91,7 +91,7 @@ const Header = () => {return (<div className="flex h-[56px] items-center">- <div className="flex min-w-0 flex-[1] items-center pl-3 pr-2 min-[1280px]:pr-3">+ <div className="flex min-w-0 flex-[1] items-center pl-3 pr-2 min-[1280px]:pr-3">{renderLogo()}<div className="mx-1.5 shrink-0 font-light text-divider-deep">/</div><WorkspaceProvider>diff --git a/web/app/components/plugins/__tests__/utils.spec.ts b/web/app/components/plugins/__tests__/utils.spec.tsindex 0dc166b1754..c626bdff7ff 100644--- a/web/app/components/plugins/__tests__/utils.spec.ts+++ b/web/app/components/plugins/__tests__/utils.spec.ts@@ -1,7 +1,17 @@import type { TagKey } from '../constants'+import type { Plugin } from '../types'import { describe, expect, it } from 'vitest'+import { API_PREFIX, MARKETPLACE_API_PREFIX } from '@/config'import { PluginCategoryEnum } from '../types'-import { getValidCategoryKeys, getValidTagKeys } from '../utils'+import { getPluginCardIconUrl, getValidCategoryKeys, getValidTagKeys } from '../utils'++const createPlugin = (overrides: Partial<Pick<Plugin, 'from' | 'name' | 'org' | 'type'>> = {}): Pick<Plugin, 'from' | 'name' | 'org' | 'type'> => ({+ from: 'github',+ name: 'demo-plugin',+ org: 'langgenius',+ type: 'plugin',+ ...overrides,+})describe('plugins/utils', () => {describe('getValidTagKeys', () => {@@ -47,4 +57,31 @@ describe('plugins/utils', () => {expect(getValidCategoryKeys('')).toBeUndefined()})})++ describe('getPluginCardIconUrl', () => {+ it('returns an empty string when icon is missing', () => {+ expect(getPluginCardIconUrl(createPlugin(), undefined, 'tenant-1')).toBe('')+ })++ it('returns absolute urls and root-relative urls as-is', () => {+ expect(getPluginCardIconUrl(createPlugin(), 'https://example.com/icon.png', 'tenant-1')).toBe('https://example.com/icon.png')+ expect(getPluginCardIconUrl(createPlugin(), '/icons/demo.png', 'tenant-1')).toBe('/icons/demo.png')+ })++ it('builds the marketplace icon url for plugins and bundles', () => {+ expect(getPluginCardIconUrl(createPlugin({ from: 'marketplace' }), 'icon.png', 'tenant-1'))+ .toBe(`${MARKETPLACE_API_PREFIX}/plugins/langgenius/demo-plugin/icon`)+ expect(getPluginCardIconUrl(createPlugin({ from: 'marketplace', type: 'bundle' }), 'icon.png', 'tenant-1'))+ .toBe(`${MARKETPLACE_API_PREFIX}/bundles/langgenius/demo-plugin/icon`)+ })++ it('falls back to the raw icon when tenant id is missing for non-marketplace plugins', () => {+ expect(getPluginCardIconUrl(createPlugin(), 'icon.png', '')).toBe('icon.png')+ })++ it('builds the workspace icon url for tenant-scoped plugins', () => {+ expect(getPluginCardIconUrl(createPlugin(), 'icon.png', 'tenant-1'))+ .toBe(`${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=tenant-1&filename=icon.png`)+ })+ })})diff --git a/web/app/components/plugins/card/__tests__/index.spec.tsx b/web/app/components/plugins/card/__tests__/index.spec.tsxindex aef89bd371f..37cdd58985d 100644--- a/web/app/components/plugins/card/__tests__/index.spec.tsx+++ b/web/app/components/plugins/card/__tests__/index.spec.tsx@@ -2,6 +2,7 @@ import type { Plugin } from '../../types'import { render, screen } from '@testing-library/react'import * as React from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { API_PREFIX, MARKETPLACE_API_PREFIX } from '@/config'import { PluginCategoryEnum } from '../../types'import Card from '../index'@@ -40,6 +41,12 @@ vi.mock('@/utils/format', () => ({formatNumber: (num: number) => num.toLocaleString(),}))+vi.mock('@/context/app-context', () => ({+ useSelector: (selector: (value: { currentWorkspace: { id: string } }) => string) => selector({+ currentWorkspace: { id: 'workspace-123' },+ }),+}))+vi.mock('@/utils/mcp', () => ({shouldUseMcpIcon: (src: unknown) => typeof src === 'object' && src !== null && (src as { content?: string })?.content === '🔗',}))@@ -189,6 +196,36 @@ describe('Card', () => {expect(iconElement).toBeInTheDocument()})+ it('should normalize package icon filenames to workspace icon urls', () => {+ const plugin = createMockPlugin({+ from: 'package',+ icon: 'custom-icon.png',+ })++ const { container } = render(<Card payload={plugin} />)++ const iconElement = container.querySelector('[style*="background-image"]')+ expect(iconElement).toBeInTheDocument()+ expect(iconElement).toHaveStyle({+ backgroundImage: `url(${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=workspace-123&filename=custom-icon.png)`,+ })+ })++ it('should normalize marketplace icon filenames to marketplace icon urls', () => {+ const plugin = createMockPlugin({+ from: 'marketplace',+ icon: 'custom-icon.png',+ })++ const { container } = render(<Card payload={plugin} />)++ const iconElement = container.querySelector('[style*="background-image"]')+ expect(iconElement).toBeInTheDocument()+ expect(iconElement).toHaveStyle({+ backgroundImage: `url(${MARKETPLACE_API_PREFIX}/plugins/${plugin.org}/${plugin.name}/icon)`,+ })+ })+it('should use icon_dark when theme is dark and icon_dark is provided', () => {// Set theme to darkmockTheme = 'dark'diff --git a/web/app/components/plugins/card/index.tsx b/web/app/components/plugins/card/index.tsxindex 0fc5e37241f..d1af00182f1 100644--- a/web/app/components/plugins/card/index.tsx+++ b/web/app/components/plugins/card/index.tsx@@ -3,6 +3,7 @@ import type { Plugin } from '../types'import { useTranslation } from '#i18n'import { RiAlertFill } from '@remixicon/react'import * as React from 'react'+import { useSelector } from '@/context/app-context'import { useGetLanguage } from '@/context/i18n'import useTheme from '@/hooks/use-theme'import {@@ -14,6 +15,7 @@ import Partner from '../base/badges/partner'import Verified from '../base/badges/verified'import Icon from '../card/base/card-icon'import { useCategories } from '../hooks'+import { getPluginCardIconUrl } from '../utils'import CornerMark from './base/corner-mark'import Description from './base/description'import OrgInfo from './base/org-info'@@ -50,9 +52,14 @@ const Card = ({const locale = useGetLanguage()const { t } = useTranslation()const { categoriesMap } = useCategories(true)- const { category, type, name, org, label, brief, icon, icon_dark, verified, badges = [] } = payload+ const currentWorkspaceId = useSelector(s => s.currentWorkspace.id)+ const { category, type, name, org, label, brief, icon, icon_dark, verified, badges = [], from } = payloadconst { theme } = useTheme()- const iconSrc = theme === Theme.dark && icon_dark ? icon_dark : icon+ const iconSrc = getPluginCardIconUrl(+ { from, name, org, type },+ theme === Theme.dark && icon_dark ? icon_dark : icon,+ currentWorkspaceId,+ )const getLocalizedText = (obj: Record<string, string> | undefined) =>obj ? renderI18nObject(obj, locale) : ''const isPartner = badges.includes('partner')@@ -101,7 +108,7 @@ const Card = ({&& (<div className="relative flex h-8 items-center gap-x-2 px-3 after:absolute after:bottom-0 after:left-0 after:right-0 after:top-0 after:bg-toast-warning-bg after:opacity-40"><RiAlertFill className="h-3 w-3 shrink-0 text-text-warning-secondary" />- <p className="system-xs-regular z-10 grow text-text-secondary">+ <p className="z-10 grow text-text-secondary system-xs-regular">{t('installModal.installWarning', { ns: 'plugin' })}</p></div>diff --git a/web/app/components/plugins/hooks.spec.ts b/web/app/components/plugins/hooks.spec.tsnew file mode 100644index 00000000000..6eeaa99d4c2--- /dev/null+++ b/web/app/components/plugins/hooks.spec.ts@@ -0,0 +1,128 @@+import type { PluginDetail } from './types'+import { useQuery } from '@tanstack/react-query'+import { renderHook } from '@testing-library/react'+import { consoleQuery } from '@/service/client'+import { usePluginsWithLatestVersion } from './hooks'+import { PluginSource } from './types'++vi.mock('@tanstack/react-query', () => ({+ useQuery: vi.fn(),+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ plugins: {+ latestVersions: {+ queryOptions: vi.fn((options: unknown) => options),+ },+ },+ },+}))++const createPlugin = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({+ id: 'plugin-1',+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+ name: 'demo-plugin',+ plugin_id: 'plugin-1',+ plugin_unique_identifier: '[email protected]',+ declaration: {} as PluginDetail['declaration'],+ installation_id: 'installation-1',+ tenant_id: 'tenant-1',+ endpoints_setups: 0,+ endpoints_active: 0,+ version: '1.0.0',+ latest_version: '1.0.0',+ latest_unique_identifier: '[email protected]',+ source: PluginSource.marketplace,+ meta: undefined,+ status: 'active',+ deprecated_reason: '',+ alternative_plugin_id: '',+ ...overrides,+})++describe('usePluginsWithLatestVersion', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(useQuery).mockReturnValue({ data: undefined } as never)+ })++ it('should disable latest-version querying when there are no marketplace plugins', () => {+ const plugins = [+ createPlugin({ plugin_id: 'github-plugin', source: PluginSource.github }),+ ]++ const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))++ expect(consoleQuery.plugins.latestVersions.queryOptions).toHaveBeenCalledWith({+ input: { body: { plugin_ids: [] } },+ enabled: false,+ })+ expect(result.current).toEqual(plugins)+ })++ it('should return the original plugins when version data is unavailable', () => {+ const plugins = [createPlugin()]++ const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))++ expect(result.current).toEqual(plugins)+ })++ it('should keep plugins unchanged when a plugin has no matching latest version', () => {+ const plugins = [createPlugin()]+ vi.mocked(useQuery).mockReturnValue({+ data: { versions: {} },+ } as never)++ const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))++ expect(result.current).toEqual(plugins)+ })++ it('should merge latest version fields for marketplace plugins with version data', () => {+ const plugins = [+ createPlugin(),+ createPlugin({+ id: 'plugin-2',+ plugin_id: 'plugin-2',+ plugin_unique_identifier: '[email protected]',+ latest_version: '1.0.0',+ latest_unique_identifier: '[email protected]',+ source: PluginSource.github,+ }),+ ]+ vi.mocked(useQuery).mockReturnValue({+ data: {+ versions: {+ 'plugin-1': {+ version: '1.1.0',+ unique_identifier: '[email protected]',+ status: 'deleted',+ deprecated_reason: 'replaced',+ alternative_plugin_id: 'plugin-3',+ },+ },+ },+ } as never)++ const { result } = renderHook(() => usePluginsWithLatestVersion(plugins))++ expect(consoleQuery.plugins.latestVersions.queryOptions).toHaveBeenCalledWith({+ input: { body: { plugin_ids: ['plugin-1'] } },+ enabled: true,+ })+ expect(result.current).toEqual([+ expect.objectContaining({+ plugin_id: 'plugin-1',+ latest_version: '1.1.0',+ latest_unique_identifier: '[email protected]',+ status: 'deleted',+ deprecated_reason: 'replaced',+ alternative_plugin_id: 'plugin-3',+ }),+ plugins[1],+ ])+ })+})diff --git a/web/app/components/plugins/hooks.ts b/web/app/components/plugins/hooks.tsindex 65d073cc2f2..5349cd4e852 100644--- a/web/app/components/plugins/hooks.ts+++ b/web/app/components/plugins/hooks.ts@@ -1,11 +1,14 @@import type { CategoryKey, TagKey } from './constants'+import type { PluginDetail } from './types'+import { useQuery } from '@tanstack/react-query'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'+import { consoleQuery } from '@/service/client'import {categoryKeys,tagKeys,} from './constants'-import { PluginCategoryEnum } from './types'+import { PluginCategoryEnum, PluginSource } from './types'export type Tag = {name: TagKey@@ -95,3 +98,39 @@ export const usePluginPageTabs = () => {]return tabs}++const EMPTY_PLUGINS: PluginDetail[] = []++export function usePluginsWithLatestVersion(plugins: PluginDetail[] = EMPTY_PLUGINS): PluginDetail[] {+ const marketplacePluginIds = useMemo(+ () => plugins+ .filter(p => p.source === PluginSource.marketplace)+ .map(p => p.plugin_id),+ [plugins],+ )++ const { data: latestVersionData } = useQuery(consoleQuery.plugins.latestVersions.queryOptions({+ input: { body: { plugin_ids: marketplacePluginIds } },+ enabled: !!marketplacePluginIds.length,+ }))++ return useMemo(() => {+ const versions = latestVersionData?.versions+ if (!versions)+ return plugins++ return plugins.map((plugin) => {+ const info = versions[plugin.plugin_id]+ if (!info)+ return plugin+ return {+ ...plugin,+ latest_version: info.version,+ latest_unique_identifier: info.unique_identifier,+ status: info.status,+ deprecated_reason: info.deprecated_reason,+ alternative_plugin_id: info.alternative_plugin_id,+ }+ })+ }, [plugins, latestVersionData])+}diff --git a/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx b/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsxindex 777a5174c64..fee88913b79 100644--- a/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx+++ b/web/app/components/plugins/install-plugin/install-bundle/__tests__/index.spec.tsx@@ -170,9 +170,13 @@ vi.mock('@/service/use-plugins', () => ({}))// Mock config-vi.mock('@/config', () => ({- MARKETPLACE_API_PREFIX: 'https://marketplace.example.com',-}))+vi.mock('@/config', async () => {+ const actual = await vi.importActual<typeof import('@/config')>('@/config')+ return {+ ...actual,+ MARKETPLACE_API_PREFIX: 'https://marketplace.example.com',+ }+})// Mock mitt contextvi.mock('@/context/mitt-context', () => ({diff --git a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.tsindex 1950a47f6d2..47f85d35cf0 100644--- a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts+++ b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/__tests__/use-install-multi-state.spec.ts@@ -266,10 +266,117 @@ describe('useInstallMultiState', () => {expect(result.current.plugins[1]).toBeDefined()})})++ it('should fall back to latest_version when marketplace plugin version is missing', async () => {+ mockMarketplaceData = {+ data: {+ list: [{+ plugin: {+ plugin_id: 'test-org/plugin-0',+ org: 'test-org',+ name: 'Test Plugin 0',+ version: '',+ latest_version: '2.0.0',+ },+ version: {+ unique_identifier: 'plugin-0-uid',+ },+ }],+ },+ }++ const params = createDefaultParams({+ allPlugins: [createMarketplaceDependency(0)] as Dependency[],+ })+ const { result } = renderHook(() => useInstallMultiState(params))++ await waitFor(() => {+ expect(result.current.plugins[0]?.version).toBe('2.0.0')+ })+ })++ it('should resolve marketplace dependency from organization and plugin fields', async () => {+ mockMarketplaceData = createMarketplaceApiData([0])++ const params = createDefaultParams({+ allPlugins: [+ {+ type: 'marketplace',+ value: {+ organization: 'test-org',+ plugin: 'plugin-0',+ version: '1.0.0',+ },+ } as GitHubItemAndMarketPlaceDependency,+ ] as Dependency[],+ })+ const { result } = renderHook(() => useInstallMultiState(params))++ await waitFor(() => {+ expect(result.current.plugins[0]).toBeDefined()+ expect(result.current.errorIndexes).not.toContain(0)+ })+ })})// ==================== Error Handling ====================describe('Error Handling', () => {+ it('should mark marketplace index as error when identifier misses plugin and version parts', async () => {+ const params = createDefaultParams({+ allPlugins: [+ {+ type: 'marketplace',+ value: {+ marketplace_plugin_unique_identifier: 'invalid-identifier',+ version: '1.0.0',+ },+ } as GitHubItemAndMarketPlaceDependency,+ ] as Dependency[],+ })+ const { result } = renderHook(() => useInstallMultiState(params))++ await waitFor(() => {+ expect(result.current.errorIndexes).toContain(0)+ })+ })++ it('should mark marketplace index as error when identifier has an empty plugin segment', async () => {+ const params = createDefaultParams({+ allPlugins: [+ {+ type: 'marketplace',+ value: {+ marketplace_plugin_unique_identifier: 'test-org/:1.0.0',+ version: '1.0.0',+ },+ } as GitHubItemAndMarketPlaceDependency,+ ] as Dependency[],+ })+ const { result } = renderHook(() => useInstallMultiState(params))++ await waitFor(() => {+ expect(result.current.errorIndexes).toContain(0)+ })+ })++ it('should mark marketplace index as error when identifier is missing', async () => {+ const params = createDefaultParams({+ allPlugins: [+ {+ type: 'marketplace',+ value: {+ version: '1.0.0',+ },+ } as GitHubItemAndMarketPlaceDependency,+ ] as Dependency[],+ })+ const { result } = renderHook(() => useInstallMultiState(params))++ await waitFor(() => {+ expect(result.current.errorIndexes).toContain(0)+ })+ })+it('should mark all marketplace indexes as errors on fetch failure', async () => {mockMarketplaceError = new Error('Fetch failed')@@ -303,6 +410,19 @@ describe('useInstallMultiState', () => {expect(result.current.errorIndexes).not.toContain(0)})})++ it('should ignore marketplace requests whose dsl index cannot be mapped', () => {+ const duplicatedMarketplaceDependency = createMarketplaceDependency(0)+ const allPlugins = [duplicatedMarketplaceDependency] as Dependency[]++ allPlugins.filter = vi.fn(() => [duplicatedMarketplaceDependency, duplicatedMarketplaceDependency]) as typeof allPlugins.filter++ const params = createDefaultParams({ allPlugins })+ const { result } = renderHook(() => useInstallMultiState(params))++ expect(result.current.plugins).toHaveLength(1)+ expect(result.current.errorIndexes).toEqual([])+ })})// ==================== Loaded All Data Notification ====================diff --git a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.tsindex b430d47afdd..86dd287c998 100644--- a/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts+++ b/web/app/components/plugins/install-plugin/install-bundle/steps/hooks/use-install-multi-state.ts@@ -14,14 +14,55 @@ type UseInstallMultiStateParams = {onLoadedAllPlugin: (installedInfo: Record<string, VersionInfo>) => void}+type MarketplacePluginInfo = {+ organization: string+ plugin: string+ version?: string+}++type MarketplaceRequest = {+ dslIndex: number+ dependency: GitHubItemAndMarketPlaceDependency+ info: MarketplacePluginInfo+}+export function getPluginKey(plugin: Plugin | undefined): string {return `${plugin?.org || plugin?.author}/${plugin?.name}`}-function parseMarketplaceIdentifier(identifier: string) {- const [orgPart, nameAndVersionPart] = identifier.split('@')[0].split('/')- const [name, version] = nameAndVersionPart.split(':')- return { organization: orgPart, plugin: name, version }+function parseMarketplaceIdentifier(identifier?: string): MarketplacePluginInfo | null {+ if (!identifier)+ return null++ const withoutHash = identifier.split('@')[0]+ const [organization, nameAndVersionPart] = withoutHash.split('/')+ if (!organization || !nameAndVersionPart)+ return null++ const [plugin, version] = nameAndVersionPart.split(':')+ if (!plugin)+ return null++ return { organization, plugin, version }+}++function getMarketplacePluginInfo(+ value: GitHubItemAndMarketPlaceDependency['value'],+): MarketplacePluginInfo | null {+ const parsedInfo = parseMarketplaceIdentifier(+ value.marketplace_plugin_unique_identifier || value.plugin_unique_identifier,+ )+ if (parsedInfo)+ return parsedInfo++ if (!value.organization || !value.plugin)+ return null++ return {+ organization: value.organization,+ plugin: value.plugin,+ version: value.version,+ }}function initPluginsFromDependencies(allPlugins: Dependency[]): (Plugin | undefined)[] {@@ -61,67 +102,73 @@ export function useInstallMultiState({}, [])}, [allPlugins])- // Marketplace data fetching: by unique identifier and by meta info+ const { marketplaceRequests, invalidMarketplaceIndexes } = useMemo(() => {+ return marketplacePlugins.reduce<{+ marketplaceRequests: MarketplaceRequest[]+ invalidMarketplaceIndexes: number[]+ }>((acc, dependency, marketplaceIndex) => {+ const dslIndex = marketPlaceInDSLIndex[marketplaceIndex]+ if (dslIndex === undefined)+ return acc++ const marketplaceInfo = getMarketplacePluginInfo(dependency.value)+ if (!marketplaceInfo)+ acc.invalidMarketplaceIndexes.push(dslIndex)+ else+ acc.marketplaceRequests.push({ dslIndex, dependency, info: marketplaceInfo })++ return acc+ }, {+ marketplaceRequests: [],+ invalidMarketplaceIndexes: [],+ })+ }, [marketPlaceInDSLIndex, marketplacePlugins])++ // Marketplace data fetching: by normalized marketplace infoconst {isLoading: isFetchingById,data: infoGetById,error: infoByIdError,} = useFetchPluginsInMarketPlaceByInfo(- marketplacePlugins.map(d => parseMarketplaceIdentifier(d.value.marketplace_plugin_unique_identifier!)),- )-- const {- isLoading: isFetchingByMeta,- data: infoByMeta,- error: infoByMetaError,- } = useFetchPluginsInMarketPlaceByInfo(- marketplacePlugins.map(d => d.value!),+ marketplaceRequests.map(request => request.info),)// Derive marketplace plugin data and errors from API responsesconst { marketplacePluginMap, marketplaceErrorIndexes } = useMemo(() => {const pluginMap = new Map<number, Plugin>()- const errorSet = new Set<number>()+ const errorSet = new Set<number>(invalidMarketplaceIndexes)// Process "by ID" responseif (!isFetchingById && infoGetById?.data.list) {- const sortedList = marketplacePlugins.map((d) => {- const id = d.value.marketplace_plugin_unique_identifier?.split(':')[0]- const retPluginInfo = infoGetById.data.list.find(item => item.plugin.plugin_id === id)?.plugin- return { ...retPluginInfo, from: d.type } as Plugin- })- marketPlaceInDSLIndex.forEach((index, i) => {- if (sortedList[i]) {- pluginMap.set(index, {- ...sortedList[i],- version: sortedList[i]!.version || sortedList[i]!.latest_version,- })- }- else { errorSet.add(index) }- })- }+ const payloads = infoGetById.data.list+ const pluginById = new Map(+ payloads.map(item => [item.plugin.plugin_id, item.plugin]),+ )++ marketplaceRequests.forEach((request, requestIndex) => {+ const pluginId = (+ request.dependency.value.marketplace_plugin_unique_identifier+ || request.dependency.value.plugin_unique_identifier+ )?.split(':')[0]+ const pluginInfo = (pluginId ? pluginById.get(pluginId) : undefined) || payloads[requestIndex]?.plugin- // Process "by meta" response (may overwrite "by ID" results)- if (!isFetchingByMeta && infoByMeta?.data.list) {- const payloads = infoByMeta.data.list- marketPlaceInDSLIndex.forEach((index, i) => {- if (payloads[i]) {- const item = payloads[i]- pluginMap.set(index, {- ...item.plugin,- plugin_id: item.version.unique_identifier,- } as Plugin)+ if (pluginInfo) {+ pluginMap.set(request.dslIndex, {+ ...pluginInfo,+ from: request.dependency.type,+ version: pluginInfo.version || pluginInfo.latest_version,+ })}- else { errorSet.add(index) }+ else { errorSet.add(request.dslIndex) }})}// Mark all marketplace indexes as errors on fetch failure- if (infoByMetaError || infoByIdError)+ if (infoByIdError)marketPlaceInDSLIndex.forEach(index => errorSet.add(index))return { marketplacePluginMap: pluginMap, marketplaceErrorIndexes: errorSet }- }, [isFetchingById, isFetchingByMeta, infoGetById, infoByMeta, infoByMetaError, infoByIdError, marketPlaceInDSLIndex, marketplacePlugins])+ }, [invalidMarketplaceIndexes, isFetchingById, infoGetById, infoByIdError, marketPlaceInDSLIndex, marketplaceRequests])// GitHub-fetched plugins and errors (imperative state from child callbacks)const [githubPluginMap, setGithubPluginMap] = useState<Map<number, Plugin>>(() => new Map())diff --git a/web/app/components/plugins/marketplace/__tests__/atoms.spec.tsx b/web/app/components/plugins/marketplace/__tests__/atoms.spec.tsxindex 2fae0f90d62..0a532f537dd 100644--- a/web/app/components/plugins/marketplace/__tests__/atoms.spec.tsx+++ b/web/app/components/plugins/marketplace/__tests__/atoms.spec.tsx@@ -3,6 +3,16 @@ import { act, renderHook } from '@testing-library/react'import { Provider as JotaiProvider } from 'jotai'import { beforeEach, describe, expect, it, vi } from 'vitest'import { createNuqsTestWrapper } from '@/test/nuqs-testing'+import {+ useActivePluginType,+ useFilterPluginTags,+ useMarketplaceMoreClick,+ useMarketplaceSearchMode,+ useMarketplaceSort,+ useMarketplaceSortValue,+ useSearchPluginText,+ useSetMarketplaceSort,+} from '../atoms'import { DEFAULT_SORT } from '../constants'const createWrapper = (searchParams = '') => {@@ -22,8 +32,7 @@ describe('Marketplace sort atoms', () => {vi.clearAllMocks()})- it('should return default sort value from useMarketplaceSort', async () => {- const { useMarketplaceSort } = await import('../atoms')+ it('should return default sort value from useMarketplaceSort', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useMarketplaceSort(), { wrapper })@@ -31,24 +40,28 @@ describe('Marketplace sort atoms', () => {expect(typeof result.current[1]).toBe('function')})- it('should return default sort value from useMarketplaceSortValue', async () => {- const { useMarketplaceSortValue } = await import('../atoms')+ it('should return default sort value from useMarketplaceSortValue', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useMarketplaceSortValue(), { wrapper })expect(result.current).toEqual(DEFAULT_SORT)})- it('should return setter from useSetMarketplaceSort', async () => {- const { useSetMarketplaceSort } = await import('../atoms')+ it('should return setter from useSetMarketplaceSort', () => {const { wrapper } = createWrapper()- const { result } = renderHook(() => useSetMarketplaceSort(), { wrapper })+ const { result } = renderHook(() => ({+ setSort: useSetMarketplaceSort(),+ sortValue: useMarketplaceSortValue(),+ }), { wrapper })- expect(typeof result.current).toBe('function')+ act(() => {+ result.current.setSort({ sortBy: 'created_at', sortOrder: 'ASC' })+ })++ expect(result.current.sortValue).toEqual({ sortBy: 'created_at', sortOrder: 'ASC' })})- it('should update sort value via useMarketplaceSort setter', async () => {- const { useMarketplaceSort } = await import('../atoms')+ it('should update sort value via useMarketplaceSort setter', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useMarketplaceSort(), { wrapper })@@ -65,8 +78,7 @@ describe('useSearchPluginText', () => {vi.clearAllMocks()})- it('should return empty string as default', async () => {- const { useSearchPluginText } = await import('../atoms')+ it('should return empty string as default', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useSearchPluginText(), { wrapper })@@ -74,8 +86,7 @@ describe('useSearchPluginText', () => {expect(typeof result.current[1]).toBe('function')})- it('should parse q from search params', async () => {- const { useSearchPluginText } = await import('../atoms')+ it('should parse q from search params', () => {const { wrapper } = createWrapper('?q=hello')const { result } = renderHook(() => useSearchPluginText(), { wrapper })@@ -83,16 +94,14 @@ describe('useSearchPluginText', () => {})it('should expose a setter function for search text', async () => {- const { useSearchPluginText } = await import('../atoms')const { wrapper } = createWrapper()const { result } = renderHook(() => useSearchPluginText(), { wrapper })- expect(typeof result.current[1]).toBe('function')-- // Calling the setter should not throwawait act(async () => {result.current[1]('search term')})++ expect(result.current[0]).toBe('search term')})})@@ -101,16 +110,14 @@ describe('useActivePluginType', () => {vi.clearAllMocks()})- it('should return "all" as default category', async () => {- const { useActivePluginType } = await import('../atoms')+ it('should return "all" as default category', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useActivePluginType(), { wrapper })expect(result.current[0]).toBe('all')})- it('should parse category from search params', async () => {- const { useActivePluginType } = await import('../atoms')+ it('should parse category from search params', () => {const { wrapper } = createWrapper('?category=tool')const { result } = renderHook(() => useActivePluginType(), { wrapper })@@ -123,16 +130,14 @@ describe('useFilterPluginTags', () => {vi.clearAllMocks()})- it('should return empty array as default', async () => {- const { useFilterPluginTags } = await import('../atoms')+ it('should return empty array as default', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useFilterPluginTags(), { wrapper })expect(result.current[0]).toEqual([])})- it('should parse tags from search params', async () => {- const { useFilterPluginTags } = await import('../atoms')+ it('should parse tags from search params', () => {const { wrapper } = createWrapper('?tags=search')const { result } = renderHook(() => useFilterPluginTags(), { wrapper })@@ -145,42 +150,35 @@ describe('useMarketplaceSearchMode', () => {vi.clearAllMocks()})- it('should return false when no search text, no tags, and category has collections (all)', async () => {- const { useMarketplaceSearchMode } = await import('../atoms')+ it('should return false when no search text, no tags, and category has collections (all)', () => {const { wrapper } = createWrapper('?category=all')const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })- // "all" is in PLUGIN_CATEGORY_WITH_COLLECTIONS, so search mode should be falseexpect(result.current).toBe(false)})- it('should return true when search text is present', async () => {- const { useMarketplaceSearchMode } = await import('../atoms')+ it('should return true when search text is present', () => {const { wrapper } = createWrapper('?q=test&category=all')const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })expect(result.current).toBe(true)})- it('should return true when tags are present', async () => {- const { useMarketplaceSearchMode } = await import('../atoms')+ it('should return true when tags are present', () => {const { wrapper } = createWrapper('?tags=search&category=all')const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })expect(result.current).toBe(true)})- it('should return true when category does not have collections (e.g. model)', async () => {- const { useMarketplaceSearchMode } = await import('../atoms')+ it('should return true when category does not have collections (e.g. model)', () => {const { wrapper } = createWrapper('?category=model')const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })- // "model" is NOT in PLUGIN_CATEGORY_WITH_COLLECTIONS, so search mode = trueexpect(result.current).toBe(true)})- it('should return false when category has collections (tool) and no search/tags', async () => {- const { useMarketplaceSearchMode } = await import('../atoms')+ it('should return false when category has collections (tool) and no search/tags', () => {const { wrapper } = createWrapper('?category=tool')const { result } = renderHook(() => useMarketplaceSearchMode(), { wrapper })@@ -193,27 +191,33 @@ describe('useMarketplaceMoreClick', () => {vi.clearAllMocks()})- it('should return a callback function', async () => {- const { useMarketplaceMoreClick } = await import('../atoms')+ it('should return a callback function', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => useMarketplaceMoreClick(), { wrapper })expect(typeof result.current).toBe('function')})- it('should do nothing when called with no params', async () => {- const { useMarketplaceMoreClick } = await import('../atoms')+ it('should do nothing when called with no params', () => {const { wrapper } = createWrapper()- const { result } = renderHook(() => useMarketplaceMoreClick(), { wrapper })+ const { result } = renderHook(() => ({+ handleMoreClick: useMarketplaceMoreClick(),+ sort: useMarketplaceSortValue(),+ searchText: useSearchPluginText()[0],+ }), { wrapper })++ const sortBefore = result.current.sort+ const searchTextBefore = result.current.searchText- // Should not throw when called with undefinedact(() => {- result.current(undefined)+ result.current.handleMoreClick(undefined)})++ expect(result.current.sort).toEqual(sortBefore)+ expect(result.current.searchText).toBe(searchTextBefore)})- it('should update search state when called with search params', async () => {- const { useMarketplaceMoreClick, useMarketplaceSortValue } = await import('../atoms')+ it('should update search state when called with search params', () => {const { wrapper } = createWrapper()const { result } = renderHook(() => ({@@ -229,17 +233,20 @@ describe('useMarketplaceMoreClick', () => {})})- // Sort should be updated via the jotai atomexpect(result.current.sort).toEqual({ sortBy: 'created_at', sortOrder: 'ASC' })})- it('should use defaults when search params fields are missing', async () => {- const { useMarketplaceMoreClick } = await import('../atoms')+ it('should use defaults when search params fields are missing', () => {const { wrapper } = createWrapper()- const { result } = renderHook(() => useMarketplaceMoreClick(), { wrapper })+ const { result } = renderHook(() => ({+ handleMoreClick: useMarketplaceMoreClick(),+ sort: useMarketplaceSortValue(),+ }), { wrapper })act(() => {- result.current({})+ result.current.handleMoreClick({})})++ expect(result.current.sort).toEqual(DEFAULT_SORT)})})diff --git a/web/app/components/plugins/marketplace/__tests__/plugin-type-switch.spec.tsx b/web/app/components/plugins/marketplace/__tests__/plugin-type-switch.spec.tsxindex 3e5e6a5e0aa..7cf3b10e25b 100644--- a/web/app/components/plugins/marketplace/__tests__/plugin-type-switch.spec.tsx+++ b/web/app/components/plugins/marketplace/__tests__/plugin-type-switch.spec.tsx@@ -74,31 +74,40 @@ describe('PluginTypeSwitch', () => {const { Wrapper } = createWrapper('?category=all')render(<PluginTypeSwitch />, { wrapper: Wrapper })- // Click on Models option — should not throw- expect(() => fireEvent.click(screen.getByText('Models'))).not.toThrow()+ fireEvent.click(screen.getByText('Models'))++ const modelsButton = screen.getByText('Models').closest('div')+ expect(modelsButton?.className).toContain('!bg-components-main-nav-nav-button-bg-active')})it('should handle clicking on category with collections (Tools)', () => {const { Wrapper } = createWrapper('?category=model')render(<PluginTypeSwitch />, { wrapper: Wrapper })- // Click on "Tools" which has collections → setSearchMode(null)- expect(() => fireEvent.click(screen.getByText('Tools'))).not.toThrow()+ fireEvent.click(screen.getByText('Tools'))++ const toolsButton = screen.getByText('Tools').closest('div')+ expect(toolsButton?.className).toContain('!bg-components-main-nav-nav-button-bg-active')})it('should handle clicking on category without collections (Models)', () => {const { Wrapper } = createWrapper('?category=all')render(<PluginTypeSwitch />, { wrapper: Wrapper })- // Click on "Models" which does NOT have collections → no setSearchMode call- expect(() => fireEvent.click(screen.getByText('Models'))).not.toThrow()+ fireEvent.click(screen.getByText('Models'))++ const modelsButton = screen.getByText('Models').closest('div')+ expect(modelsButton?.className).toContain('!bg-components-main-nav-nav-button-bg-active')})it('should handle clicking on bundles', () => {const { Wrapper } = createWrapper('?category=all')render(<PluginTypeSwitch />, { wrapper: Wrapper })- expect(() => fireEvent.click(screen.getByText('Bundles'))).not.toThrow()+ fireEvent.click(screen.getByText('Bundles'))++ const bundlesButton = screen.getByText('Bundles').closest('div')+ expect(bundlesButton?.className).toContain('!bg-components-main-nav-nav-button-bg-active')})it('should handle clicking on each category', () => {@@ -107,7 +116,10 @@ describe('PluginTypeSwitch', () => {const categories = ['All', 'Models', 'Tools', 'Data Sources', 'Triggers', 'Agents', 'Extensions', 'Bundles']categories.forEach((category) => {- expect(() => fireEvent.click(screen.getByText(category))).not.toThrow()+ fireEvent.click(screen.getByText(category))++ const button = screen.getByText(category).closest('div')+ expect(button?.className).toContain('!bg-components-main-nav-nav-button-bg-active')})})diff --git a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts b/web/app/components/plugins/marketplace/__tests__/utils.spec.tsindex ad0f899de45..92bed9be62c 100644--- a/web/app/components/plugins/marketplace/__tests__/utils.spec.ts+++ b/web/app/components/plugins/marketplace/__tests__/utils.spec.ts@@ -234,6 +234,24 @@ describe('getMarketplacePluginsByCollectionId', () => {expect(result).toEqual([])})+ it('should send an empty body when query is omitted', async () => {+ mockCollectionPlugins.mockResolvedValueOnce({+ data: { plugins: [] },+ })++ const { getMarketplacePluginsByCollectionId } = await import('../utils')+ await getMarketplacePluginsByCollectionId('test-collection')++ expect(mockCollectionPlugins).toHaveBeenCalledWith({+ params: {+ collectionId: 'test-collection',+ },+ body: {},+ }, expect.objectContaining({+ signal: undefined,+ }))+ })+it('should pass abort signal when provided', async () => {const mockPlugins = [{ type: 'plugin', org: 'test', name: 'plugin1' }]mockCollectionPlugins.mockResolvedValueOnce({diff --git a/web/app/components/plugins/marketplace/utils.ts b/web/app/components/plugins/marketplace/utils.tsindex 01f3c59284f..70522ff8833 100644--- a/web/app/components/plugins/marketplace/utils.ts+++ b/web/app/components/plugins/marketplace/utils.ts@@ -63,7 +63,7 @@ export const getMarketplacePluginsByCollectionId = async (params: {collectionId,},- body: query,+ body: query ?? {},}, {signal: options?.signal,})diff --git a/web/app/components/plugins/plugin-auth/authorized/index.tsx b/web/app/components/plugins/plugin-auth/authorized/index.tsxindex daee3131ad0..347d35e577e 100644--- a/web/app/components/plugins/plugin-auth/authorized/index.tsx+++ b/web/app/components/plugins/plugin-auth/authorized/index.tsx@@ -249,7 +249,7 @@ const Authorized = ({!!oAuthCredentials.length && (<div className="p-1"><div className={cn(- 'system-xs-medium px-3 pb-0.5 pt-1 text-text-tertiary',+ 'px-3 pb-0.5 pt-1 text-text-tertiary system-xs-medium',showItemSelectedIcon && 'pl-7',)}>@@ -279,7 +279,7 @@ const Authorized = ({!!apiKeyCredentials.length && (<div className="p-1"><div className={cn(- 'system-xs-medium px-3 pb-0.5 pt-1 text-text-tertiary',+ 'px-3 pb-0.5 pt-1 text-text-tertiary system-xs-medium',showItemSelectedIcon && 'pl-7',)}>diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsxindex a35fcec8be8..f0ec5b6c83e 100644--- a/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/detail-header.spec.tsx@@ -79,6 +79,10 @@ vi.mock('@/service/plugins', () => ({uninstallPlugin: mockUninstallPlugin,}))+vi.mock('@/service/use-plugins', () => ({+ useInvalidateCheckInstalled: () => vi.fn(),+}))+vi.mock('@/service/use-tools', () => ({useAllToolProviders: () => ({ data: [] }),useInvalidateAllToolProviders: () => mockInvalidateAllToolProviders,@@ -218,23 +222,6 @@ vi.mock('../../plugin-auth', () => ({PluginAuth: () => <div data-testid="plugin-auth" />,}))-// Mock Confirm component-vi.mock('@/app/components/base/confirm', () => ({- default: ({ isShow, onCancel, onConfirm, isLoading }: {- isShow: boolean- onCancel: () => void- onConfirm: () => void- isLoading: boolean- }) => isShow- ? (- <div data-testid="delete-confirm">- <button data-testid="confirm-cancel" onClick={onCancel}>Cancel</button>- <button data-testid="confirm-ok" onClick={onConfirm} disabled={isLoading}>Confirm</button>- </div>- )- : null,-}))-const createPluginDetail = (overrides: Partial<PluginDetail> = {}): PluginDetail => ({id: 'test-id',created_at: '2024-01-01',@@ -801,7 +788,7 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})})@@ -810,13 +797,13 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})- fireEvent.click(screen.getByTestId('confirm-cancel'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))await waitFor(() => {- expect(screen.queryByTestId('delete-confirm')).not.toBeInTheDocument()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()})})@@ -825,10 +812,10 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})- fireEvent.click(screen.getByTestId('confirm-ok'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))await waitFor(() => {expect(mockUninstallPlugin).toHaveBeenCalledWith('test-id')@@ -840,10 +827,10 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})- fireEvent.click(screen.getByTestId('confirm-ok'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))await waitFor(() => {expect(mockOnUpdate).toHaveBeenCalledWith(true)@@ -861,10 +848,10 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})- fireEvent.click(screen.getByTestId('confirm-ok'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))await waitFor(() => {expect(mockRefreshModelProviders).toHaveBeenCalled()@@ -876,10 +863,10 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})- fireEvent.click(screen.getByTestId('confirm-ok'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))await waitFor(() => {expect(mockInvalidateAllToolProviders).toHaveBeenCalled()@@ -891,10 +878,10 @@ describe('DetailHeader', () => {fireEvent.click(screen.getByTestId('remove-btn'))await waitFor(() => {- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})- fireEvent.click(screen.getByTestId('confirm-ok'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))await waitFor(() => {expect(amplitude.trackEvent).toHaveBeenCalledWith('plugin_uninstalled', expect.any(Object))diff --git a/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx b/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsxindex 7379927ffd6..b8d84763df6 100644--- a/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/__tests__/operation-dropdown.spec.tsx@@ -1,4 +1,6 @@+import type { ReactElement, ReactNode } from 'react'import { fireEvent, render, screen } from '@testing-library/react'+import { cloneElement } from 'react'import { beforeEach, describe, expect, it, vi } from 'vitest'import { PluginSource } from '../../types'import OperationDropdown from '../operation-dropdown'@@ -12,24 +14,22 @@ vi.mock('@/utils/classnames', () => ({cn: (...args: (string | undefined | false | null)[]) => args.filter(Boolean).join(' '),}))-vi.mock('@/app/components/base/action-button', () => ({- default: ({ children, className, onClick }: { children: React.ReactNode, className?: string, onClick?: () => void }) => (- <button data-testid="action-button" className={className} onClick={onClick}>- {children}- </button>+vi.mock('@/app/components/base/ui/dropdown-menu', () => ({+ DropdownMenu: ({ children, open }: { children: ReactNode, open: boolean }) => (+ <div data-testid="dropdown-menu" data-open={open}>{children}</div>),-}))--vi.mock('@/app/components/base/portal-to-follow-elem', () => ({- PortalToFollowElem: ({ children, open }: { children: React.ReactNode, open: boolean }) => (- <div data-testid="portal-elem" data-open={open}>{children}</div>+ DropdownMenuTrigger: ({ children, className }: { children: ReactNode, className?: string }) => (+ <button data-testid="dropdown-trigger" className={className}>{children}</button>),- PortalToFollowElemTrigger: ({ children, onClick }: { children: React.ReactNode, onClick: () => void }) => (- <div data-testid="portal-trigger" onClick={onClick}>{children}</div>- ),- PortalToFollowElemContent: ({ children, className }: { children: React.ReactNode, className?: string }) => (- <div data-testid="portal-content" className={className}>{children}</div>+ DropdownMenuContent: ({ children }: { children: ReactNode }) => (+ <div data-testid="dropdown-content">{children}</div>),+ DropdownMenuItem: ({ children, onClick, render, destructive }: { children: ReactNode, onClick?: () => void, render?: ReactElement, destructive?: boolean }) => {+ if (render)+ return cloneElement(render, { onClick, 'data-destructive': destructive } as Record<string, unknown>, children)+ return <div data-testid="dropdown-item" data-destructive={destructive} onClick={onClick}>{children}</div>+ },+ DropdownMenuSeparator: () => <hr data-testid="dropdown-separator" />,}))describe('OperationDropdown', () => {@@ -52,14 +52,13 @@ describe('OperationDropdown', () => {it('should render trigger button', () => {render(<OperationDropdown {...defaultProps} />)- expect(screen.getByTestId('portal-trigger')).toBeInTheDocument()- expect(screen.getByTestId('action-button')).toBeInTheDocument()+ expect(screen.getByTestId('dropdown-trigger')).toBeInTheDocument()})it('should render dropdown content', () => {render(<OperationDropdown {...defaultProps} />)- expect(screen.getByTestId('portal-content')).toBeInTheDocument()+ expect(screen.getByTestId('dropdown-content')).toBeInTheDocument()})it('should render info option for github source', () => {@@ -118,14 +117,10 @@ describe('OperationDropdown', () => {})describe('User Interactions', () => {- it('should toggle dropdown when trigger is clicked', () => {+ it('should render dropdown menu root', () => {render(<OperationDropdown {...defaultProps} />)- const trigger = screen.getByTestId('portal-trigger')- fireEvent.click(trigger)-- // The portal-elem should reflect the open state- expect(screen.getByTestId('portal-elem')).toBeInTheDocument()+ expect(screen.getByTestId('dropdown-menu')).toBeInTheDocument()})it('should call onInfo when info option is clicked', () => {@@ -174,7 +169,7 @@ describe('OperationDropdown', () => {const { unmount } = render(<OperationDropdown {...defaultProps} source={source} />,)- expect(screen.getByTestId('portal-elem')).toBeInTheDocument()+ expect(screen.getByTestId('dropdown-menu')).toBeInTheDocument()expect(screen.getByText('plugin.detailPanel.operation.remove')).toBeInTheDocument()unmount()})@@ -199,9 +194,7 @@ describe('OperationDropdown', () => {describe('Memoization', () => {it('should be wrapped with React.memo', () => {- // Verify the component is exported as a memo componentexpect(OperationDropdown).toBeDefined()- // React.memo wraps the component, so it should have $$typeofexpect((OperationDropdown as { $$typeof?: symbol }).$$typeof).toBeDefined()})})diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/components/__tests__/header-modals.spec.tsx b/web/app/components/plugins/plugin-detail-panel/detail-header/components/__tests__/header-modals.spec.tsxindex 843800c1907..004e6b94f04 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/components/__tests__/header-modals.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/components/__tests__/header-modals.spec.tsx@@ -9,24 +9,6 @@ vi.mock('@/context/i18n', () => ({useGetLanguage: () => 'en_US',}))-vi.mock('@/app/components/base/confirm', () => ({- default: ({ isShow, title, onCancel, onConfirm, isLoading }: {- isShow: boolean- title: string- onCancel: () => void- onConfirm: () => void- isLoading: boolean- }) => isShow- ? (- <div data-testid="delete-confirm">- <div data-testid="delete-title">{title}</div>- <button data-testid="confirm-cancel" onClick={onCancel}>Cancel</button>- <button data-testid="confirm-ok" onClick={onConfirm} disabled={isLoading}>Confirm</button>- </div>- )- : null,-}))-vi.mock('@/app/components/plugins/plugin-page/plugin-info', () => ({default: ({ repository, release, packageName, onHide }: {repository: string@@ -230,7 +212,7 @@ describe('HeaderModals', () => {/>,)- expect(screen.queryByTestId('delete-confirm')).not.toBeInTheDocument()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()})it('should render delete confirm when isShowDeleteConfirm is true', () => {@@ -247,7 +229,7 @@ describe('HeaderModals', () => {/>,)- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()})it('should show correct delete title', () => {@@ -264,7 +246,7 @@ describe('HeaderModals', () => {/>,)- expect(screen.getByTestId('delete-title')).toHaveTextContent('plugin.action.delete')+ expect(screen.getByRole('alertdialog')).toHaveTextContent('plugin.action.delete')})it('should call hideDeleteConfirm when cancel is clicked', () => {@@ -281,7 +263,7 @@ describe('HeaderModals', () => {/>,)- fireEvent.click(screen.getByTestId('confirm-cancel'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.cancel' }))expect(modalStates.hideDeleteConfirm).toHaveBeenCalled()})@@ -300,7 +282,7 @@ describe('HeaderModals', () => {/>,)- fireEvent.click(screen.getByTestId('confirm-ok'))+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.confirm' }))expect(mockOnDelete).toHaveBeenCalled()})@@ -319,7 +301,7 @@ describe('HeaderModals', () => {/>,)- expect(screen.getByTestId('confirm-ok')).toBeDisabled()+ expect(screen.getByRole('button', { name: /common\.operation\.confirm/ })).toBeDisabled()})})@@ -485,7 +467,7 @@ describe('HeaderModals', () => {)expect(screen.getByTestId('plugin-info')).toBeInTheDocument()- expect(screen.getByTestId('delete-confirm')).toBeInTheDocument()+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()expect(screen.getByTestId('update-modal')).toBeInTheDocument()})})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 62840b64e34..dea7b58d382 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@@ -4,7 +4,15 @@ import type { FC } from 'react'import type { PluginDetail } from '../../../types'import type { ModalStates, VersionTarget } from '../hooks'import { useTranslation } from 'react-i18next'-import Confirm from '@/app/components/base/confirm'+import {+ AlertDialog,+ AlertDialogActions,+ AlertDialogCancelButton,+ AlertDialogConfirmButton,+ AlertDialogContent,+ AlertDialogDescription,+ AlertDialogTitle,+} from '@/app/components/base/ui/alert-dialog'import PluginInfo from '@/app/components/plugins/plugin-page/plugin-info'import UpdateFromMarketplace from '@/app/components/plugins/update-plugin/from-market-place'import { useGetLanguage } from '@/context/i18n'@@ -50,7 +58,6 @@ const HeaderModals: FC<HeaderModalsProps> = ({return (<>- {/* Plugin Info Modal */}{isShowPluginInfo && (<PluginInforepository={isFromGitHub ? meta?.repo : ''}@@ -60,27 +67,35 @@ const HeaderModals: FC<HeaderModalsProps> = ({/>)}- {/* Delete Confirm Modal */}- {isShowDeleteConfirm && (- <Confirm- isShow- title={t(`${i18nPrefix}.delete`, { ns: 'plugin' })}- content={(- <div>+ <AlertDialog+ open={isShowDeleteConfirm}+ onOpenChange={(open) => {+ if (!open)+ hideDeleteConfirm()+ }}+ >+ <AlertDialogContent backdropProps={{ forceRender: true }}>+ <div className="flex flex-col gap-2 px-6 pb-4 pt-6">+ <AlertDialogTitle className="text-text-primary title-2xl-semi-bold">+ {t(`${i18nPrefix}.delete`, { ns: 'plugin' })}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full whitespace-pre-wrap break-words text-text-tertiary system-md-regular">{t(`${i18nPrefix}.deleteContentLeft`, { ns: 'plugin' })}- <span className="system-md-semibold">{label[locale]}</span>+ <span className="text-text-secondary system-md-semibold">{label[locale]}</span>{t(`${i18nPrefix}.deleteContentRight`, { ns: 'plugin' })}- <br />- </div>- )}- onCancel={hideDeleteConfirm}- onConfirm={onDelete}- isLoading={deleting}- isDisabled={deleting}- />- )}+ </AlertDialogDescription>+ </div>+ <AlertDialogActions>+ <AlertDialogCancelButton disabled={deleting}>+ {t('operation.cancel', { ns: 'common' })}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton loading={deleting} disabled={deleting} onClick={onDelete}>+ {t('operation.confirm', { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogActions>+ </AlertDialogContent>+ </AlertDialog>- {/* Update from Marketplace Modal */}{isShowUpdateModal && (<UpdateFromMarketplacepluginId={detail.plugin_id}diff --git a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.tsindex 15397ab6fcd..0fcec7f16b5 100644--- a/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts+++ b/web/app/components/plugins/plugin-detail-panel/detail-header/hooks/__tests__/use-plugin-operations.spec.ts@@ -15,6 +15,7 @@ type VersionPickerMock = {const {mockSetShowUpdatePluginModal,mockRefreshModelProviders,+ mockInvalidateCheckInstalled,mockInvalidateAllToolProviders,mockUninstallPlugin,mockFetchReleases,@@ -23,6 +24,7 @@ const {return {mockSetShowUpdatePluginModal: vi.fn(),mockRefreshModelProviders: vi.fn(),+ mockInvalidateCheckInstalled: vi.fn(),mockInvalidateAllToolProviders: vi.fn(),mockUninstallPlugin: vi.fn(() => Promise.resolve({ success: true })),mockFetchReleases: vi.fn(() => Promise.resolve([{ tag_name: 'v2.0.0' }])),@@ -46,6 +48,10 @@ vi.mock('@/service/plugins', () => ({uninstallPlugin: mockUninstallPlugin,}))+vi.mock('@/service/use-plugins', () => ({+ useInvalidateCheckInstalled: () => mockInvalidateCheckInstalled,+}))+vi.mock('@/service/use-tools', () => ({useInvalidateAllToolProviders: () => mockInvalidateAllToolProviders,}))@@ -178,6 +184,7 @@ describe('usePluginOperations', () => {result.current.handleUpdatedFromMarketplace()})+ expect(mockInvalidateCheckInstalled).toHaveBeenCalled()expect(mockOnUpdate).toHaveBeenCalled()expect(modalStates.hideUpdateModal).toHaveBeenCalled()})@@ -251,6 +258,32 @@ describe('usePluginOperations', () => {expect(mockSetShowUpdatePluginModal).toHaveBeenCalled()})+ it('should invalidate checkInstalled when GitHub update save callback fires', async () => {+ const detail = createPluginDetail({+ source: PluginSource.github,+ meta: { repo: 'owner/repo', version: 'v1.0.0', package: 'pkg' },+ })+ const { result } = renderHook(() =>+ usePluginOperations({+ detail,+ modalStates,+ versionPicker,+ isFromMarketplace: false,+ onUpdate: mockOnUpdate,+ }),+ )++ await act(async () => {+ await result.current.handleUpdate()+ })++ const firstCall = mockSetShowUpdatePluginModal.mock.calls.at(0)?.[0]+ firstCall?.onSaveCallback()++ expect(mockInvalidateCheckInstalled).toHaveBeenCalled()+ expect(mockOnUpdate).toHaveBeenCalled()+ })+it('should not show modal when no releases found', async () => {mockFetchReleases.mockResolvedValueOnce([])const detail = createPluginDetail({@@ -388,6 +421,7 @@ describe('usePluginOperations', () => {await result.current.handleDelete()})+ expect(mockInvalidateCheckInstalled).toHaveBeenCalled()expect(mockOnUpdate).toHaveBeenCalledWith(true)})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 f3f0296a888..bf6bb4aae65 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@@ -3,11 +3,13 @@import type { PluginDetail } from '../../../types'import type { ModalStates, VersionTarget } from './use-detail-header-state'import { useCallback } from 'react'+import { useTranslation } from 'react-i18next'import { trackEvent } from '@/app/components/base/amplitude'import Toast from '@/app/components/base/toast'import { useModalContext } from '@/context/modal-context'import { useProviderContext } from '@/context/provider-context'import { uninstallPlugin } from '@/service/plugins'+import { useInvalidateCheckInstalled } from '@/service/use-plugins'import { useInvalidateAllToolProviders } from '@/service/use-tools'import { useGitHubReleases } from '../../../install-plugin/hooks'import { PluginCategoryEnum, PluginSource } from '../../../types'@@ -36,13 +38,19 @@ export const usePluginOperations = ({isFromMarketplace,onUpdate,}: UsePluginOperationsParams): UsePluginOperationsReturn => {+ const { t } = useTranslation()const { checkForUpdates, fetchReleases } = useGitHubReleases()const { setShowUpdatePluginModal } = useModalContext()const { refreshModelProviders } = useProviderContext()+ const invalidateCheckInstalled = useInvalidateCheckInstalled()const invalidateAllToolProviders = useInvalidateAllToolProviders()const { id, meta, plugin_id } = detailconst { author, category, name } = detail.declaration || detail+ const handlePluginUpdated = useCallback((isDelete?: boolean) => {+ invalidateCheckInstalled()+ onUpdate?.(isDelete)+ }, [invalidateCheckInstalled, onUpdate])const handleUpdate = useCallback(async (isDowngrade?: boolean) => {if (isFromMarketplace) {@@ -71,7 +79,7 @@ export const usePluginOperations = ({if (needUpdate) {setShowUpdatePluginModal({onSaveCallback: () => {- onUpdate?.()+ handlePluginUpdated()},payload: {type: PluginSource.github,@@ -97,15 +105,15 @@ export const usePluginOperations = ({checkForUpdates,setShowUpdatePluginModal,detail,- onUpdate,+ handlePluginUpdated,modalStates,versionPicker,])const handleUpdatedFromMarketplace = useCallback(() => {- onUpdate?.()+ handlePluginUpdated()modalStates.hideUpdateModal()- }, [onUpdate, modalStates])+ }, [handlePluginUpdated, modalStates])const handleDelete = useCallback(async () => {modalStates.showDeleting()@@ -114,7 +122,11 @@ export const usePluginOperations = ({if (res.success) {modalStates.hideDeleteConfirm()- onUpdate?.(true)+ Toast.notify({+ type: 'success',+ message: t('action.deleteSuccess', { ns: 'plugin' }),+ })+ handlePluginUpdated(true)if (PluginCategoryEnum.model.includes(category))refreshModelProviders()@@ -130,7 +142,7 @@ export const usePluginOperations = ({plugin_id,name,modalStates,- onUpdate,+ handlePluginUpdated,refreshModelProviders,invalidateAllToolProviders,])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 8f265c5717f..111cb94a82b 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,16 +1,12 @@'use client'import type { PluginDetail } from '../../types'-import {- RiArrowLeftRightLine,- RiCloseLine,-} from '@remixicon/react'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import ActionButton from '@/app/components/base/action-button'import Badge from '@/app/components/base/badge'import Button from '@/app/components/base/button'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { AuthCategory, PluginAuth } from '@/app/components/plugins/plugin-auth'import OperationDropdown from '@/app/components/plugins/plugin-detail-panel/operation-dropdown'import PluginVersionPicker from '@/app/components/plugins/update-plugin/plugin-version-picker'@@ -180,7 +176,7 @@ const DetailHeader = ({text={(<><div>{isFromGitHub ? (meta?.version ?? version ?? '') : version}</div>- {isFromMarketplace && !isReadmeView && <RiArrowLeftRightLine className="ml-1 h-3 w-3 text-text-tertiary" />}+ {isFromMarketplace && !isReadmeView && <span aria-hidden className="i-ri-arrow-left-right-line ml-1 h-3 w-3 text-text-tertiary" />}</>)}hasRedCornerMark={hasNewVersion}@@ -191,25 +187,43 @@ const DetailHeader = ({{/* Auto Update Badge */}{isAutoUpgradeEnabled && !isReadmeView && (- <Tooltip popupContent={t('autoUpdate.nextUpdateTime', { ns: 'plugin', time: timeOfDayToDayjs(convertUTCDaySecondsToLocalSeconds(autoUpgradeInfo?.upgrade_time_of_day || 0, timezone!)).format('hh:mm A') })}>- <div>- <Badge className="mr-1 cursor-pointer px-1">- <AutoUpdateLine className="size-3" />- </Badge>- </div>+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={(+ <div>+ <Badge className="mr-1 cursor-pointer px-1">+ <AutoUpdateLine className="size-3" />+ </Badge>+ </div>+ )}+ />+ <TooltipContent>+ {t('autoUpdate.nextUpdateTime', { ns: 'plugin', time: timeOfDayToDayjs(convertUTCDaySecondsToLocalSeconds(autoUpgradeInfo?.upgrade_time_of_day || 0, timezone!)).format('hh:mm A') })}+ </TooltipContent></Tooltip>)}{/* Update Button */}{(hasNewVersion || isFromGitHub) && (- <Button- variant="secondary-accent"- size="small"- className="!h-5"- onClick={handleTriggerLatestUpdate}- >- {t('detailPanel.operation.update', { ns: 'plugin' })}- </Button>+ <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>)}</div>@@ -237,7 +251,7 @@ const DetailHeader = ({detailUrl={detailUrl}/><ActionButton onClick={onHide}>- <RiCloseLine className="h-4 w-4" />+ <span aria-hidden className="i-ri-close-line h-4 w-4" /></ActionButton></div>)}diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsxindex e5750d007b0..9b04a710e0b 100644--- a/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-detail-panel/model-selector/__tests__/index.spec.tsx@@ -9,40 +9,6 @@ import ModelParameterModal from '../index'// ==================== Mock Setup ====================-// Mock shared state for portal-let mockPortalOpenState = false--vi.mock('@/app/components/base/portal-to-follow-elem', () => ({- PortalToFollowElem: ({ children, open }: { children: React.ReactNode, open: boolean }) => {- mockPortalOpenState = open || false- return (- <div data-testid="portal-elem" data-open={open}>- {children}- </div>- )- },- PortalToFollowElemTrigger: ({ children, onClick, className }: { children: React.ReactNode, onClick: () => void, className?: string }) => (- <div data-testid="portal-trigger" onClick={onClick} className={className}>- {children}- </div>- ),- PortalToFollowElemContent: ({ children, className }: { children: React.ReactNode, className?: string }) => {- if (!mockPortalOpenState)- return null- return (- <div data-testid="portal-content" className={className}>- {children}- </div>- )- },-}))--vi.mock('@/app/components/base/toast', () => ({- default: {- notify: vi.fn(),- },-}))-// Mock provider contextconst mockProviderContextValue = {isAPIKeySet: true,@@ -87,6 +53,8 @@ vi.mock('@/utils/completion-params', () => ({fetchAndMergeValidCompletionParams: (...args: unknown[]) => mockFetchAndMergeValidCompletionParams(...args),}))+const mockToastNotify = vi.spyOn(Toast, 'notify')+// Mock child componentsvi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({default: ({ defaultModel, modelList, scopeFeatures, onSelect }: {@@ -108,30 +76,33 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/model-selec}))vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger', () => ({- default: ({ disabled, hasDeprecated, modelDisabled, currentProvider, currentModel, providerName, modelId, isInWorkflow }: {- disabled?: boolean- hasDeprecated?: boolean- modelDisabled?: boolean+ default: ({ currentProvider, currentModel, providerName, modelId, isInWorkflow }: {currentProvider?: ModelcurrentModel?: ModelItemproviderName?: stringmodelId?: stringisInWorkflow?: boolean- }) => (- <div- data-testid="trigger"- data-disabled={disabled}- data-has-deprecated={hasDeprecated}- data-model-disabled={modelDisabled}- data-provider={providerName}- data-model={modelId}- data-in-workflow={isInWorkflow}- data-has-current-provider={!!currentProvider}- data-has-current-model={!!currentModel}- >- Trigger- </div>- ),+ }) => {+ const hasDeprecated = !currentProvider || !currentModel+ const modelDisabled = currentModel?.status !== ModelStatusEnum.active+ const disabled = !mockProviderContextValue.isAPIKeySet || hasDeprecated || modelDisabled++ return (+ <div+ data-testid="trigger"+ data-disabled={disabled}+ data-has-deprecated={hasDeprecated}+ data-model-disabled={modelDisabled}+ data-provider={providerName}+ data-model={modelId}+ data-in-workflow={isInWorkflow}+ data-has-current-provider={!!currentProvider}+ data-has-current-model={!!currentModel}+ >+ Trigger+ </div>+ )+ },}))vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger', () => ({@@ -273,7 +244,7 @@ const setupModelLists = (config: {describe('ModelParameterModal', () => {beforeEach(() => {vi.clearAllMocks()- mockPortalOpenState = false+ mockToastNotify.mockReturnValue({})mockProviderContextValue.isAPIKeySet = truemockProviderContextValue.modelProviders = []setupModelLists()@@ -356,7 +327,7 @@ describe('ModelParameterModal', () => {render(<ModelParameterModal {...props} />)// Assert- expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()})it('should render model selector inside portal content when open', async () => {@@ -365,13 +336,12 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {- expect(screen.getByTestId('portal-content')).toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toBeInTheDocument()})- expect(screen.getByTestId('model-selector')).toBeInTheDocument()})})@@ -405,12 +375,11 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {- const content = screen.getByTestId('portal-content')- expect(content.querySelector('.custom-popup-class')).toBeInTheDocument()+ expect(document.querySelector('.custom-popup-class')).toBeInTheDocument()})})@@ -422,7 +391,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertconst selector = screen.getByTestId('model-selector')@@ -438,13 +407,13 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {- expect(screen.getByTestId('portal-content')).toBeInTheDocument()+ expect(screen.getByTestId('model-selector')).toBeInTheDocument()})})@@ -454,15 +423,15 @@ describe('ModelParameterModal', () => {// Actconst { rerender } = render(<ModelParameterModal {...props} />)- expect(screen.getByTestId('portal-elem')).toHaveAttribute('data-open', 'false')+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Force a re-render to ensure state is stablererender(<ModelParameterModal {...props} />)// Assert - open state should remain false due to readonly- expect(screen.getByTestId('portal-elem')).toHaveAttribute('data-open', 'false')+ expect(screen.queryByTestId('model-selector')).not.toBeInTheDocument()})})@@ -474,7 +443,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -489,7 +458,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -512,7 +481,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -530,7 +499,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -547,7 +516,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -564,7 +533,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -581,7 +550,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -598,7 +567,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -615,7 +584,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -632,7 +601,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -831,7 +800,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {fireEvent.click(screen.getByTestId('model-selector'))@@ -856,7 +825,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {fireEvent.click(screen.getByTestId('model-selector'))@@ -888,7 +857,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {fireEvent.click(screen.getByTestId('model-selector'))@@ -915,7 +884,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {fireEvent.click(screen.getByTestId('model-selector'))@@ -951,7 +920,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {const panel = screen.getByTestId('llm-params-panel')@@ -988,7 +957,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {const panel = screen.getByTestId('tts-params-panel')@@ -1025,7 +994,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -1051,7 +1020,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -1077,7 +1046,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -1104,12 +1073,11 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {- const content = screen.getByTestId('portal-content')- expect(content.querySelector('.bg-divider-subtle')).toBeInTheDocument()+ expect(document.querySelector('.bg-divider-subtle')).toBeInTheDocument()})})})@@ -1146,7 +1114,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -1185,7 +1153,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -1264,7 +1232,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assertawait waitFor(() => {@@ -1280,7 +1248,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assert - defaultModel is created with undefined providerawait waitFor(() => {@@ -1297,7 +1265,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assert - defaultModel is created with undefined modelawait waitFor(() => {@@ -1314,7 +1282,7 @@ describe('ModelParameterModal', () => {// Actrender(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))// Assert - when defaultModel is undefined, attribute is not set (returns null)await waitFor(() => {@@ -1350,14 +1318,13 @@ describe('ModelParameterModal', () => {// Actconst { rerender } = render(<ModelParameterModal {...props} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByTestId('trigger'))await waitFor(() => {expect(screen.getByTestId('model-selector')).toHaveAttribute('data-model-list-count', '1')})// Rerender with different scope- mockPortalOpenState = truererender(<ModelParameterModal {...props} scope={ModelTypeEnum.textEmbedding} />)// Assert@@ -1398,7 +1365,7 @@ describe('ModelParameterModal', () => {render(<ModelParameterModal {...props} />)// Assert- const trigger = screen.getByTestId('portal-trigger')+ const trigger = screen.getByTestId('trigger')expect(trigger).toBeInTheDocument()})})diff --git a/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx b/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsxindex 182b62496c1..761b7a12f4d 100644--- a/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx+++ b/web/app/components/plugins/plugin-detail-panel/model-selector/index.tsx@@ -10,12 +10,12 @@ import type {import type { TriggerProps } from '@/app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger'import { useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'-import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'import Toast from '@/app/components/base/toast'+import {+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'import { ModelStatusEnum, ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'import {useModelList,@@ -114,15 +114,8 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({}}, [scopedModelList, value?.provider, value?.model])- const hasDeprecated = useMemo(() => {- return !currentProvider || !currentModel- }, [currentModel, currentProvider])- const modelDisabled = useMemo(() => {- return currentModel?.status !== ModelStatusEnum.active- }, [currentModel?.status])- const disabled = useMemo(() => {- return !isAPIKeySet || hasDeprecated || modelDisabled- }, [hasDeprecated, isAPIKeySet, modelDisabled])+ const hasDeprecated = !currentProvider || !currentModel+ const disabled = !isAPIKeySet || hasDeprecated || currentModel?.status !== ModelStatusEnum.activeconst handleChangeModel = async ({ provider, model }: DefaultModel) => {const targetProvider = scopedModelList.find(modelItem => modelItem.provider === provider)@@ -187,99 +180,95 @@ const ModelParameterModal: FC<ModelParameterModalProps> = ({}return (- <PortalToFollowElem+ <Popoveropen={open}- onOpenChange={setOpen}- placement={isInWorkflow ? 'left' : 'bottom-end'}- offset={4}+ onOpenChange={(newOpen) => {+ if (readonly)+ return+ setOpen(newOpen)+ }}><div className="relative">- <PortalToFollowElemTrigger- onClick={() => {- if (readonly)- return- setOpen(v => !v)- }}- className="block"- >- {- renderTrigger- ? renderTrigger({- open,- disabled,- modelDisabled,- hasDeprecated,- currentProvider,- currentModel,- providerName: value?.provider,- modelId: value?.model,- })- : (isAgentStrategy- ? (- <AgentModelTrigger- disabled={disabled}- hasDeprecated={hasDeprecated}- currentProvider={currentProvider}- currentModel={currentModel}- providerName={value?.provider}- modelId={value?.model}- scope={scope}- />+ <PopoverTrigger+ render={(+ <button type="button" className="block w-full border-none bg-transparent p-0 text-left [color:inherit] [font:inherit]">+ {+ renderTrigger+ ? renderTrigger({+ open,+ currentProvider,+ currentModel,+ providerName: value?.provider,+ modelId: value?.model,+ })+ : (isAgentStrategy+ ? (+ <AgentModelTrigger+ disabled={disabled}+ hasDeprecated={hasDeprecated}+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName={value?.provider}+ modelId={value?.model}+ scope={scope}+ />+ )+ : (+ <Trigger+ isInWorkflow={isInWorkflow}+ currentProvider={currentProvider}+ currentModel={currentModel}+ providerName={value?.provider}+ modelId={value?.model}+ />+ ))- : (- <Trigger- disabled={disabled}- isInWorkflow={isInWorkflow}- modelDisabled={modelDisabled}- hasDeprecated={hasDeprecated}- currentProvider={currentProvider}- currentModel={currentModel}- providerName={value?.provider}- modelId={value?.model}- />- )- )- }- </PortalToFollowElemTrigger>- <PortalToFollowElemContent className={cn('z-50', portalToFollowElemContentClassName)}>- <div className={cn(popupClassName, 'w-[389px] rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg')}>- <div className={cn('max-h-[420px] overflow-y-auto p-4 pt-3')}>- <div className="relative">- <div className={cn('system-sm-semibold mb-1 flex h-6 items-center text-text-secondary')}>- {t('modelProvider.model', { ns: 'common' }).toLocaleUpperCase()}- </div>- <ModelSelector- defaultModel={(value?.provider || value?.model) ? { provider: value?.provider, model: value?.model } : undefined}- modelList={scopedModelList}- scopeFeatures={scopeFeatures}- onSelect={handleChangeModel}- />+ }+ </button>+ )}+ />+ <PopoverContent+ placement={isInWorkflow ? 'left' : 'bottom-end'}+ sideOffset={4}+ className={portalToFollowElemContentClassName}+ popupClassName={cn(popupClassName, 'w-[389px] rounded-2xl')}+ >+ <div className="max-h-[420px] overflow-y-auto p-4 pt-3">+ <div className="relative">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">+ {t('modelProvider.model', { ns: 'common' }).toLocaleUpperCase()}</div>- {(currentModel?.model_type === ModelTypeEnum.textGeneration || currentModel?.model_type === ModelTypeEnum.tts) && (- <div className="my-3 h-px bg-divider-subtle" />- )}- {currentModel?.model_type === ModelTypeEnum.textGeneration && (- <LLMParamsPanel- provider={value?.provider}- modelId={value?.model}- completionParams={value?.completion_params || {}}- onCompletionParamsChange={handleLLMParamsChange}- isAdvancedMode={isAdvancedMode}- />- )}- {currentModel?.model_type === ModelTypeEnum.tts && (- <TTSParamsPanel- currentModel={currentModel}- language={value?.language}- voice={value?.voice}- onChange={handleTTSParamsChange}- />- )}+ <ModelSelector+ defaultModel={(value?.provider || value?.model) ? { provider: value?.provider, model: value?.model } : undefined}+ modelList={scopedModelList}+ scopeFeatures={scopeFeatures}+ onSelect={handleChangeModel}+ /></div>+ {(currentModel?.model_type === ModelTypeEnum.textGeneration || currentModel?.model_type === ModelTypeEnum.tts) && (+ <div className="my-3 h-px bg-divider-subtle" />+ )}+ {currentModel?.model_type === ModelTypeEnum.textGeneration && (+ <LLMParamsPanel+ provider={value?.provider}+ modelId={value?.model}+ completionParams={value?.completion_params || {}}+ onCompletionParamsChange={handleLLMParamsChange}+ isAdvancedMode={isAdvancedMode}+ />+ )}+ {currentModel?.model_type === ModelTypeEnum.tts && (+ <TTSParamsPanel+ currentModel={currentModel}+ language={value?.language}+ voice={value?.voice}+ onChange={handleTTSParamsChange}+ />+ )}</div>- </PortalToFollowElemContent>+ </PopoverContent></div>- </PortalToFollowElem>+ </Popover>)}diff --git a/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx b/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsxindex c32dc9ac58a..b056f977935 100644--- a/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx+++ b/web/app/components/plugins/plugin-detail-panel/operation-dropdown.tsx@@ -1,16 +1,15 @@'use client'import type { FC } from 'react'-import { RiArrowRightUpLine, RiMoreFill } from '@remixicon/react'+import type { Placement } from '@/app/components/base/ui/placement'import * as React from 'react'-import { useCallback, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'-import ActionButton from '@/app/components/base/action-button'-// import Button from '@/app/components/base/button'import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/app/components/base/ui/dropdown-menu'import { useGlobalPublicStore } from '@/context/global-public-context'import { cn } from '@/utils/classnames'import { PluginSource } from '../types'@@ -21,6 +20,10 @@ type Props = {onCheckVersion: () => voidonRemove: () => voiddetailUrl: string+ placement?: Placement+ sideOffset?: number+ alignOffset?: number+ popupClassName?: string}const OperationDropdown: FC<Props> = ({@@ -29,83 +32,52 @@ const OperationDropdown: FC<Props> = ({onInfo,onCheckVersion,onRemove,+ placement = 'bottom-end',+ sideOffset = 4,+ alignOffset = 0,+ popupClassName,}) => {const { t } = useTranslation()- const [open, doSetOpen] = useState(false)- const openRef = useRef(open)- const setOpen = useCallback((v: boolean) => {- doSetOpen(v)- openRef.current = v- }, [doSetOpen])-- const handleTrigger = useCallback(() => {- setOpen(!openRef.current)- }, [setOpen])-+ const [open, setOpen] = React.useState(false)const { enable_marketplace } = useGlobalPublicStore(s => s.systemFeatures)return (- <PortalToFollowElem- open={open}- onOpenChange={setOpen}- placement="bottom-end"- offset={{- mainAxis: -12,- crossAxis: 36,- }}- >- <PortalToFollowElemTrigger onClick={handleTrigger}>- <div>- <ActionButton className={cn(open && 'bg-state-base-hover')}>- <RiMoreFill className="h-4 w-4" />- </ActionButton>- </div>- </PortalToFollowElemTrigger>- <PortalToFollowElemContent className="z-50">- <div className="w-[160px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg">- {source === PluginSource.github && (- <div- onClick={() => {- onInfo()- handleTrigger()- }}- className="system-md-regular cursor-pointer rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover"- >- {t('detailPanel.operation.info', { ns: 'plugin' })}- </div>- )}- {source === PluginSource.github && (- <div- onClick={() => {- onCheckVersion()- handleTrigger()- }}- className="system-md-regular cursor-pointer rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover"- >- {t('detailPanel.operation.checkUpdate', { ns: 'plugin' })}- </div>- )}- {(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (- <a href={detailUrl} target="_blank" className="system-md-regular flex cursor-pointer items-center rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-base-hover">- <span className="grow">{t('detailPanel.operation.viewDetail', { ns: 'plugin' })}</span>- <RiArrowRightUpLine className="h-3.5 w-3.5 shrink-0 text-text-tertiary" />- </a>- )}- {(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (- <div className="my-1 h-px bg-divider-subtle"></div>- )}- <div- onClick={() => {- onRemove()- handleTrigger()- }}- className="system-md-regular cursor-pointer rounded-lg px-3 py-1.5 text-text-secondary hover:bg-state-destructive-hover hover:text-text-destructive"- >- {t('detailPanel.operation.remove', { ns: 'plugin' })}- </div>- </div>- </PortalToFollowElemContent>- </PortalToFollowElem>+ <DropdownMenu open={open} onOpenChange={setOpen}>+ <DropdownMenuTrigger+ className={cn('action-btn action-btn-m', open && 'bg-state-base-hover')}+ >+ <span className="i-ri-more-fill h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent+ placement={placement}+ sideOffset={sideOffset}+ alignOffset={alignOffset}+ popupClassName={cn('w-auto min-w-[160px]', popupClassName)}+ >+ {source === PluginSource.github && (+ <DropdownMenuItem onClick={onInfo}>+ {t('detailPanel.operation.info', { ns: 'plugin' })}+ </DropdownMenuItem>+ )}+ {source === PluginSource.github && (+ <DropdownMenuItem onClick={onCheckVersion}>+ {t('detailPanel.operation.checkUpdate', { ns: 'plugin' })}+ </DropdownMenuItem>+ )}+ {(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (+ <DropdownMenuItem render={<a href={detailUrl} target="_blank" rel="noopener noreferrer" />}>+ <span className="grow">{t('detailPanel.operation.viewDetail', { ns: 'plugin' })}</span>+ <span className="i-ri-arrow-right-up-line h-3.5 w-3.5 shrink-0 text-text-tertiary" />+ </DropdownMenuItem>+ )}+ {(source === PluginSource.marketplace || source === PluginSource.github) && enable_marketplace && (+ <DropdownMenuSeparator />+ )}+ <DropdownMenuItem destructive onClick={onRemove}>+ {t('detailPanel.operation.remove', { ns: 'plugin' })}+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>)}export default React.memo(OperationDropdown)diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/__tests__/index.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/__tests__/index.spec.tsxindex 85db1066469..56992b377ff 100644--- a/web/app/components/plugins/plugin-page/plugin-tasks/__tests__/index.spec.tsx+++ b/web/app/components/plugins/plugin-page/plugin-tasks/__tests__/index.spec.tsx@@ -1,7 +1,7 @@import type { PluginStatus } from '@/app/components/plugins/types'import { fireEvent, render, screen, waitFor } from '@testing-library/react'import { beforeEach, describe, expect, it, vi } from 'vitest'-import { TaskStatus } from '@/app/components/plugins/types'+import { PluginSource, TaskStatus } from '@/app/components/plugins/types'// Import mocked modulesimport { useMutationClearTaskPlugin, usePluginTaskList } from '@/service/use-plugins'import PluginTaskList from '../components/plugin-task-list'@@ -30,6 +30,7 @@ vi.mock('@/context/i18n', () => ({const createMockPlugin = (overrides: Partial<PluginStatus> = {}): PluginStatus => ({plugin_unique_identifier: `plugin-${Math.random().toString(36).substr(2, 9)}`,plugin_id: 'test-plugin',+ source: PluginSource.marketplace,status: TaskStatus.running,message: '',icon: 'test-icon.png',@@ -438,7 +439,7 @@ describe('PluginTaskList Component', () => {// Translation key is returned as text in tests, multiple matches expected (title + status)expect(screen.getAllByText(/task\.installing/i).length).toBeGreaterThan(0)// Verify section container is rendered- expect(document.querySelector('.max-h-\\[200px\\]')).toBeInTheDocument()+ expect(document.querySelector('.max-h-\\[300px\\]')).toBeInTheDocument()})it('should render success plugins section when plugins exist', () => {@@ -467,7 +468,7 @@ describe('PluginTaskList Component', () => {)// All sections should be present- expect(document.querySelectorAll('.max-h-\\[200px\\]').length).toBe(3)+ expect(document.querySelectorAll('.max-h-\\[300px\\]').length).toBe(3)})})@@ -523,8 +524,9 @@ describe('PluginTaskList Component', () => {/>,)- // The individual clear button has the text 'operation.clear'- fireEvent.click(screen.getByRole('button', { name: /operation\.clear/i }))+ const closeButton = screen.getAllByRole('button')+ .find(btn => btn.querySelector('.i-ri-close-line'))!+ fireEvent.click(closeButton)expect(handleClearSingle).toHaveBeenCalledWith('task-123', 'error-plugin-1')})@@ -844,7 +846,7 @@ describe('PluginTasks Integration', () => {fireEvent.click(document.getElementById('plugin-task-trigger')!)// All sections should be visible- const sections = document.querySelectorAll('.max-h-\\[200px\\]')+ const sections = document.querySelectorAll('.max-h-\\[300px\\]')expect(sections.length).toBe(3)})})diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsxnew file mode 100644index 00000000000..fcae8d67169--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/error-plugin-item.spec.tsx@@ -0,0 +1,380 @@+import type { PluginInfoFromMarketPlace, PluginStatus } from '@/app/components/plugins/types'+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { PluginCategoryEnum, PluginSource, TaskStatus } from '@/app/components/plugins/types'+import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'++import ErrorPluginItem from '../error-plugin-item'++vi.mock('@/app/components/plugins/card/base/card-icon', () => ({+ default: ({ src, size }: { src: string, size: string }) => (+ <div data-testid="card-icon" data-src={src} data-size={size} />+ ),+}))++vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () => ({+ default: ({ uniqueIdentifier, onClose, onSuccess }: { uniqueIdentifier: string, onClose: () => void, onSuccess: () => void }) => (+ <div data-testid="install-modal" data-uid={uniqueIdentifier}>+ <button onClick={onClose}>Close modal</button>+ <button onClick={onSuccess}>Success</button>+ </div>+ ),+}))++vi.mock('@/service/plugins', () => ({+ fetchPluginInfoFromMarketPlace: vi.fn(),+}))++const mockFetch = vi.mocked(fetchPluginInfoFromMarketPlace)+const mockGetIconUrl = vi.fn((icon: string) => `https://icons/${icon}`)++function createMarketplaceResponse(identifier: string, version: string) {+ return {+ data: {+ plugin: {+ category: PluginCategoryEnum.tool,+ latest_package_identifier: identifier,+ latest_version: version,+ } satisfies PluginInfoFromMarketPlace,+ version: { version },+ },+ }+}++const createPlugin = (overrides: Partial<PluginStatus> = {}): PluginStatus => ({+ plugin_unique_identifier: 'org/plugin:1.0.0',+ plugin_id: 'org/plugin',+ source: PluginSource.marketplace,+ status: TaskStatus.failed,+ message: '',+ icon: 'icon.png',+ labels: { en_US: 'Test Plugin' } as PluginStatus['labels'],+ taskId: 'task-1',+ ...overrides,+})++describe('ErrorPluginItem', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Rendering', () => {+ it('should render plugin name', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText('Test Plugin')).toBeInTheDocument()+ })++ it('should render error status icon', () => {+ const { container } = render(+ <ErrorPluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(container.querySelector('.i-ri-error-warning-fill')).toBeInTheDocument()+ })++ it('should apply destructive text styling', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ const errorText = screen.getByText(/plugin\.task\.errorMsg\.marketplace/i)+ expect(errorText.closest('.text-text-destructive')).toBeInTheDocument()+ })+ })++ describe('Source detection and error messages', () => {+ it('should show marketplace error message for marketplace plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.marketplace, plugin_id: 'org/my-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.errorMsg\.marketplace/)).toBeInTheDocument()+ })++ it('should show github error message for github plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.github, plugin_id: 'https://github.com/user/repo' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.errorMsg\.github/)).toBeInTheDocument()+ })++ it('should show unknown error message for unknown source plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.local, plugin_id: 'local-only-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.errorMsg\.unknown/)).toBeInTheDocument()+ })++ it('should show plugin.message when available instead of default error', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ message: 'Custom error occurred' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText('Custom error occurred')).toBeInTheDocument()+ })+ })++ describe('Action buttons', () => {+ it('should show "Install from Marketplace" button for marketplace plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.marketplace, plugin_id: 'org/my-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.installFromMarketplace/)).toBeInTheDocument()+ })++ it('should show "Install from GitHub" button for github plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.github, plugin_id: 'https://github.com/user/repo' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.installFromGithub/)).toBeInTheDocument()+ })++ it('should not show action button for unknown source plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.local, plugin_id: 'local-only-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.queryByText(/plugin\.task\.installFrom/)).not.toBeInTheDocument()+ })++ it('should use source instead of plugin_id heuristics when deciding button text', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.github, plugin_id: 'org/my-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.installFromGithub/)).toBeInTheDocument()+ expect(screen.queryByText(/plugin\.task\.installFromMarketplace/)).not.toBeInTheDocument()+ })+ })++ describe('User Interactions', () => {+ it('should call onClear when clear button is clicked', () => {+ const onClear = vi.fn()+ render(+ <ErrorPluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={onClear}+ />,+ )++ // The clear button (×) is from PluginItem+ const buttons = screen.getAllByRole('button')+ const clearButton = buttons.find(btn => !btn.textContent?.includes('plugin.task'))+ fireEvent.click(clearButton!)++ expect(onClear).toHaveBeenCalledTimes(1)+ })++ it('should fetch marketplace info and show install modal on button click', async () => {+ mockFetch.mockResolvedValueOnce(createMarketplaceResponse('org/my-plugin:2.0.0', '2.0.0'))++ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.marketplace, plugin_id: 'org/my-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByText(/plugin\.task\.installFromMarketplace/))++ await waitFor(() => {+ expect(screen.getByTestId('install-modal')).toBeInTheDocument()+ })++ expect(mockFetch).toHaveBeenCalledWith({ org: 'org', name: 'my-plugin' })+ expect(screen.getByTestId('install-modal')).toHaveAttribute('data-uid', 'org/my-plugin:2.0.0')+ })++ it('should close install modal when onClose is called', async () => {+ mockFetch.mockResolvedValueOnce(createMarketplaceResponse('org/my-plugin:2.0.0', '2.0.0'))++ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.marketplace, plugin_id: 'org/my-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByText(/plugin\.task\.installFromMarketplace/))++ await waitFor(() => {+ expect(screen.getByTestId('install-modal')).toBeInTheDocument()+ })++ fireEvent.click(screen.getByText('Close modal'))++ expect(screen.queryByTestId('install-modal')).not.toBeInTheDocument()+ })++ it('should silently handle fetch failure', async () => {+ mockFetch.mockRejectedValueOnce(new Error('Network error'))++ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.marketplace, plugin_id: 'org/my-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ fireEvent.click(screen.getByText(/plugin\.task\.installFromMarketplace/))++ await waitFor(() => {+ expect(mockFetch).toHaveBeenCalled()+ })++ expect(screen.queryByTestId('install-modal')).not.toBeInTheDocument()+ })++ it('should not fetch when plugin_id has fewer than 2 parts', async () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.local, plugin_id: 'single-part' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ // Unknown source won't render the marketplace button, so nothing to click+ expect(screen.queryByText(/plugin\.task\.installFromMarketplace/)).not.toBeInTheDocument()+ expect(mockFetch).not.toHaveBeenCalled()+ })+ })++ describe('Edge Cases', () => {+ it('should render github action when source is github even if plugin_id looks like a URL', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.github, plugin_id: 'http://github.com/user/repo' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.installFromGithub/)).toBeInTheDocument()+ })++ it('should close install modal and clear the error item when onSuccess is called', async () => {+ mockFetch.mockResolvedValueOnce(createMarketplaceResponse('org/p:1.0.0', '1.0.0'))+ const onClear = vi.fn()++ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.marketplace, plugin_id: 'org/p' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={onClear}+ />,+ )++ fireEvent.click(screen.getByText(/plugin\.task\.installFromMarketplace/))++ await waitFor(() => {+ expect(screen.getByTestId('install-modal')).toBeInTheDocument()+ })++ fireEvent.click(screen.getByText('Success'))++ expect(screen.queryByTestId('install-modal')).not.toBeInTheDocument()+ expect(onClear).toHaveBeenCalledTimes(1)+ })++ it('should show unknown action state for local source even if id contains github keyword', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.local, plugin_id: 'my-github-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.queryByText(/plugin\.task\.installFromGithub/)).not.toBeInTheDocument()+ expect(screen.getByText(/plugin\.task\.errorMsg\.unknown/)).toBeInTheDocument()+ })++ it('should show unknown error message for debugging source plugins', () => {+ render(+ <ErrorPluginItem+ plugin={createPlugin({ source: PluginSource.debugging, plugin_id: 'remote-plugin' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ onClear={vi.fn()}+ />,+ )++ expect(screen.getByText(/plugin\.task\.errorMsg\.unknown/)).toBeInTheDocument()+ expect(screen.queryByText(/plugin\.task\.installFrom/)).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-item.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-item.spec.tsxnew file mode 100644index 00000000000..772e246e22c--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-item.spec.tsx@@ -0,0 +1,221 @@+import type { PluginStatus } from '@/app/components/plugins/types'+import { fireEvent, render, screen } from '@testing-library/react'+import { PluginSource, TaskStatus } from '@/app/components/plugins/types'+import PluginItem from '../plugin-item'++vi.mock('@/app/components/plugins/card/base/card-icon', () => ({+ default: ({ src, size }: { src: string, size: string }) => (+ <div data-testid="card-icon" data-src={src} data-size={size} />+ ),+}))++const mockGetIconUrl = vi.fn((icon: string) => `https://example.com/icons/${icon}`)++const createPlugin = (overrides: Partial<PluginStatus> = {}): PluginStatus => ({+ plugin_unique_identifier: 'org/plugin:1.0.0',+ plugin_id: 'org/plugin',+ source: PluginSource.marketplace,+ status: TaskStatus.running,+ message: '',+ icon: 'icon.png',+ labels: {+ en_US: 'Test Plugin',+ zh_Hans: '测试插件',+ } as PluginStatus['labels'],+ taskId: 'task-1',+ ...overrides,+})++describe('PluginItem', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Rendering', () => {+ it('should render plugin name based on language', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span data-testid="status-icon" />}+ statusText="Installing..."+ />,+ )++ expect(screen.getByText('Test Plugin')).toBeInTheDocument()+ })++ it('should render status text', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span data-testid="status-icon" />}+ statusText="Installing... please wait"+ />,+ )++ expect(screen.getByText('Installing... please wait')).toBeInTheDocument()+ })++ it('should render status icon', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span data-testid="status-icon" />}+ statusText="status"+ />,+ )++ expect(screen.getByTestId('status-icon')).toBeInTheDocument()+ })++ it('should anchor the status icon to the card icon wrapper', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span data-testid="status-icon" />}+ statusText="status"+ />,+ )++ const cardIcon = screen.getByTestId('card-icon')+ const iconWrapper = cardIcon.parentElement++ expect(iconWrapper).toHaveClass('relative', 'self-start')+ expect(screen.getByTestId('status-icon').parentElement).toHaveClass('absolute', '-bottom-0.5', '-right-0.5')+ })++ it('should pass icon url to CardIcon', () => {+ render(+ <PluginItem+ plugin={createPlugin({ icon: 'my-icon.svg' })}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="status"+ />,+ )++ expect(mockGetIconUrl).toHaveBeenCalledWith('my-icon.svg')+ const cardIcon = screen.getByTestId('card-icon')+ expect(cardIcon).toHaveAttribute('data-src', 'https://example.com/icons/my-icon.svg')+ expect(cardIcon).toHaveAttribute('data-size', 'small')+ })+ })++ describe('Props', () => {+ it('should apply custom statusClassName', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="done"+ statusClassName="text-text-success"+ />,+ )++ expect(screen.getByText('done').className).toContain('text-text-success')+ })++ it('should apply default statusClassName when not provided', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="done"+ />,+ )++ expect(screen.getByText('done').className).toContain('text-text-tertiary')+ })++ it('should render action when provided', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="status"+ action={<button>Install</button>}+ />,+ )++ expect(screen.getByRole('button', { name: /install/i })).toBeInTheDocument()+ })++ it('should not render action when not provided', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="status"+ />,+ )++ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('should render zh-Hans label when language is zh_Hans', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="zh_Hans"+ statusIcon={<span />}+ statusText="status"+ />,+ )++ expect(screen.getByText('测试插件')).toBeInTheDocument()+ })+ })++ describe('User Interactions', () => {+ it('should render clear button when onClear is provided', () => {+ const handleClear = vi.fn()+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="status"+ onClear={handleClear}+ />,+ )++ const clearButton = screen.getByRole('button')+ fireEvent.click(clearButton)++ expect(handleClear).toHaveBeenCalledTimes(1)+ })++ it('should not render clear button when onClear is not provided', () => {+ render(+ <PluginItem+ plugin={createPlugin()}+ getIconUrl={mockGetIconUrl}+ language="en_US"+ statusIcon={<span />}+ statusText="status"+ />,+ )++ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-section.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-section.spec.tsxnew file mode 100644index 00000000000..fb7429e9be5--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-section.spec.tsx@@ -0,0 +1,164 @@+import type { PluginStatus } from '@/app/components/plugins/types'+import { fireEvent, render, screen } from '@testing-library/react'+import { PluginSource, TaskStatus } from '@/app/components/plugins/types'+import PluginSection from '../plugin-section'++vi.mock('@/app/components/plugins/card/base/card-icon', () => ({+ default: ({ src, size }: { src: string, size: string }) => (+ <div data-testid="card-icon" data-src={src} data-size={size} />+ ),+}))++const mockGetIconUrl = vi.fn((icon: string) => `https://icons/${icon}`)++const createPlugin = (id: string, name: string, message = ''): PluginStatus => ({+ plugin_unique_identifier: id,+ plugin_id: `org/${name.toLowerCase()}`,+ source: PluginSource.marketplace,+ status: TaskStatus.running,+ message,+ icon: `${name.toLowerCase()}.png`,+ labels: { en_US: name, zh_Hans: name } as PluginStatus['labels'],+ taskId: 'task-1',+})++const defaultProps = {+ title: 'Installing plugins',+ count: 2,+ plugins: [createPlugin('p1', 'PluginA'), createPlugin('p2', 'PluginB')],+ getIconUrl: mockGetIconUrl,+ language: 'en_US' as const,+ statusIcon: <span data-testid="status-icon" />,+ defaultStatusText: 'Default status',+}++describe('PluginSection', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Rendering', () => {+ it('should render title and count', () => {+ render(<PluginSection {...defaultProps} />)++ expect(screen.getByText(/installing plugins/i)).toBeInTheDocument()+ expect(screen.getByText(/installing plugins/i).textContent).toContain('2')+ })++ it('should render all plugin items', () => {+ render(<PluginSection {...defaultProps} />)++ expect(screen.getByText('PluginA')).toBeInTheDocument()+ expect(screen.getByText('PluginB')).toBeInTheDocument()+ })++ it('should render status icons for each plugin', () => {+ render(<PluginSection {...defaultProps} />)++ expect(screen.getAllByTestId('status-icon')).toHaveLength(2)+ })+ })++ describe('Props', () => {+ it('should return null when plugins array is empty', () => {+ const { container } = render(+ <PluginSection {...defaultProps} plugins={[]} />,+ )++ expect(container.innerHTML).toBe('')+ })++ it('should use plugin.message as statusText when available', () => {+ const plugins = [createPlugin('p1', 'PluginA', 'Custom message')]+ render(<PluginSection {...defaultProps} plugins={plugins} count={1} />)++ expect(screen.getByText('Custom message')).toBeInTheDocument()+ })++ it('should use defaultStatusText when plugin has no message', () => {+ const plugins = [createPlugin('p1', 'PluginA', '')]+ render(<PluginSection {...defaultProps} plugins={plugins} count={1} />)++ expect(screen.getByText('Default status')).toBeInTheDocument()+ })++ it('should apply statusClassName to items', () => {+ const plugins = [createPlugin('p1', 'PluginA')]+ render(+ <PluginSection+ {...defaultProps}+ plugins={plugins}+ count={1}+ statusClassName="text-text-success"+ />,+ )++ expect(screen.getByText('Default status').className).toContain('text-text-success')+ })++ it('should render headerAction when provided', () => {+ render(+ <PluginSection+ {...defaultProps}+ headerAction={<button>Clear all</button>}+ />,+ )++ expect(screen.getByRole('button', { name: /clear all/i })).toBeInTheDocument()+ })++ it('should not render headerAction when not provided', () => {+ render(<PluginSection {...defaultProps} />)++ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })++ it('should render item actions via renderItemAction', () => {+ render(+ <PluginSection+ {...defaultProps}+ renderItemAction={plugin => (+ <button>{`Action ${plugin.labels.en_US}`}</button>+ )}+ />,+ )++ expect(screen.getByRole('button', { name: /action plugina/i })).toBeInTheDocument()+ expect(screen.getByRole('button', { name: /action pluginb/i })).toBeInTheDocument()+ })+ })++ describe('User Interactions', () => {+ it('should call onClearSingle with taskId and plugin identifier', () => {+ const onClearSingle = vi.fn()+ render(+ <PluginSection+ {...defaultProps}+ onClearSingle={onClearSingle}+ />,+ )++ // Clear buttons are rendered when onClearSingle is provided+ const clearButtons = screen.getAllByRole('button')+ fireEvent.click(clearButtons[0])++ expect(onClearSingle).toHaveBeenCalledWith('task-1', 'p1')+ })++ it('should not render clear buttons when onClearSingle is not provided', () => {+ render(<PluginSection {...defaultProps} />)++ expect(screen.queryByRole('button')).not.toBeInTheDocument()+ })+ })++ describe('Edge Cases', () => {+ it('should handle single plugin', () => {+ const plugins = [createPlugin('p1', 'Solo')]+ render(<PluginSection {...defaultProps} plugins={plugins} count={1} />)++ expect(screen.getByText('Solo')).toBeInTheDocument()+ expect(screen.getByText(/solo/i).closest('.max-h-\\[300px\\]')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-task-list.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-task-list.spec.tsxnew file mode 100644index 00000000000..2d0d3f7fd6f--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/plugin-task-list.spec.tsx@@ -0,0 +1,251 @@+import type { PluginStatus } from '@/app/components/plugins/types'+import { fireEvent, render, screen } from '@testing-library/react'+import { PluginSource, TaskStatus } from '@/app/components/plugins/types'+import PluginTaskList from '../plugin-task-list'++vi.mock('@/app/components/plugins/card/base/card-icon', () => ({+ default: ({ src, size }: { src: string, size: string }) => (+ <div data-testid="card-icon" data-src={src} data-size={size} />+ ),+}))++vi.mock('@/app/components/plugins/install-plugin/install-from-marketplace', () => ({+ default: () => <div data-testid="install-modal" />,+}))++vi.mock('@/service/plugins', () => ({+ fetchPluginInfoFromMarketPlace: vi.fn(),+}))++vi.mock('@/context/i18n', () => ({+ useGetLanguage: () => 'en_US',+}))++const mockGetIconUrl = vi.fn((icon: string) => `https://icons/${icon}`)++const createPlugin = (id: string, name: string, overrides: Partial<PluginStatus> = {}): PluginStatus => ({+ plugin_unique_identifier: id,+ plugin_id: `org/${name.toLowerCase()}`,+ source: PluginSource.marketplace,+ status: TaskStatus.running,+ message: '',+ icon: `${name.toLowerCase()}.png`,+ labels: { en_US: name } as PluginStatus['labels'],+ taskId: 'task-1',+ ...overrides,+})++const runningPlugins = [+ createPlugin('r1', 'OpenAI', { status: TaskStatus.running }),+ createPlugin('r2', 'Anthropic', { status: TaskStatus.running }),+]++const successPlugins = [+ createPlugin('s1', 'Google', { status: TaskStatus.success }),+]++const errorPlugins = [+ createPlugin('e1', 'DALLE', { status: TaskStatus.failed, plugin_id: 'org/dalle' }),+]++describe('PluginTaskList', () => {+ const defaultProps = {+ runningPlugins: [] as PluginStatus[],+ successPlugins: [] as PluginStatus[],+ errorPlugins: [] as PluginStatus[],+ getIconUrl: mockGetIconUrl,+ onClearAll: vi.fn(),+ onClearErrors: vi.fn(),+ onClearSingle: vi.fn(),+ }++ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Rendering', () => {+ it('should render empty container when no plugins', () => {+ const { container } = render(<PluginTaskList {...defaultProps} />)+ const wrapper = container.firstElementChild!+ expect(wrapper).toBeInTheDocument()+ expect(wrapper.children).toHaveLength(0)+ })++ it('should render running section when running plugins exist', () => {+ const { container } = render(<PluginTaskList {...defaultProps} runningPlugins={runningPlugins} />)++ // Header contains the title text+ const headers = container.querySelectorAll('.system-sm-semibold-uppercase')+ expect(headers).toHaveLength(1)+ expect(headers[0].textContent).toContain('plugin.task.installing')+ expect(screen.getByText('OpenAI')).toBeInTheDocument()+ expect(screen.getByText('Anthropic')).toBeInTheDocument()+ })++ it('should render success section when success plugins exist', () => {+ const { container } = render(<PluginTaskList {...defaultProps} successPlugins={successPlugins} />)++ const headers = container.querySelectorAll('.system-sm-semibold-uppercase')+ expect(headers).toHaveLength(1)+ expect(headers[0].textContent).toContain('plugin.task.installed')+ expect(screen.getByText('Google')).toBeInTheDocument()+ })++ it('should render error section when error plugins exist', () => {+ const { container } = render(<PluginTaskList {...defaultProps} errorPlugins={errorPlugins} />)++ const headers = container.querySelectorAll('.system-sm-semibold-uppercase')+ expect(headers).toHaveLength(1)+ expect(headers[0].textContent).toContain('plugin.task.installedError')+ expect(screen.getByText('DALLE')).toBeInTheDocument()+ })++ it('should render all three sections simultaneously', () => {+ render(+ <PluginTaskList+ {...defaultProps}+ runningPlugins={runningPlugins}+ successPlugins={successPlugins}+ errorPlugins={errorPlugins}+ />,+ )++ expect(screen.getByText('OpenAI')).toBeInTheDocument()+ expect(screen.getByText('Google')).toBeInTheDocument()+ expect(screen.getByText('DALLE')).toBeInTheDocument()+ })+ })++ describe('Clear actions', () => {+ it('should show Clear all button in success section', () => {+ render(<PluginTaskList {...defaultProps} successPlugins={successPlugins} />)++ const clearButtons = screen.getAllByText(/plugin\.task\.clearAll/)+ expect(clearButtons).toHaveLength(1)+ })++ it('should call onClearAll when success section Clear all is clicked', () => {+ const onClearAll = vi.fn()+ render(+ <PluginTaskList+ {...defaultProps}+ successPlugins={successPlugins}+ onClearAll={onClearAll}+ />,+ )++ fireEvent.click(screen.getByText(/plugin\.task\.clearAll/))+ expect(onClearAll).toHaveBeenCalledTimes(1)+ })++ it('should show Clear all button in error section', () => {+ render(<PluginTaskList {...defaultProps} errorPlugins={errorPlugins} />)++ const clearButtons = screen.getAllByText(/plugin\.task\.clearAll/)+ expect(clearButtons).toHaveLength(1)+ })++ it('should call onClearErrors when error section Clear all is clicked', () => {+ const onClearErrors = vi.fn()+ render(+ <PluginTaskList+ {...defaultProps}+ errorPlugins={errorPlugins}+ onClearErrors={onClearErrors}+ />,+ )++ fireEvent.click(screen.getByText(/plugin\.task\.clearAll/))+ expect(onClearErrors).toHaveBeenCalledTimes(1)+ })++ it('should call onClearSingle from success section clear button', () => {+ const onClearSingle = vi.fn()+ render(+ <PluginTaskList+ {...defaultProps}+ successPlugins={successPlugins}+ onClearSingle={onClearSingle}+ />,+ )++ // The × close button from PluginItem (rendered inside PluginSection)+ const closeButtons = screen.getAllByRole('button')+ const clearItemBtn = closeButtons.find(btn => !btn.textContent?.includes('plugin.task'))+ if (clearItemBtn)+ fireEvent.click(clearItemBtn)++ expect(onClearSingle).toHaveBeenCalledWith('task-1', 's1')+ })+ })++ describe('Running section', () => {+ it('should not render clear buttons for running plugins', () => {+ render(<PluginTaskList {...defaultProps} runningPlugins={runningPlugins} />)++ // Running section has no headerAction and no onClearSingle+ expect(screen.queryByText(/plugin\.task\.clearAll/)).not.toBeInTheDocument()+ })++ it('should show installing hint as status text', () => {+ render(<PluginTaskList {...defaultProps} runningPlugins={runningPlugins} />)++ // defaultStatusText is t('task.installingHint', { ns: 'plugin' })+ const hintTexts = screen.getAllByText(/plugin\.task\.installingHint/)+ expect(hintTexts.length).toBeGreaterThan(0)+ })+ })++ describe('Error section clear single', () => {+ it('should call onClearSingle from error item clear button', () => {+ const onClearSingle = vi.fn()+ render(+ <PluginTaskList+ {...defaultProps}+ errorPlugins={errorPlugins}+ onClearSingle={onClearSingle}+ />,+ )++ // Find the × close button inside error items (not the "Clear all" button)+ const allButtons = screen.getAllByRole('button')+ const clearItemBtn = allButtons.find(btn =>+ !btn.textContent?.includes('plugin.task')+ && !btn.textContent?.includes('installFrom'),+ )+ if (clearItemBtn)+ fireEvent.click(clearItemBtn)++ expect(onClearSingle).toHaveBeenCalledWith('task-1', 'e1')+ })+ })++ describe('Edge Cases', () => {+ it('should not render sections for empty plugin arrays', () => {+ const { container } = render(+ <PluginTaskList+ {...defaultProps}+ runningPlugins={[]}+ successPlugins={[]}+ errorPlugins={[]}+ />,+ )++ expect(container.querySelector('.w-\\[360px\\]')!.children).toHaveLength(0)+ })++ it('should render error section with multiple error plugins', () => {+ const multipleErrors = [+ createPlugin('e1', 'PluginA', { status: TaskStatus.failed, plugin_id: 'org/a' }),+ createPlugin('e2', 'PluginB', { status: TaskStatus.failed, plugin_id: 'https://github.com/b' }),+ createPlugin('e3', 'PluginC', { status: TaskStatus.failed, plugin_id: 'local-only' }),+ ]++ render(<PluginTaskList {...defaultProps} errorPlugins={multipleErrors} />)++ expect(screen.getByText('PluginA')).toBeInTheDocument()+ expect(screen.getByText('PluginB')).toBeInTheDocument()+ expect(screen.getByText('PluginC')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/task-status-indicator.spec.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/task-status-indicator.spec.tsxnew file mode 100644index 00000000000..4c1c8fb49d7--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/__tests__/task-status-indicator.spec.tsx@@ -0,0 +1,237 @@+import { fireEvent, render, screen } from '@testing-library/react'+import TaskStatusIndicator from '../task-status-indicator'++vi.mock('@/app/components/base/progress-bar/progress-circle', () => ({+ default: ({ percentage }: { percentage: number }) => (+ <div data-testid="progress-circle" data-percentage={percentage} />+ ),+}))++vi.mock('@/app/components/base/tooltip', () => ({+ default: ({ children, popupContent }: { children: React.ReactNode, popupContent: string }) => (+ <div data-testid="tooltip" data-tip={popupContent}>{children}</div>+ ),+}))++vi.mock('@/app/components/header/plugins-nav/downloading-icon', () => ({+ default: () => <span data-testid="downloading-icon" />,+}))++const defaultProps = {+ tip: 'Installing plugins',+ isInstalling: false,+ isInstallingWithSuccess: false,+ isInstallingWithError: false,+ isSuccess: false,+ isFailed: false,+ successPluginsLength: 0,+ runningPluginsLength: 0,+ totalPluginsLength: 0,+ onClick: vi.fn(),+}++describe('TaskStatusIndicator', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ describe('Rendering', () => {+ it('should render without crashing', () => {+ render(<TaskStatusIndicator {...defaultProps} />)+ expect(screen.getByTestId('tooltip')).toBeInTheDocument()+ })++ it('should pass tip to tooltip', () => {+ render(<TaskStatusIndicator {...defaultProps} tip="My tip" />)+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-tip', 'My tip')+ })++ it('should render install icon by default', () => {+ const { container } = render(<TaskStatusIndicator {...defaultProps} />)+ // RiInstallLine renders as svg+ expect(container.querySelector('svg')).toBeInTheDocument()+ expect(screen.queryByTestId('downloading-icon')).not.toBeInTheDocument()+ })+ })++ describe('Installing state', () => {+ it('should show downloading icon when isInstalling', () => {+ render(<TaskStatusIndicator {...defaultProps} isInstalling />)+ expect(screen.getByTestId('downloading-icon')).toBeInTheDocument()+ })++ it('should show downloading icon when isInstallingWithError', () => {+ render(<TaskStatusIndicator {...defaultProps} isInstallingWithError />)+ expect(screen.getByTestId('downloading-icon')).toBeInTheDocument()+ })++ it('should show progress circle when isInstalling', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isInstalling+ successPluginsLength={2}+ totalPluginsLength={5}+ />,+ )+ const progress = screen.getByTestId('progress-circle')+ expect(progress).toHaveAttribute('data-percentage', '40')+ })++ it('should show progress circle when isInstallingWithSuccess', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isInstallingWithSuccess+ successPluginsLength={3}+ totalPluginsLength={4}+ />,+ )+ const progress = screen.getByTestId('progress-circle')+ expect(progress).toHaveAttribute('data-percentage', '75')+ })++ it('should show error progress circle when isInstallingWithError', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isInstallingWithError+ runningPluginsLength={1}+ totalPluginsLength={3}+ />,+ )+ const progress = screen.getByTestId('progress-circle')+ expect(progress).toBeInTheDocument()+ })++ it('should handle zero totalPluginsLength without division error', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isInstalling+ totalPluginsLength={0}+ />,+ )+ const progress = screen.getByTestId('progress-circle')+ expect(progress).toHaveAttribute('data-percentage', '0')+ })+ })++ describe('Success state', () => {+ it('should show success icon when isSuccess', () => {+ const { container } = render(+ <TaskStatusIndicator+ {...defaultProps}+ isSuccess+ successPluginsLength={3}+ totalPluginsLength={3}+ />,+ )+ // RiCheckboxCircleFill is rendered as svg with text-text-success+ const successIcon = container.querySelector('.text-text-success')+ expect(successIcon).toBeInTheDocument()+ })++ it('should show success icon when successPlugins > 0 and no running plugins', () => {+ const { container } = render(+ <TaskStatusIndicator+ {...defaultProps}+ successPluginsLength={2}+ runningPluginsLength={0}+ totalPluginsLength={2}+ />,+ )+ const successIcon = container.querySelector('.text-text-success')+ expect(successIcon).toBeInTheDocument()+ })++ it('should not show success icon during installing states', () => {+ const { container } = render(+ <TaskStatusIndicator+ {...defaultProps}+ isInstalling+ successPluginsLength={1}+ runningPluginsLength={1}+ totalPluginsLength={2}+ />,+ )+ // Progress circle shown instead of success icon+ expect(screen.getByTestId('progress-circle')).toBeInTheDocument()+ expect(container.querySelector('.text-text-success')).not.toBeInTheDocument()+ })+ })++ describe('Failed state', () => {+ it('should show error icon when isFailed', () => {+ const { container } = render(+ <TaskStatusIndicator+ {...defaultProps}+ isFailed+ totalPluginsLength={2}+ />,+ )+ const errorIcon = container.querySelector('.text-text-destructive')+ expect(errorIcon).toBeInTheDocument()+ })++ it('should apply destructive styling when isFailed', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isFailed+ totalPluginsLength={1}+ />,+ )+ const button = document.getElementById('plugin-task-trigger')!+ expect(button.className).toContain('bg-state-destructive-hover')+ })++ it('should apply destructive styling when isInstallingWithError', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isInstallingWithError+ totalPluginsLength={2}+ />,+ )+ const button = document.getElementById('plugin-task-trigger')!+ expect(button.className).toContain('bg-state-destructive-hover')+ })+ })++ describe('User Interactions', () => {+ it('should call onClick when clicked', () => {+ const onClick = vi.fn()+ render(<TaskStatusIndicator {...defaultProps} onClick={onClick} />)++ const button = document.getElementById('plugin-task-trigger')!+ fireEvent.click(button)++ expect(onClick).toHaveBeenCalledTimes(1)+ })+ })++ describe('Edge Cases', () => {+ it('should apply cursor-pointer for interactive states', () => {+ render(+ <TaskStatusIndicator+ {...defaultProps}+ isSuccess+ successPluginsLength={1}+ totalPluginsLength={1}+ />,+ )+ const button = document.getElementById('plugin-task-trigger')!+ expect(button.className).toContain('cursor-pointer')+ })++ it('should not show any badge indicators when all flags are false', () => {+ render(<TaskStatusIndicator {...defaultProps} />)+ expect(screen.queryByTestId('progress-circle')).not.toBeInTheDocument()+ const button = document.getElementById('plugin-task-trigger')!+ // No success or error icons in the badge area+ expect(button.querySelector('.text-text-success')).not.toBeInTheDocument()+ expect(button.querySelector('.text-text-destructive')).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsxnew file mode 100644index 00000000000..a4f59be20cd--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/error-plugin-item.tsx@@ -0,0 +1,134 @@+import type { FC } from 'react'+import type { Plugin, PluginStatus } from '@/app/components/plugins/types'+import type { Locale } from '@/i18n-config'+import { useCallback, useState } from 'react'+import { useTranslation } from 'react-i18next'+import Button from '@/app/components/base/button'+import InstallFromMarketplace from '@/app/components/plugins/install-plugin/install-from-marketplace'+import { PluginSource } from '@/app/components/plugins/types'+import { fetchPluginInfoFromMarketPlace } from '@/service/plugins'+import PluginItem from './plugin-item'++type ErrorPluginItemProps = {+ plugin: PluginStatus+ getIconUrl: (icon: string) => string+ language: Locale+ onClear: () => void+}++const ErrorPluginItem: FC<ErrorPluginItemProps> = ({ plugin, getIconUrl, language, onClear }) => {+ const { t } = useTranslation()+ const source = plugin.source+ const [showInstallModal, setShowInstallModal] = useState(false)+ const [installPayload, setInstallPayload] = useState<{ uniqueIdentifier: string, manifest: Plugin } | null>(null)+ const [isFetching, setIsFetching] = useState(false)++ const handleInstallFromMarketplace = useCallback(async () => {+ const parts = plugin.plugin_id.split('/')+ if (parts.length < 2)+ return+ const [org, name] = parts+ setIsFetching(true)+ try {+ const response = await fetchPluginInfoFromMarketPlace({ org, name })+ const info = response.data.plugin+ const manifest: Plugin = {+ plugin_id: plugin.plugin_id,+ type: info.category as Plugin['type'],+ category: info.category,+ name,+ org,+ version: info.latest_version,+ latest_version: info.latest_version,+ latest_package_identifier: info.latest_package_identifier,+ label: plugin.labels,+ brief: {},+ description: {},+ icon: plugin.icon,+ verified: true,+ introduction: '',+ repository: '',+ install_count: 0,+ endpoint: { settings: [] },+ tags: [],+ badges: [],+ verification: { authorized_category: 'langgenius' },+ from: 'marketplace',+ }+ setInstallPayload({ uniqueIdentifier: info.latest_package_identifier, manifest })+ setShowInstallModal(true)+ }+ catch {+ // silently fail+ }+ finally {+ setIsFetching(false)+ }+ }, [plugin.plugin_id, plugin.labels, plugin.icon])++ const errorMsgKey: 'task.errorMsg.marketplace' | 'task.errorMsg.github' | 'task.errorMsg.unknown' = source === PluginSource.marketplace+ ? 'task.errorMsg.marketplace'+ : source === PluginSource.github+ ? 'task.errorMsg.github'+ : 'task.errorMsg.unknown'++ const errorMsg = t(errorMsgKey, { ns: 'plugin' })++ const renderAction = () => {+ if (source === PluginSource.marketplace) {+ return (+ <div className="pt-1">+ <Button variant="secondary" size="small" loading={isFetching} onClick={handleInstallFromMarketplace}>+ {t('task.installFromMarketplace', { ns: 'plugin' })}+ </Button>+ </div>+ )+ }+ if (source === PluginSource.github) {+ return (+ <div className="pt-1">+ <Button variant="secondary" size="small">+ {t('task.installFromGithub', { ns: 'plugin' })}+ </Button>+ </div>+ )+ }+ return undefined+ }++ return (+ <>+ <PluginItem+ plugin={plugin}+ getIconUrl={getIconUrl}+ language={language}+ statusIcon={(+ <span className="flex h-4 w-4 items-center justify-center rounded-full border border-components-panel-bg bg-components-panel-bg">+ <span className="i-ri-error-warning-fill h-4 w-4 text-text-destructive" />+ </span>+ )}+ statusText={(+ <span className="whitespace-pre-line">+ {plugin.message || errorMsg}+ </span>+ )}+ statusClassName="text-text-destructive"+ action={renderAction()}+ onClear={onClear}+ />+ {showInstallModal && installPayload && (+ <InstallFromMarketplace+ uniqueIdentifier={installPayload.uniqueIdentifier}+ manifest={installPayload.manifest}+ onClose={() => setShowInstallModal(false)}+ onSuccess={() => {+ setShowInstallModal(false)+ onClear()+ }}+ />+ )}+ </>+ )+}++export default ErrorPluginItemdiff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-item.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-item.tsxnew file mode 100644index 00000000000..2b88336522f--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-item.tsx@@ -0,0 +1,60 @@+import type { FC, ReactNode } from 'react'+import type { PluginStatus } from '@/app/components/plugins/types'+import type { Locale } from '@/i18n-config'+import CardIcon from '@/app/components/plugins/card/base/card-icon'++export type PluginItemProps = {+ plugin: PluginStatus+ getIconUrl: (icon: string) => string+ language: Locale+ statusIcon: ReactNode+ statusText: ReactNode+ statusClassName?: string+ action?: ReactNode+ onClear?: () => void+}++const PluginItem: FC<PluginItemProps> = ({+ plugin,+ getIconUrl,+ language,+ statusIcon,+ statusText,+ statusClassName,+ action,+ onClear,+}) => {+ return (+ <div className="group/item flex gap-1 rounded-lg p-2 hover:bg-state-base-hover">+ <div className="relative shrink-0 self-start">+ <CardIcon+ size="small"+ src={getIconUrl(plugin.icon)}+ />+ <div className="absolute -bottom-0.5 -right-0.5 z-10">+ {statusIcon}+ </div>+ </div>+ <div className="flex min-w-0 grow flex-col gap-0.5 px-1">+ <div className="truncate text-text-secondary system-sm-medium">+ {plugin.labels[language]}+ </div>+ <div className={`system-xs-regular ${statusClassName || 'text-text-tertiary'}`}>+ {statusText}+ </div>+ {action}+ </div>+ {onClear && (+ <button+ type="button"+ className="hidden h-6 w-6 shrink-0 items-center justify-center rounded-md hover:bg-state-base-hover-alt group-hover/item:flex"+ onClick={onClear}+ >+ <span className="i-ri-close-line h-4 w-4 text-text-tertiary" />+ </button>+ )}+ </div>+ )+}++export default PluginItemdiff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-section.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-section.tsxnew file mode 100644index 00000000000..5a6dfe00942--- /dev/null+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-section.tsx@@ -0,0 +1,67 @@+import type { FC, ReactNode } from 'react'+import type { PluginStatus } from '@/app/components/plugins/types'+import type { Locale } from '@/i18n-config'+import PluginItem from './plugin-item'++export type PluginSectionProps = {+ title: string+ count: number+ plugins: PluginStatus[]+ getIconUrl: (icon: string) => string+ language: Locale+ statusIcon: ReactNode+ defaultStatusText: ReactNode+ statusClassName?: string+ headerAction?: ReactNode+ renderItemAction?: (plugin: PluginStatus) => ReactNode+ onClearSingle?: (taskId: string, pluginId: string) => void+}++const PluginSection: FC<PluginSectionProps> = ({+ title,+ count,+ plugins,+ getIconUrl,+ language,+ statusIcon,+ defaultStatusText,+ statusClassName,+ headerAction,+ renderItemAction,+ onClearSingle,+}) => {+ if (plugins.length === 0)+ return null++ return (+ <>+ <div className="sticky top-0 flex h-7 items-center justify-between px-2 pt-1 text-text-secondary system-sm-semibold-uppercase">+ {title}+ {' '}+ (+ {count}+ )+ {headerAction}+ </div>+ <div className="max-h-[300px] overflow-y-auto">+ {plugins.map(plugin => (+ <PluginItem+ key={plugin.plugin_unique_identifier}+ plugin={plugin}+ getIconUrl={getIconUrl}+ language={language}+ statusIcon={statusIcon}+ statusText={plugin.message || defaultStatusText}+ statusClassName={statusClassName}+ action={renderItemAction?.(plugin)}+ onClear={onClearSingle+ ? () => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)+ : undefined}+ />+ ))}+ </div>+ </>+ )+}++export default PluginSectiondiff --git a/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-task-list.tsx b/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-task-list.tsxindex 5067a972048..728d3aceaba 100644--- a/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-task-list.tsx+++ b/web/app/components/plugins/plugin-page/plugin-tasks/components/plugin-task-list.tsx@@ -1,39 +1,10 @@-import type { FC, ReactNode } from 'react'+import type { FC } from 'react'import type { PluginStatus } from '@/app/components/plugins/types'-import type { Locale } from '@/i18n-config'-import {- RiCheckboxCircleFill,- RiErrorWarningFill,- RiLoaderLine,-} from '@remixicon/react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'-import CardIcon from '@/app/components/plugins/card/base/card-icon'import { useGetLanguage } from '@/context/i18n'--// Types-type PluginItemProps = {- plugin: PluginStatus- getIconUrl: (icon: string) => string- language: Locale- statusIcon: ReactNode- statusText: string- statusClassName?: string- action?: ReactNode-}--type PluginSectionProps = {- title: string- count: number- plugins: PluginStatus[]- getIconUrl: (icon: string) => string- language: Locale- statusIcon: ReactNode- defaultStatusText: string- statusClassName?: string- headerAction?: ReactNode- renderItemAction?: (plugin: PluginStatus) => ReactNode-}+import ErrorPluginItem from './error-plugin-item'+import PluginSection from './plugin-section'type PluginTaskListProps = {runningPlugins: PluginStatus[]@@ -45,83 +16,6 @@ type PluginTaskListProps = {onClearSingle: (taskId: string, pluginId: string) => void}-// Plugin Item Component-const PluginItem: FC<PluginItemProps> = ({- plugin,- getIconUrl,- language,- statusIcon,- statusText,- statusClassName,- action,-}) => {- return (- <div className="flex items-center rounded-lg p-2 hover:bg-state-base-hover">- <div className="relative mr-2 flex h-6 w-6 items-center justify-center rounded-md border-[0.5px] border-components-panel-border-subtle bg-background-default-dodge">- {statusIcon}- <CardIcon- size="tiny"- src={getIconUrl(plugin.icon)}- />- </div>- <div className="grow">- <div className="system-md-regular truncate text-text-secondary">- {plugin.labels[language]}- </div>- <div className={`system-xs-regular ${statusClassName || 'text-text-tertiary'}`}>- {statusText}- </div>- </div>- {action}- </div>- )-}--// Plugin Section Component-const PluginSection: FC<PluginSectionProps> = ({- title,- count,- plugins,- getIconUrl,- language,- statusIcon,- defaultStatusText,- statusClassName,- headerAction,- renderItemAction,-}) => {- if (plugins.length === 0)- return null-- return (- <>- <div className="system-sm-semibold-uppercase sticky top-0 flex h-7 items-center justify-between px-2 pt-1 text-text-secondary">- {title}- {' '}- (- {count}- )- {headerAction}- </div>- <div className="max-h-[200px] overflow-y-auto">- {plugins.map(plugin => (- <PluginItem- key={plugin.plugin_unique_identifier}- plugin={plugin}- getIconUrl={getIconUrl}- language={language}- statusIcon={statusIcon}- statusText={plugin.message || defaultStatusText}- statusClassName={statusClassName}- action={renderItemAction?.(plugin)}- />- ))}- </div>- </>- )-}--// Main Plugin Task List Componentconst PluginTaskList: FC<PluginTaskListProps> = ({runningPlugins,successPlugins,@@ -145,9 +39,9 @@ const PluginTaskList: FC<PluginTaskListProps> = ({getIconUrl={getIconUrl}language={language}statusIcon={- <RiLoaderLine className="absolute -bottom-0.5 -right-0.5 z-10 h-3 w-3 animate-spin text-text-accent" />+ <span className="i-ri-loader-2-line h-3.5 w-3.5 animate-spin text-text-accent" />}- defaultStatusText={t('task.installing', { ns: 'plugin' })}+ defaultStatusText={t('task.installingHint', { ns: 'plugin' })}/>)}@@ -160,7 +54,7 @@ const PluginTaskList: FC<PluginTaskListProps> = ({getIconUrl={getIconUrl}language={language}statusIcon={- <RiCheckboxCircleFill className="absolute -bottom-0.5 -right-0.5 z-10 h-3 w-3 text-text-success" />+ <span className="i-ri-checkbox-circle-fill h-3.5 w-3.5 text-text-success" />}defaultStatusText={t('task.installed', { ns: 'plugin' })}statusClassName="text-text-success"@@ -174,23 +68,15 @@ const PluginTaskList: FC<PluginTaskListProps> = ({{t('task.clearAll', { ns: 'plugin' })}</Button>)}+ onClearSingle={onClearSingle}/>)}{/* Error Plugins Section */}{errorPlugins.length > 0 && (- <PluginSection- title={t('task.installError', { ns: 'plugin', errorLength: errorPlugins.length })}- count={errorPlugins.length}- plugins={errorPlugins}- getIconUrl={getIconUrl}- language={language}- statusIcon={- <RiErrorWarningFill className="absolute -bottom-0.5 -right-0.5 z-10 h-3 w-3 text-text-destructive" />- }- defaultStatusText={t('task.installError', { ns: 'plugin', errorLength: errorPlugins.length })}- statusClassName="text-text-destructive break-all"- headerAction={(+ <>+ <div className="sticky top-0 flex h-7 items-center justify-between px-2 pt-1 text-text-secondary system-sm-semibold-uppercase">+ {t('task.installedError', { ns: 'plugin', errorLength: errorPlugins.length })}<ButtonclassName="shrink-0"size="small"@@ -199,18 +85,19 @@ const PluginTaskList: FC<PluginTaskListProps> = ({>{t('task.clearAll', { ns: 'plugin' })}</Button>- )}- renderItemAction={plugin => (- <Button- className="shrink-0"- size="small"- variant="ghost"- onClick={() => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)}- >- {t('operation.clear', { ns: 'common' })}- </Button>- )}- />+ </div>+ <div className="max-h-[300px] overflow-y-auto">+ {errorPlugins.map(plugin => (+ <ErrorPluginItem+ key={plugin.plugin_unique_identifier}+ plugin={plugin}+ getIconUrl={getIconUrl}+ language={language}+ onClear={() => onClearSingle(plugin.taskId, plugin.plugin_unique_identifier)}+ />+ ))}+ </div>+ </>)}</div>)diff --git a/web/app/components/plugins/plugin-page/plugins-panel.tsx b/web/app/components/plugins/plugin-page/plugins-panel.tsxindex d2ba8b23634..efa469f59dd 100644--- a/web/app/components/plugins/plugin-page/plugins-panel.tsx+++ b/web/app/components/plugins/plugin-page/plugins-panel.tsx@@ -9,8 +9,8 @@ import Loading from '@/app/components/base/loading'import PluginDetailPanel from '@/app/components/plugins/plugin-detail-panel'import { useGetLanguage } from '@/context/i18n'import { renderI18nObject } from '@/i18n-config'-import { useInstalledLatestVersion, useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'-import { PluginSource } from '../types'+import { useInstalledPluginList, useInvalidateInstalledPluginList } from '@/service/use-plugins'+import { usePluginsWithLatestVersion } from '../hooks'import { usePluginPageContext } from './context'import Empty from './empty'import FilterManagement from './filter-management'@@ -47,11 +47,7 @@ const PluginsPanel = () => {const filters = usePluginPageContext(v => v.filters) as FilterStateconst setFilters = usePluginPageContext(v => v.setFilters)const { data: pluginList, isLoading: isPluginListLoading, isFetching, isLastPage, loadNextPage } = useInstalledPluginList()- const { data: installedLatestVersion } = useInstalledLatestVersion(- pluginList?.plugins- .filter(plugin => plugin.source === PluginSource.marketplace)- .map(plugin => plugin.plugin_id) ?? [],- )+ const pluginListWithLatestVersion = usePluginsWithLatestVersion(pluginList?.plugins)const invalidateInstalledPluginList = useInvalidateInstalledPluginList()const currentPluginID = usePluginPageContext(v => v.currentPluginID)const setCurrentPluginID = usePluginPageContext(v => v.setCurrentPluginID)@@ -60,17 +56,6 @@ const PluginsPanel = () => {setFilters(filters)}, { wait: 500 })- const pluginListWithLatestVersion = useMemo(() => {- return pluginList?.plugins.map(plugin => ({- ...plugin,- latest_version: installedLatestVersion?.versions[plugin.plugin_id]?.version ?? '',- latest_unique_identifier: installedLatestVersion?.versions[plugin.plugin_id]?.unique_identifier ?? '',- status: installedLatestVersion?.versions[plugin.plugin_id]?.status ?? 'active',- deprecated_reason: installedLatestVersion?.versions[plugin.plugin_id]?.deprecated_reason ?? '',- alternative_plugin_id: installedLatestVersion?.versions[plugin.plugin_id]?.alternative_plugin_id ?? '',- })) || []- }, [pluginList, installedLatestVersion])-const filteredList = useMemo(() => {const { categories, searchQuery, tags } = filtersconst filteredList = pluginListWithLatestVersion.filter((plugin) => {diff --git a/web/app/components/plugins/types.ts b/web/app/components/plugins/types.tsindex 4aa0326cb4a..c5aa710be74 100644--- a/web/app/components/plugins/types.ts+++ b/web/app/components/plugins/types.ts@@ -432,6 +432,7 @@ export enum TaskStatus {export type PluginStatus = {plugin_unique_identifier: stringplugin_id: string+ source: PluginSourcestatus: TaskStatusmessage: stringicon: string@@ -508,6 +509,8 @@ export type GitHubItemAndMarketPlaceDependency = {type: 'github' | 'marketplace' | 'package'value: {repo?: string+ organization?: string // from bundle marketplace dependency+ plugin?: string // from bundle marketplace dependencyversion?: string // from app DSLpackage?: string // from app DSLrelease?: string // from local package. same to the versiondiff --git a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx b/web/app/components/plugins/update-plugin/__tests__/index.spec.tsxindex 8a4b2187b5d..73fb1328507 100644--- a/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx+++ b/web/app/components/plugins/update-plugin/__tests__/index.spec.tsx@@ -104,36 +104,6 @@ vi.mock('../../install-plugin/install-from-github', () => ({),}))-// Mock Portal components for PluginVersionPicker-let mockPortalOpen = false-vi.mock('@/app/components/base/portal-to-follow-elem', () => ({- PortalToFollowElem: ({ children, open, onOpenChange: _onOpenChange }: {- children: React.ReactNode- open: boolean- onOpenChange: (open: boolean) => void- }) => {- mockPortalOpen = open- return <div data-testid="portal-elem" data-open={open}>{children}</div>- },- PortalToFollowElemTrigger: ({ children, onClick, className }: {- children: React.ReactNode- onClick: () => void- className?: string- }) => (- <div data-testid="portal-trigger" onClick={onClick} className={className}>- {children}- </div>- ),- PortalToFollowElemContent: ({ children, className }: {- children: React.ReactNode- className?: string- }) => {- if (!mockPortalOpen)- return null- return <div data-testid="portal-content" className={className}>{children}</div>- },-}))-// Mock semvervi.mock('semver', () => ({lt: (v1: string, v2: string) => {@@ -247,7 +217,6 @@ const renderWithQueryClient = (ui: React.ReactElement) => {describe('update-plugin', () => {beforeEach(() => {vi.clearAllMocks()- mockPortalOpen = falsemockCheck.mockResolvedValue({ status: TaskStatus.success })})@@ -732,8 +701,8 @@ describe('update-plugin', () => {})})- it('should show error toast when task status is failed', async () => {- // Arrange - covers lines 99-100+ it('should reset loading state when task status check fails', async () => {+ // Arrangeconst mockToastNotify = vi.fn()vi.mocked(await import('../../../base/toast')).default.notify = mockToastNotify@@ -770,6 +739,53 @@ describe('update-plugin', () => {})// onSave should NOT be called when task failsexpect(onSave).not.toHaveBeenCalled()+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' })).toBeInTheDocument()+ })+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeInTheDocument()+ })++ it('should stop loading when upgrade API returns failed task directly', async () => {+ // Arrange+ const mockToastNotify = vi.fn()+ vi.mocked(await import('../../../base/toast')).default.notify = mockToastNotify++ mockUpdateFromMarketPlace.mockResolvedValue({+ task: {+ status: TaskStatus.failed,+ plugins: [{+ plugin_unique_identifier: 'test-target-id',+ status: TaskStatus.failed,+ message: 'failed to init environment',+ }],+ },+ })+ const onSave = vi.fn()+ const payload = createMockMarketPlacePayload()++ // Act+ renderWithQueryClient(+ <UpdateFromMarketplace+ payload={payload}+ onSave={onSave}+ onCancel={vi.fn()}+ />,+ )+ fireEvent.click(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' }))++ // Assert+ await waitFor(() => {+ expect(mockToastNotify).toHaveBeenCalledWith({+ type: 'error',+ message: 'failed to init environment',+ })+ })+ expect(mockCheck).not.toHaveBeenCalled()+ expect(onSave).not.toHaveBeenCalled()+ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'plugin.upgrade.upgrade' })).toBeInTheDocument()+ })+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeInTheDocument()})})@@ -946,7 +962,7 @@ describe('update-plugin', () => {onShowChange: vi.fn(),pluginID: 'test-plugin-id',currentVersion: '1.0.0',- trigger: <button>Select Version</button>,+ trigger: <span>Select Version</span>,onSelect: vi.fn(),}@@ -964,7 +980,7 @@ describe('update-plugin', () => {render(<PluginVersionPicker {...defaultProps} isShow={false} />)// Assert- expect(screen.queryByTestId('portal-content')).not.toBeInTheDocument()+ expect(screen.queryByText('plugin.detailPanel.switchVersion')).not.toBeInTheDocument()})it('should render version list when isShow is true', () => {@@ -972,7 +988,6 @@ describe('update-plugin', () => {render(<PluginVersionPicker {...defaultProps} isShow={true} />)// Assert- expect(screen.getByTestId('portal-content')).toBeInTheDocument()expect(screen.getByText('plugin.detailPanel.switchVersion')).toBeInTheDocument()})@@ -1002,7 +1017,7 @@ describe('update-plugin', () => {// Actrender(<PluginVersionPicker {...defaultProps} onShowChange={onShowChange} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByText('Select Version'))// Assertexpect(onShowChange).toHaveBeenCalledWith(true)@@ -1014,7 +1029,7 @@ describe('update-plugin', () => {// Actrender(<PluginVersionPicker {...defaultProps} disabled={true} onShowChange={onShowChange} />)- fireEvent.click(screen.getByTestId('portal-trigger'))+ fireEvent.click(screen.getByText('Select Version'))// Assertexpect(onShowChange).not.toHaveBeenCalled()@@ -1116,7 +1131,7 @@ describe('update-plugin', () => {)// Assert- expect(screen.getByTestId('portal-elem')).toBeInTheDocument()+ expect(screen.getByText('plugin.detailPanel.switchVersion')).toBeInTheDocument()})it('should support custom offset', () => {@@ -1125,12 +1140,13 @@ describe('update-plugin', () => {<PluginVersionPicker{...defaultProps}isShow={true}- offset={{ mainAxis: 10, crossAxis: 20 }}+ sideOffset={10}+ alignOffset={20}/>,)// Assert- expect(screen.getByTestId('portal-elem')).toBeInTheDocument()+ expect(screen.getByText('plugin.detailPanel.switchVersion')).toBeInTheDocument()})})@@ -1190,7 +1206,7 @@ describe('update-plugin', () => {onShowChange: vi.fn(),pluginID: 'test',currentVersion: '1.0.0',- trigger: <button>Select</button>,+ trigger: <span>Select</span>,onSelect: vi.fn(),}}/>,diff --git a/web/app/components/plugins/update-plugin/downgrade-warning.tsx b/web/app/components/plugins/update-plugin/downgrade-warning.tsxindex 4cf38d0ab2d..42348c929ad 100644--- a/web/app/components/plugins/update-plugin/downgrade-warning.tsx+++ b/web/app/components/plugins/update-plugin/downgrade-warning.tsx@@ -18,8 +18,8 @@ const DowngradeWarningModal = ({return (<><div className="flex flex-col items-start gap-2 self-stretch">- <div className="title-2xl-semi-bold text-text-primary">{t(`${i18nPrefix}.title`, { ns: 'plugin' })}</div>- <div className="system-md-regular text-text-secondary">+ <div className="text-text-primary title-2xl-semi-bold">{t(`${i18nPrefix}.title`, { ns: 'plugin' })}</div>+ <div className="text-text-secondary system-md-regular">{t(`${i18nPrefix}.description`, { ns: 'plugin' })}</div></div>diff --git a/web/app/components/plugins/update-plugin/from-market-place.tsx b/web/app/components/plugins/update-plugin/from-market-place.tsxindex 18c9ac2eafe..7564eae638b 100644--- a/web/app/components/plugins/update-plugin/from-market-place.tsx+++ b/web/app/components/plugins/update-plugin/from-market-place.tsx@@ -6,7 +6,12 @@ import { useCallback, useEffect, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'import Badge, { BadgeState } from '@/app/components/base/badge/index'import Button from '@/app/components/base/button'-import Modal from '@/app/components/base/modal'+import {+ Dialog,+ DialogCloseButton,+ DialogContent,+ DialogTitle,+} from '@/app/components/base/ui/dialog'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'@@ -28,6 +33,16 @@ type Props = {isShowDowngradeWarningModal?: boolean}+type FailedUpgradeResponse = {+ task?: {+ status?: TaskStatus+ plugins?: Array<{+ plugin_unique_identifier: string+ message: string+ }>+ }+}+enum UploadStep {notStarted = 'notStarted',upgrading = 'upgrading',@@ -78,13 +93,26 @@ const UpdatePluginModal: FC<Props> = ({if (uploadStep === UploadStep.notStarted) {setUploadStep(UploadStep.upgrading)try {+ const response = await updateFromMarketPlace({+ 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.notify({+ type: 'error',+ message: failedPlugin?.message || t('error', { ns: 'common' }),+ })+ setUploadStep(UploadStep.notStarted)+ return+ }+const {all_installed: isInstalled,task_id: taskId,- } = await updateFromMarketPlace({- original_plugin_unique_identifier: originalPackageInfo.id,- new_plugin_unique_identifier: targetPackageInfo.id,- })+ } = responseif (isInstalled) {onSave()@@ -97,6 +125,7 @@ const UpdatePluginModal: FC<Props> = ({})if (status === TaskStatus.failed) {Toast.notify({ type: 'error', message: error! })+ setUploadStep(UploadStep.notStarted)return}onSave()@@ -109,7 +138,7 @@ const UpdatePluginModal: FC<Props> = ({}if (uploadStep === UploadStep.installed)onSave()- }, [onSave, uploadStep, check, originalPackageInfo.id, handleRefetch, targetPackageInfo.id])+ }, [onSave, uploadStep, check, originalPackageInfo.id, handleRefetch, t, targetPackageInfo.id])const { mutateAsync } = useRemoveAutoUpgrade()const invalidateReferenceSettings = useInvalidateReferenceSettings()@@ -125,63 +154,65 @@ const UpdatePluginModal: FC<Props> = ({const doShowDowngradeWarningModal = isShowDowngradeWarningModal && uploadStep === UploadStep.notStartedreturn (- <Modal- isShow={true}- onClose={onCancel}- className={cn('min-w-[560px]', doShowDowngradeWarningModal && 'min-w-[640px]')}- closable- title={!doShowDowngradeWarningModal && t(`${i18nPrefix}.${uploadStep === UploadStep.installed ? 'successfulTitle' : 'title'}`, { ns: 'plugin' })}- >- {doShowDowngradeWarningModal && (- <DowngradeWarningModal- onCancel={onCancel}- onJustDowngrade={handleConfirm}- onExcludeAndDowngrade={handleExcludeAndDownload}- />- )}- {!doShowDowngradeWarningModal && (- <>- <div className="system-md-regular mb-2 mt-3 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" state={BadgeState.Warning}>- {`${originalPackageInfo.payload.version} -> ${targetPackageInfo.version}`}- </Badge>- </>+ <Dialog open onOpenChange={() => onCancel()}>+ <DialogContent+ backdropProps={{ forceRender: true }}+ className={cn('min-w-[560px]', doShowDowngradeWarningModal && 'min-w-[640px]')}+ >+ <DialogCloseButton />+ {doShowDowngradeWarningModal && (+ <DowngradeWarningModal+ onCancel={onCancel}+ onJustDowngrade={handleConfirm}+ onExcludeAndDowngrade={handleExcludeAndDownload}+ />+ )}+ {!doShowDowngradeWarningModal && (+ <>+ <DialogTitle className="text-text-primary title-2xl-semi-bold">+ {t(`${i18nPrefix}.${uploadStep === UploadStep.installed ? 'successfulTitle' : 'title'}`, { ns: 'plugin' })}+ </DialogTitle>+ <div className="mb-2 mt-3 text-text-secondary system-md-regular">+ {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" state={BadgeState.Warning}>+ {`${originalPackageInfo.payload.version} -> ${targetPackageInfo.version}`}+ </Badge>+ </>+ )}+ />+ </div>+ <div className="flex items-center justify-end gap-2 self-stretch pt-5">+ {uploadStep === UploadStep.notStarted && (+ <Button+ onClick={handleCancel}+ >+ {t('operation.cancel', { ns: 'common' })}+ </Button>)}- />- </div>- <div className="flex items-center justify-end gap-2 self-stretch pt-5">- {uploadStep === UploadStep.notStarted && (<Button- onClick={handleCancel}+ variant="primary"+ loading={uploadStep === UploadStep.upgrading}+ onClick={handleConfirm}+ disabled={uploadStep === UploadStep.upgrading}>- {t('operation.cancel', { ns: 'common' })}+ {configBtnText}</Button>- )}- <Button- variant="primary"- loading={uploadStep === UploadStep.upgrading}- onClick={handleConfirm}- disabled={uploadStep === UploadStep.upgrading}- >- {configBtnText}- </Button>- </div>- </>- )}-- </Modal>+ </div>+ </>+ )}+ </DialogContent>+ </Dialog>)}export default React.memo(UpdatePluginModal)diff --git a/web/app/components/plugins/update-plugin/plugin-version-picker.tsx b/web/app/components/plugins/update-plugin/plugin-version-picker.tsxindex 8327e4eabdc..d662c2b6e0e 100644--- a/web/app/components/plugins/update-plugin/plugin-version-picker.tsx+++ b/web/app/components/plugins/update-plugin/plugin-version-picker.tsx@@ -1,19 +1,16 @@'use client'-import type {- OffsetOptions,- Placement,-} from '@floating-ui/react'import type { FC } from 'react'+import type { Placement } from '@/app/components/base/ui/placement'import * as React from 'react'import { useCallback } from 'react'import { useTranslation } from 'react-i18next'import { lt } from 'semver'import Badge from '@/app/components/base/badge'import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'+ Popover,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'import useTimestamp from '@/hooks/use-timestamp'import { useVersionListOfPlugin } from '@/service/use-plugins'import { cn } from '@/utils/classnames'@@ -26,7 +23,8 @@ type Props = {currentVersion: stringtrigger: React.ReactNodeplacement?: Placement- offset?: OffsetOptions+ sideOffset?: number+ alignOffset?: numberonSelect: ({version,unique_identifier,@@ -46,22 +44,14 @@ const PluginVersionPicker: FC<Props> = ({currentVersion,trigger,placement = 'bottom-start',- offset = {- mainAxis: 4,- crossAxis: -16,- },+ sideOffset = 4,+ alignOffset = -16,onSelect,}) => {const { t } = useTranslation()const format = t('dateTimeFormat', { ns: 'appLog' }).split(' ')[0]const { formatDate } = useTimestamp()- const handleTriggerClick = () => {- if (disabled)- return- onShowChange(true)- }-const { data: res } = useVersionListOfPlugin(pluginID)const handleSelect = useCallback(({ version, unique_identifier, isDowngrade }: {@@ -76,49 +66,53 @@ const PluginVersionPicker: FC<Props> = ({}, [currentVersion, onSelect, onShowChange])return (- <PortalToFollowElem- placement={placement}- offset={offset}+ <Popoveropen={isShow}- onOpenChange={onShowChange}+ onOpenChange={(open) => {+ if (!disabled)+ onShowChange(open)+ }}>- <PortalToFollowElemTrigger+ <PopoverTrigger+ disabled={disabled}className={cn('inline-flex cursor-pointer items-center', disabled && 'cursor-default')}- onClick={handleTriggerClick}>{trigger}- </PortalToFollowElemTrigger>+ </PopoverTrigger>- <PortalToFollowElemContent className="z-[1000]">- <div className="relative w-[209px] rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur p-1 shadow-lg backdrop-blur-sm">- <div className="system-xs-medium-uppercase px-3 pb-0.5 pt-1 text-text-tertiary">- {t('detailPanel.switchVersion', { ns: 'plugin' })}- </div>- <div className="relative">- {res?.data.versions.map(version => (- <div- key={version.unique_identifier}- className={cn(- 'flex h-7 cursor-pointer items-center gap-1 rounded-lg px-3 py-1 hover:bg-state-base-hover',- currentVersion === version.version && 'cursor-default opacity-30 hover:bg-transparent',- )}- onClick={() => handleSelect({- version: version.version,- unique_identifier: version.unique_identifier,- isDowngrade: lt(version.version, currentVersion),- })}- >- <div className="flex grow items-center">- <div className="system-sm-medium text-text-secondary">{version.version}</div>- {currentVersion === version.version && <Badge className="ml-1" text="CURRENT" />}- </div>- <div className="system-xs-regular shrink-0 text-text-tertiary">{formatDate(version.created_at, format)}</div>+ <PopoverContent+ placement={placement}+ sideOffset={sideOffset}+ alignOffset={alignOffset}+ popupClassName="relative w-[209px] bg-components-panel-bg-blur p-1 backdrop-blur-sm"+ >+ <div className="px-3 pb-0.5 pt-1 text-text-tertiary system-xs-medium-uppercase">+ {t('detailPanel.switchVersion', { ns: 'plugin' })}+ </div>+ <div className="relative max-h-[224px] overflow-y-auto">+ {res?.data.versions.map(version => (+ <div+ key={version.unique_identifier}+ className={cn(+ 'flex h-7 cursor-pointer items-center gap-1 rounded-lg px-3 py-1 hover:bg-state-base-hover',+ currentVersion === version.version && 'cursor-default opacity-30 hover:bg-transparent',+ )}+ onClick={() => handleSelect({+ version: version.version,+ unique_identifier: version.unique_identifier,+ isDowngrade: lt(version.version, currentVersion),+ })}+ >+ <div className="flex grow items-center">+ <div className="text-text-secondary system-sm-medium">{version.version}</div>+ {currentVersion === version.version && <Badge className="ml-1" text="CURRENT" />}</div>- ))}- </div>+ <div className="shrink-0 text-text-tertiary system-xs-regular">{formatDate(version.created_at, format)}</div>+ </div>+ ))}</div>- </PortalToFollowElemContent>- </PortalToFollowElem>+ </PopoverContent>+ </Popover>)}diff --git a/web/app/components/plugins/utils.ts b/web/app/components/plugins/utils.tsindex e68ad0d9593..1cf6dead975 100644--- a/web/app/components/plugins/utils.ts+++ b/web/app/components/plugins/utils.ts@@ -1,7 +1,9 @@import type {TagKey,} from './constants'+import type { Plugin } from './types'+import { API_PREFIX, MARKETPLACE_API_PREFIX } from '@/config'import {categoryKeys,tagKeys,@@ -14,3 +16,27 @@ export const getValidTagKeys = (tags: TagKey[]) => {export const getValidCategoryKeys = (category?: string) => {return categoryKeys.find(key => key === category)}++const hasUrlProtocol = (value: string) => /^[a-z][a-z\d+.-]*:/i.test(value)++export const getPluginCardIconUrl = (+ plugin: Pick<Plugin, 'from' | 'name' | 'org' | 'type'>,+ icon: string | undefined,+ tenantId: string,+) => {+ if (!icon)+ return ''++ if (hasUrlProtocol(icon) || icon.startsWith('/'))+ return icon++ if (plugin.from === 'marketplace') {+ const basePath = plugin.type === 'bundle' ? 'bundles' : 'plugins'+ return `${MARKETPLACE_API_PREFIX}/${basePath}/${plugin.org}/${plugin.name}/icon`+ }++ if (!tenantId)+ return icon++ return `${API_PREFIX}/workspaces/current/plugin/icon?tenant_id=${tenantId}&filename=${icon}`+}diff --git a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsxindex 371e4fd7213..c084a5d45d1 100644--- a/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx+++ b/web/app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx@@ -119,14 +119,14 @@ const Popup = () => {type: 'success',message: t('publishPipeline.success.message', { ns: 'datasetPipeline' }),children: (- <div className="system-xs-regular text-text-secondary">+ <div className="text-text-secondary system-xs-regular"><Transi18nKey="publishPipeline.success.tip"ns="datasetPipeline"components={{CustomLink: (<Link- className="system-xs-medium text-text-accent"+ className="text-text-accent system-xs-medium"href={`/datasets/${datasetId}/documents`}></Link>@@ -185,13 +185,13 @@ const Popup = () => {message: t('publishTemplate.success.message', { ns: 'datasetPipeline' }),children: (<div className="flex flex-col gap-y-1">- <span className="system-xs-regular text-text-secondary">+ <span className="text-text-secondary system-xs-regular">{t('publishTemplate.success.tip', { ns: 'datasetPipeline' })}</span><Linkhref={docLink()}target="_blank"- className="system-xs-medium-uppercase inline-block text-text-accent"+ className="inline-block text-text-accent system-xs-medium-uppercase">{t('publishTemplate.success.learnMore', { ns: 'datasetPipeline' })}</Link>@@ -219,14 +219,14 @@ const Popup = () => {return (<div className={cn('rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xl shadow-shadow-shadow-5', isAllowPublishAsCustomKnowledgePipelineTemplate ? 'w-[360px]' : 'w-[400px]')}><div className="p-4 pt-3">- <div className="system-xs-medium-uppercase flex h-6 items-center text-text-tertiary">+ <div className="flex h-6 items-center text-text-tertiary system-xs-medium-uppercase">{publishedAt ? t('common.latestPublished', { ns: 'workflow' }) : t('common.currentDraftUnpublished', { ns: 'workflow' })}</div>{publishedAt? (<div className="flex items-center justify-between">- <div className="system-sm-medium flex items-center text-text-secondary">+ <div className="flex items-center text-text-secondary system-sm-medium">{t('common.publishedAt', { ns: 'workflow' })}{' '}{formatTimeFromNow(publishedAt)}@@ -234,7 +234,7 @@ const Popup = () => {</div>): (- <div className="system-sm-medium flex items-center text-text-secondary">+ <div className="flex items-center text-text-secondary system-sm-medium">{t('common.autoSaved', { ns: 'workflow' })}{' '}·@@ -305,7 +305,7 @@ const Popup = () => {{!isAllowPublishAsCustomKnowledgePipelineTemplate && (<PremiumBadge className="shrink-0 cursor-pointer select-none" size="s" color="indigo"><SparklesSoft className="flex size-3 items-center text-components-premium-badge-indigo-text-stop-0" />- <span className="system-2xs-medium p-0.5">+ <span className="p-0.5 system-2xs-medium">{t('upgradeBtn.encourageShort', { ns: 'billing' })}</span></PremiumBadge>diff --git a/web/app/components/tools/types.ts b/web/app/components/tools/types.tsindex e20061a8996..59c36967b5d 100644--- a/web/app/components/tools/types.ts+++ b/web/app/components/tools/types.ts@@ -1,6 +1,11 @@-import type { TypeWithI18N } from '../header/account-setting/model-provider-page/declarations'import type { VarType } from '../workflow/types'+type LocalizedText<T = string> = {+ en_US: T+ zh_Hans: T+ [key: string]: T+}+export enum LOC {tools = 'tools',app = 'app',@@ -47,10 +52,10 @@ export type Collection = {id: stringname: stringauthor: string- description: TypeWithI18N+ description: LocalizedTexticon: string | Emojiicon_dark?: string | Emoji- label: TypeWithI18N+ label: LocalizedTexttype: CollectionType | stringteam_credentials: Record<string, any>is_team_authorization: boolean@@ -84,8 +89,8 @@ export type Collection = {export type ToolParameter = {name: string- label: TypeWithI18N- human_description: TypeWithI18N+ label: LocalizedText+ human_description: LocalizedTexttype: stringform: stringllm_description: string@@ -93,7 +98,7 @@ export type ToolParameter = {multiple: booleandefault: stringoptions?: {- label: TypeWithI18N+ label: LocalizedTextvalue: string}[]min?: number@@ -102,8 +107,8 @@ export type ToolParameter = {export type TriggerParameter = {name: string- label: TypeWithI18N- human_description: TypeWithI18N+ label: LocalizedText+ human_description: LocalizedTexttype: stringform: stringllm_description: string@@ -111,7 +116,7 @@ export type TriggerParameter = {multiple: booleandefault: stringoptions?: {- label: TypeWithI18N+ label: LocalizedTextvalue: string}[]}@@ -120,8 +125,8 @@ export type TriggerParameter = {export type Event = {name: stringauthor: string- label: TypeWithI18N- description: TypeWithI18N+ label: LocalizedText+ description: LocalizedTextparameters: TriggerParameter[]labels: string[]output_schema: Record<string, any>@@ -130,7 +135,7 @@ export type Event = {export type Tool = {name: stringauthor: string- label: TypeWithI18N+ label: LocalizedTextdescription: anyparameters: ToolParameter[]labels: string[]@@ -139,14 +144,14 @@ export type Tool = {export type ToolCredential = {name: string- label: TypeWithI18N- help: TypeWithI18N | null- placeholder: TypeWithI18N+ label: LocalizedText+ help: LocalizedText | null+ placeholder: LocalizedTexttype: stringrequired: booleandefault: stringoptions?: {- label: TypeWithI18N+ label: LocalizedTextvalue: string}[]}@@ -167,8 +172,8 @@ export type CustomCollectionBackend = {export type ParamItem = {name: string- label: TypeWithI18N- human_description: TypeWithI18N+ label: LocalizedText+ human_description: LocalizedTextllm_description: stringtype: stringform: string@@ -177,7 +182,7 @@ export type ParamItem = {min?: numbermax?: numberoptions?: {- label: TypeWithI18N+ label: LocalizedTextvalue: string}[]}@@ -233,8 +238,8 @@ export type WorkflowToolProviderResponse = {tool: {author: stringname: string- label: TypeWithI18N- description: TypeWithI18N+ label: LocalizedText+ description: LocalizedTextlabels: string[]parameters: ParamItem[]output_schema: WorkflowToolProviderOutputSchemadiff --git a/web/app/components/workflow/__tests__/workflow-test-env.tsx b/web/app/components/workflow/__tests__/workflow-test-env.tsxindex 00d6829964a..cd11b886a25 100644--- a/web/app/components/workflow/__tests__/workflow-test-env.tsx+++ b/web/app/components/workflow/__tests__/workflow-test-env.tsx@@ -65,6 +65,7 @@ import type { Shape as HooksStoreShape } from '../hooks-store/store'import type { Shape } from '../store/workflow'import type { Edge, Node, WorkflowRunningData } from '../types'import type { WorkflowHistoryStoreApi } from '../workflow-history-store'+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'import { render, renderHook } from '@testing-library/react'import isDeepEqual from 'fast-deep-equal'import * as React from 'react'@@ -154,6 +155,13 @@ function createWorkflowWrapper(const historyCtxValue = historyConfig? createTestHistoryStoreContext(historyConfig): undefined+ const queryClient = new QueryClient({+ defaultOptions: {+ queries: {+ retry: false,+ },+ },+ })return ({ children }: { children: React.ReactNode }) => {let inner: React.ReactNode = children@@ -175,9 +183,13 @@ function createWorkflowWrapper(}return React.createElement(- WorkflowContext.Provider,- { value: stores.store },- inner,+ QueryClientProvider,+ { client: queryClient },+ React.createElement(+ WorkflowContext.Provider,+ { value: stores.store },+ inner,+ ),)}}diff --git a/web/app/components/workflow/block-icon.tsx b/web/app/components/workflow/block-icon.tsxindex f12812af787..3558531ee8d 100644--- a/web/app/components/workflow/block-icon.tsx+++ b/web/app/components/workflow/block-icon.tsx@@ -27,6 +27,7 @@ import {VariableX,WebhookLine,} from '@/app/components/base/icons/src/vender/workflow'+import { API_PREFIX } from '@/config'import { cn } from '@/utils/classnames'import { BlockEnum } from './types'@@ -82,6 +83,17 @@ const getIcon = (type: BlockEnum, className: string) => {return <DefaultIcon className={className} />}++const normalizeToolIconUrl = (toolIcon: string) => {+ const protectedPluginIconPath = '/workspaces/current/plugin/icon'+ const pathIndex = toolIcon.indexOf(protectedPluginIconPath)++ if (pathIndex < 0)+ return toolIcon++ return `${API_PREFIX}${toolIcon.slice(pathIndex)}`+}+const ICON_CONTAINER_BG_COLOR_MAP: Record<string, string> = {[BlockEnum.Start]: 'bg-util-colors-blue-brand-blue-brand-500',[BlockEnum.LLM]: 'bg-util-colors-indigo-indigo-500',@@ -119,6 +131,9 @@ const BlockIcon: FC<BlockIconProps> = ({}) => {const isToolOrDataSourceOrTriggerPlugin = type === BlockEnum.Tool || type === BlockEnum.DataSource || type === BlockEnum.TriggerPluginconst showDefaultIcon = !isToolOrDataSourceOrTriggerPlugin || !toolIcon+ const resolvedToolIcon = typeof toolIcon === 'string'+ ? normalizeToolIconUrl(toolIcon)+ : toolIconreturn (<div className={@@ -142,12 +157,12 @@ const BlockIcon: FC<BlockIconProps> = ({!showDefaultIcon && (<>{- typeof toolIcon === 'string'+ typeof resolvedToolIcon === 'string'? (<divclassName="h-full w-full shrink-0 rounded-md bg-cover bg-center"style={{- backgroundImage: `url(${toolIcon})`,+ backgroundImage: `url(${resolvedToolIcon})`,}}></div>@@ -156,8 +171,8 @@ const BlockIcon: FC<BlockIconProps> = ({<AppIconclassName="!h-full !w-full shrink-0"size="tiny"- icon={toolIcon?.content}- background={toolIcon?.background}+ icon={resolvedToolIcon?.content}+ background={resolvedToolIcon?.background}/>)}diff --git a/web/app/components/workflow/header/checklist.tsx b/web/app/components/workflow/header/checklist.tsxdeleted file mode 100644index 96ceab28064..00000000000--- a/web/app/components/workflow/header/checklist.tsx+++ /dev/null@@ -1,201 +0,0 @@-import type { ChecklistItem } from '../hooks/use-checklist'-import type {- BlockEnum,- CommonEdgeType,-} from '../types'-import {- RiCloseLine,- RiListCheck3,-} from '@remixicon/react'-import {- memo,- useState,-} from 'react'-import { useTranslation } from 'react-i18next'-import {- useEdges,-} from 'reactflow'-import { Warning } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'-import { IconR } from '@/app/components/base/icons/src/vender/line/arrows'-import {- ChecklistSquare,-} from '@/app/components/base/icons/src/vender/line/general'-import {- PortalToFollowElem,- PortalToFollowElemContent,- PortalToFollowElemTrigger,-} from '@/app/components/base/portal-to-follow-elem'-import useNodes from '@/app/components/workflow/store/workflow/use-nodes'-import { cn } from '@/utils/classnames'-import BlockIcon from '../block-icon'-import {- useChecklist,- useNodesInteractions,-} from '../hooks'--type WorkflowChecklistProps = {- disabled: boolean- showGoTo?: boolean- onItemClick?: (item: ChecklistItem) => void-}-const WorkflowChecklist = ({- disabled,- showGoTo = true,- onItemClick,-}: WorkflowChecklistProps) => {- const { t } = useTranslation()- const [open, setOpen] = useState(false)- const edges = useEdges<CommonEdgeType>()- const nodes = useNodes()- const needWarningNodes = useChecklist(nodes, edges)- const { handleNodeSelect } = useNodesInteractions()-- const handleChecklistItemClick = (item: ChecklistItem) => {- const goToEnabled = showGoTo && item.canNavigate && !item.disableGoTo- if (!goToEnabled)- return- if (onItemClick)- onItemClick(item)- else- handleNodeSelect(item.id)- setOpen(false)- }-- return (- <PortalToFollowElem- placement="bottom-end"- offset={{- mainAxis: 12,- crossAxis: 4,- }}- open={open}- onOpenChange={setOpen}- >- <PortalToFollowElemTrigger onClick={() => !disabled && setOpen(v => !v)}>- <div- className={cn(- 'relative ml-0.5 flex h-7 w-7 items-center justify-center rounded-md',- disabled && 'cursor-not-allowed opacity-50',- )}- >- <div- className={cn('group flex h-full w-full cursor-pointer items-center justify-center rounded-md hover:bg-state-accent-hover', open && 'bg-state-accent-hover')}- >- <RiListCheck3- className={cn('h-4 w-4 group-hover:text-components-button-secondary-accent-text', open ? 'text-components-button-secondary-accent-text' : 'text-components-button-ghost-text')}- />- </div>- {- !!needWarningNodes.length && (- <div className="absolute -right-1.5 -top-1.5 flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-gray-100 bg-[#F79009] text-[11px] font-semibold text-white">- {needWarningNodes.length}- </div>- )- }- </div>- </PortalToFollowElemTrigger>- <PortalToFollowElemContent className="z-[12]">- <div- className="w-[420px] overflow-y-auto rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-lg"- style={{- maxHeight: 'calc(2 / 3 * 100vh)',- }}- >- <div className="text-md sticky top-0 z-[1] flex h-[44px] items-center bg-components-panel-bg pl-4 pr-3 pt-3 font-semibold text-text-primary">- <div className="grow">- {t('panel.checklist', { ns: 'workflow' })}- {needWarningNodes.length ? `(${needWarningNodes.length})` : ''}- </div>- <div- className="flex h-6 w-6 shrink-0 cursor-pointer items-center justify-center"- onClick={() => setOpen(false)}- >- <RiCloseLine className="h-4 w-4 text-text-tertiary" />- </div>- </div>- <div className="pb-2">- {- !!needWarningNodes.length && (- <>- <div className="px-4 pt-1 text-xs text-text-tertiary">{t('panel.checklistTip', { ns: 'workflow' })}</div>- <div className="px-4 py-2">- {- needWarningNodes.map(node => (- <div- key={node.id}- className={cn(- 'group mb-2 rounded-lg border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-xs last-of-type:mb-0',- showGoTo && node.canNavigate && !node.disableGoTo ? 'cursor-pointer' : 'cursor-default opacity-80',- )}- onClick={() => handleChecklistItemClick(node)}- >- <div className="flex h-9 items-center p-2 text-xs font-medium text-text-secondary">- <BlockIcon- type={node.type as BlockEnum}- className="mr-1.5"- toolIcon={node.toolIcon}- />- <span className="grow truncate">- {node.title}- </span>- {- (showGoTo && node.canNavigate && !node.disableGoTo) && (- <div className="flex h-4 w-[60px] shrink-0 items-center justify-center gap-1 opacity-0 transition-opacity duration-200 group-hover:opacity-100">- <span className="whitespace-nowrap text-xs font-medium leading-4 text-primary-600">- {t('panel.goTo', { ns: 'workflow' })}- </span>- <IconR className="h-3.5 w-3.5 text-primary-600" />- </div>- )- }- </div>- <div- className={cn(- 'rounded-b-lg border-t-[0.5px] border-divider-regular',- (node.unConnected || node.errorMessage) && 'bg-gradient-to-r from-components-badge-bg-orange-soft to-transparent',- )}- >- {- node.unConnected && (- <div className="px-3 py-1 first:pt-1.5 last:pb-1.5">- <div className="flex text-xs leading-4 text-text-tertiary">- <Warning className="mr-2 mt-[2px] h-3 w-3 text-[#F79009]" />- {t('common.needConnectTip', { ns: 'workflow' })}- </div>- </div>- )- }- {- node.errorMessage && (- <div className="px-3 py-1 first:pt-1.5 last:pb-1.5">- <div className="flex text-xs leading-4 text-text-tertiary">- <Warning className="mr-2 mt-[2px] h-3 w-3 text-[#F79009]" />- {node.errorMessage}- </div>- </div>- )- }- </div>- </div>- ))- }- </div>- </>- )- }- {- !needWarningNodes.length && (- <div className="mx-4 mb-3 rounded-lg bg-components-panel-bg py-4 text-center text-xs text-text-tertiary">- <ChecklistSquare className="mx-auto mb-[5px] h-8 w-8 text-text-quaternary" />- {t('panel.checklistResolved', { ns: 'workflow' })}- </div>- )- }- </div>- </div>- </PortalToFollowElemContent>- </PortalToFollowElem>- )-}--export default memo(WorkflowChecklist)diff --git a/web/app/components/workflow/header/checklist/index.spec.tsx b/web/app/components/workflow/header/checklist/index.spec.tsxnew file mode 100644index 00000000000..6a31bd6a74f--- /dev/null+++ b/web/app/components/workflow/header/checklist/index.spec.tsx@@ -0,0 +1,131 @@+import type { ReactNode } from 'react'+import { fireEvent, render, screen } from '@testing-library/react'+import { BlockEnum } from '../../types'+import WorkflowChecklist from './index'++let mockChecklistItems = [+ {+ id: 'plugin-1',+ type: BlockEnum.Tool,+ title: 'Missing Plugin',+ errorMessages: [],+ canNavigate: false,+ isPluginMissing: true,+ },+ {+ id: 'node-1',+ type: BlockEnum.LLM,+ title: 'Broken Node',+ errorMessages: ['Needs configuration'],+ canNavigate: true,+ isPluginMissing: false,+ },+]++const mockHandleNodeSelect = vi.fn()++type PopoverProps = {+ children: ReactNode+ open?: boolean+ onOpenChange?: (open: boolean) => void+}++let latestOnOpenChange: PopoverProps['onOpenChange']++vi.mock('reactflow', () => ({+ useEdges: () => [],+}))++vi.mock('@/app/components/workflow/store/workflow/use-nodes', () => ({+ default: () => [],+}))++vi.mock('../../hooks', () => ({+ useChecklist: () => mockChecklistItems,+ useNodesInteractions: () => ({+ handleNodeSelect: mockHandleNodeSelect,+ }),+}))++vi.mock('@/app/components/base/ui/popover', () => ({+ Popover: ({ children, onOpenChange }: PopoverProps) => {+ latestOnOpenChange = onOpenChange+ return <div data-testid="popover">{children}</div>+ },+ PopoverTrigger: ({ render }: { render: ReactNode }) => <>{render}</>,+ PopoverContent: ({ children }: { children: ReactNode }) => <div>{children}</div>,+ PopoverClose: ({ children, className }: { children: ReactNode, className?: string }) => <button className={className}>{children}</button>,+}))++vi.mock('./plugin-group', () => ({+ ChecklistPluginGroup: ({ items }: { items: Array<{ title: string }> }) => <div data-testid="plugin-group">{items.map(item => item.title).join(',')}</div>,+}))++vi.mock('./node-group', () => ({+ ChecklistNodeGroup: ({ item, onItemClick }: { item: { title: string }, onItemClick: (item: { title: string }) => void }) => (+ <button data-testid={`node-group-${item.title}`} onClick={() => onItemClick(item)}>+ {item.title}+ </button>+ ),+}))++describe('WorkflowChecklist', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ latestOnOpenChange = undefined+ mockChecklistItems = [+ {+ id: 'plugin-1',+ type: BlockEnum.Tool,+ title: 'Missing Plugin',+ errorMessages: [],+ canNavigate: false,+ isPluginMissing: true,+ },+ {+ id: 'node-1',+ type: BlockEnum.LLM,+ title: 'Broken Node',+ errorMessages: ['Needs configuration'],+ canNavigate: true,+ isPluginMissing: false,+ },+ ]+ })++ it('should split checklist items into plugin and node groups and delegate clicks to node selection by default', () => {+ render(<WorkflowChecklist disabled={false} />)++ expect(screen.getByText('2')).toBeInTheDocument()+ expect(screen.getByTestId('plugin-group')).toHaveTextContent('Missing Plugin')+ fireEvent.click(screen.getByTestId('node-group-Broken Node'))++ expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1')+ })++ it('should use the custom item click handler when provided', () => {+ const onItemClick = vi.fn()+ render(<WorkflowChecklist disabled={false} onItemClick={onItemClick} />)++ fireEvent.click(screen.getByTestId('node-group-Broken Node'))++ expect(onItemClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'node-1' }))+ expect(mockHandleNodeSelect).not.toHaveBeenCalled()+ })++ it('should render the resolved state when there are no checklist warnings', () => {+ mockChecklistItems = []++ render(<WorkflowChecklist disabled={false} />)++ expect(screen.getByText(/checklistResolved/i)).toBeInTheDocument()+ })++ it('should ignore popover open changes when the checklist is disabled', () => {+ render(<WorkflowChecklist disabled={true} />)++ latestOnOpenChange?.(true)++ expect(screen.getByText('2').closest('button')).toBeDisabled()+ })+})diff --git a/web/app/components/workflow/header/checklist/index.tsx b/web/app/components/workflow/header/checklist/index.tsxnew file mode 100644index 00000000000..0b5a0c0dc1e--- /dev/null+++ b/web/app/components/workflow/header/checklist/index.tsx@@ -0,0 +1,151 @@+import type { ChecklistItem } from '../../hooks/use-checklist'+import type {+ CommonEdgeType,+} from '../../types'+import {+ memo,+ useMemo,+ useState,+} from 'react'+import { useTranslation } from 'react-i18next'+import {+ useEdges,+} from 'reactflow'+import {+ Popover,+ PopoverClose,+ PopoverContent,+ PopoverTrigger,+} from '@/app/components/base/ui/popover'+import useNodes from '@/app/components/workflow/store/workflow/use-nodes'+import { cn } from '@/utils/classnames'+import {+ useChecklist,+ useNodesInteractions,+} from '../../hooks'+import { ChecklistNodeGroup } from './node-group'+import { ChecklistPluginGroup } from './plugin-group'++type WorkflowChecklistProps = {+ disabled: boolean+ showGoTo?: boolean+ onItemClick?: (item: ChecklistItem) => void+}++const WorkflowChecklist = ({+ disabled,+ showGoTo = true,+ onItemClick,+}: WorkflowChecklistProps) => {+ const { t } = useTranslation()+ const [open, setOpen] = useState(false)+ const edges = useEdges<CommonEdgeType>()+ const nodes = useNodes()+ const needWarningNodes = useChecklist(nodes, edges)+ const { handleNodeSelect } = useNodesInteractions()++ const { pluginItems, nodeItems } = useMemo(() => {+ const plugins: ChecklistItem[] = []+ const regular: ChecklistItem[] = []+ for (const item of needWarningNodes) {+ if (item.isPluginMissing)+ plugins.push(item)+ else+ regular.push(item)+ }+ return { pluginItems: plugins, nodeItems: regular }+ }, [needWarningNodes])++ const handleItemClick = (item: ChecklistItem) => {+ if (onItemClick)+ onItemClick(item)+ else+ handleNodeSelect(item.id)+ setOpen(false)+ }++ return (+ <Popover open={open} onOpenChange={newOpen => !disabled && setOpen(newOpen)}>+ <PopoverTrigger+ render={(+ <button+ type="button"+ className={cn(+ 'relative ml-0.5 flex h-7 w-7 items-center justify-center rounded-md border-none bg-transparent p-0',+ disabled && 'cursor-not-allowed opacity-50',+ )}+ disabled={disabled || undefined}+ >+ <span+ className={cn('group flex h-full w-full items-center justify-center rounded-md hover:bg-state-accent-hover', open && 'bg-state-accent-hover')}+ >+ <span+ className={cn('i-ri-list-check-3 h-4 w-4 group-hover:text-components-button-secondary-accent-text', open ? 'text-components-button-secondary-accent-text' : 'text-components-button-ghost-text')}+ />+ </span>+ {!!needWarningNodes.length && (+ <span className="absolute -right-1.5 -top-1.5 flex h-[18px] min-w-[18px] items-center justify-center rounded-full border border-gray-100 bg-text-warning-secondary text-[11px] font-semibold text-white">+ {needWarningNodes.length}+ </span>+ )}+ </button>+ )}+ />+ <PopoverContent+ placement="bottom-start"+ sideOffset={12}+ alignOffset={-30}+ popupClassName="w-[420px] rounded-2xl bg-background-default-subtle"+ >+ <div+ className="overflow-y-auto"+ style={{ maxHeight: 'calc(2 / 3 * 100vh)' }}+ >+ <div className="flex flex-col gap-0.5 px-3 pb-1 pt-3.5">+ <div className="flex items-start px-1">+ <div className="min-w-0 grow pr-8">+ <h2 className="text-base font-semibold leading-6 text-text-primary">+ {t('panel.checklist', { ns: 'workflow' })}+ {needWarningNodes.length > 0 && `(${needWarningNodes.length})`}+ </h2>+ </div>+ <PopoverClose className="-mr-0.5 -mt-0.5 flex size-7 shrink-0 items-center justify-center rounded-lg">+ <span className="i-ri-close-line size-4 text-text-tertiary" />+ </PopoverClose>+ </div>+ {needWarningNodes.length > 0 && (+ <p className="px-1 text-xs leading-4 text-text-tertiary">+ {t('panel.checklistDescription', { ns: 'workflow' })}+ </p>+ )}+ </div>++ {needWarningNodes.length > 0+ ? (+ <div className="flex flex-col gap-1 px-4 pb-4 pt-1">+ {pluginItems.length > 0 && (+ <ChecklistPluginGroup items={pluginItems} />+ )}+ {nodeItems.map(item => (+ <ChecklistNodeGroup+ key={item.id}+ item={item}+ showGoTo={showGoTo}+ onItemClick={handleItemClick}+ />+ ))}+ </div>+ )+ : (+ <div className="mx-4 mb-3 rounded-lg py-4 text-center text-xs text-text-tertiary">+ <span className="i-custom-vender-line-general-checklist-square mx-auto mb-[5px] block h-8 w-8 text-text-quaternary" />+ {t('panel.checklistResolved', { ns: 'workflow' })}+ </div>+ )}+ </div>+ </PopoverContent>+ </Popover>+ )+}++export default memo(WorkflowChecklist)diff --git a/web/app/components/workflow/header/checklist/item-indicator.tsx b/web/app/components/workflow/header/checklist/item-indicator.tsxnew file mode 100644index 00000000000..7c26cddffdb--- /dev/null+++ b/web/app/components/workflow/header/checklist/item-indicator.tsx@@ -0,0 +1,21 @@+import { cn } from '@/utils/classnames'++type ItemIndicatorProps = {+ className?: string+}++export const ItemIndicator = ({ className }: ItemIndicatorProps) => {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ width="20"+ height="24"+ viewBox="0 0 20 24"+ fill="none"+ className={cn('shrink-0', className)}+ >+ <path d="M9.5 0H10.5V24H9.5V0Z" fill="currentColor" className="text-divider-regular" />+ <circle cx="10" cy="12" r="3.25" fill="#F79009" stroke="white" strokeWidth="1.5" />+ </svg>+ )+}diff --git a/web/app/components/workflow/header/checklist/node-group.spec.tsx b/web/app/components/workflow/header/checklist/node-group.spec.tsxnew file mode 100644index 00000000000..25f54211b4f--- /dev/null+++ b/web/app/components/workflow/header/checklist/node-group.spec.tsx@@ -0,0 +1,61 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { BlockEnum } from '../../types'+import { ChecklistNodeGroup } from './node-group'++vi.mock('../../block-icon', () => ({+ default: () => <div data-testid="block-icon" />,+}))++vi.mock('./item-indicator', () => ({+ ItemIndicator: () => <div data-testid="item-indicator" />,+}))++const createItem = (overrides: Record<string, unknown> = {}) => ({+ id: 'node-1',+ type: BlockEnum.LLM,+ title: 'Broken Node',+ errorMessages: ['Needs configuration'],+ canNavigate: true,+ disableGoTo: false,+ unConnected: false,+ ...overrides,+})++describe('ChecklistNodeGroup', () => {+ it('should render errors and the connection warning, and allow navigation when go-to is enabled', () => {+ const onItemClick = vi.fn()++ render(+ <ChecklistNodeGroup+ item={createItem({ unConnected: true }) as never}+ showGoTo={true}+ onItemClick={onItemClick}+ />,+ )++ expect(screen.getByText('Needs configuration')).toBeInTheDocument()+ expect(screen.getByText(/needConnectTip/i)).toBeInTheDocument()+ expect(screen.getAllByText(/goToFix/i)).toHaveLength(2)++ fireEvent.click(screen.getByText('Needs configuration'))++ expect(onItemClick).toHaveBeenCalledWith(expect.objectContaining({ id: 'node-1' }))+ })++ it('should not allow navigation when go-to is disabled', () => {+ const onItemClick = vi.fn()++ render(+ <ChecklistNodeGroup+ item={createItem({ disableGoTo: true }) as never}+ showGoTo={true}+ onItemClick={onItemClick}+ />,+ )++ fireEvent.click(screen.getByText('Needs configuration'))++ expect(onItemClick).not.toHaveBeenCalled()+ expect(screen.queryByText(/goToFix/i)).not.toBeInTheDocument()+ })+})diff --git a/web/app/components/workflow/header/checklist/node-group.tsx b/web/app/components/workflow/header/checklist/node-group.tsxnew file mode 100644index 00000000000..3c4a3a33da4--- /dev/null+++ b/web/app/components/workflow/header/checklist/node-group.tsx@@ -0,0 +1,75 @@+import type { ChecklistItem } from '../../hooks/use-checklist'+import type { BlockEnum } from '../../types'+import { memo, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import { cn } from '@/utils/classnames'+import BlockIcon from '../../block-icon'+import { ItemIndicator } from './item-indicator'++type ChecklistSubItem = {+ key: string+ message: string+}++export const ChecklistNodeGroup = memo(({+ item,+ showGoTo,+ onItemClick,+}: {+ item: ChecklistItem+ showGoTo: boolean+ onItemClick: (item: ChecklistItem) => void+}) => {+ const { t } = useTranslation()+ const goToEnabled = showGoTo && item.canNavigate && !item.disableGoTo++ const subItems = useMemo(() => {+ const items: ChecklistSubItem[] = []+ for (let i = 0; i < item.errorMessages.length; i++)+ items.push({ key: `error-${i}`, message: item.errorMessages[i] })+ if (item.unConnected)+ items.push({ key: 'unconnected', message: t('common.needConnectTip', { ns: 'workflow' }) })+ return items+ }, [item.errorMessages, item.unConnected, t])++ return (+ <div className="overflow-clip rounded-[10px] bg-components-panel-on-panel-item-bg">+ <div className="flex items-center gap-2 px-2 pt-2">+ <BlockIcon+ type={item.type as BlockEnum}+ size="sm"+ toolIcon={item.toolIcon}+ />+ <span className="min-w-0 grow truncate text-sm font-medium leading-5 text-text-primary">+ {item.title}+ </span>+ </div>+ <div className="p-1">+ {subItems.map(sub => (+ <div+ key={sub.key}+ className={cn(+ 'group/item flex items-center gap-2 rounded-lg px-1',+ goToEnabled && 'cursor-pointer hover:bg-state-base-hover',+ )}+ onClick={() => goToEnabled && onItemClick(item)}+ >+ <ItemIndicator />+ <span className="min-w-0 grow truncate text-xs leading-4 text-text-warning">+ {sub.message}+ </span>+ {goToEnabled && (+ <div className="flex shrink-0 items-center gap-0.5 pr-0.5 opacity-0 transition-opacity duration-150 group-hover/item:opacity-100">+ <span className="whitespace-nowrap text-xs font-medium leading-4 text-text-accent">+ {t('panel.goToFix', { ns: 'workflow' })}+ </span>+ <span className="i-ri-arrow-right-line size-3.5 text-text-accent" />+ </div>+ )}+ </div>+ ))}+ </div>+ </div>+ )+})+ChecklistNodeGroup.displayName = 'ChecklistNodeGroup'diff --git a/web/app/components/workflow/header/checklist/plugin-group.spec.tsx b/web/app/components/workflow/header/checklist/plugin-group.spec.tsxnew file mode 100644index 00000000000..1d9f0dc7d6e--- /dev/null+++ b/web/app/components/workflow/header/checklist/plugin-group.spec.tsx@@ -0,0 +1,96 @@+import type { ChecklistItem } from '../../hooks/use-checklist'+import { fireEvent, render, screen } from '@testing-library/react'+import { beforeEach, describe, expect, it } from 'vitest'+import { Popover, PopoverContent } from '@/app/components/base/ui/popover'+import { useStore as usePluginDependencyStore } from '../../plugin-dependency/store'+import { BlockEnum } from '../../types'+import { ChecklistPluginGroup } from './plugin-group'++const createChecklistItem = (overrides: Partial<ChecklistItem> = {}): ChecklistItem => ({+ id: 'node-1',+ type: BlockEnum.Tool,+ title: 'Tool Node',+ errorMessages: [],+ canNavigate: false,+ isPluginMissing: true,+ pluginUniqueIdentifier: 'langgenius/test-plugin:1.0.0@sha256',+ ...overrides,+})++describe('ChecklistPluginGroup', () => {+ const getInstallButton = () => {+ return screen.getByText('workflow.nodes.agent.pluginInstaller.install').closest('button') as HTMLButtonElement+ }++ const renderInPopover = (items: ChecklistItem[]) => {+ return render(+ <Popover open>+ <PopoverContent>+ <ChecklistPluginGroup items={items} />+ </PopoverContent>+ </Popover>,+ )+ }++ beforeEach(() => {+ usePluginDependencyStore.setState({ dependencies: [] })+ })++ it('should set marketplace dependencies when install button is clicked', () => {+ const items: ChecklistItem[] = [+ createChecklistItem({ id: 'node-1', pluginUniqueIdentifier: 'langgenius/test-plugin:1.0.0@sha256' }),+ createChecklistItem({ id: 'node-2', pluginUniqueIdentifier: 'langgenius/test-plugin:1.0.0@sha256' }),+ createChecklistItem({ id: 'node-3', pluginUniqueIdentifier: 'langgenius/another-plugin:2.0.0@sha256' }),+ ]++ renderInPopover(items)++ fireEvent.click(getInstallButton())++ expect(usePluginDependencyStore.getState().dependencies).toEqual([+ {+ type: 'marketplace',+ value: {+ marketplace_plugin_unique_identifier: 'langgenius/test-plugin:1.0.0@sha256',+ plugin_unique_identifier: 'langgenius/test-plugin:1.0.0@sha256',+ version: '1.0.0',+ },+ },+ {+ type: 'marketplace',+ value: {+ marketplace_plugin_unique_identifier: 'langgenius/another-plugin:2.0.0@sha256',+ plugin_unique_identifier: 'langgenius/another-plugin:2.0.0@sha256',+ version: '2.0.0',+ },+ },+ ])+ })++ it('should keep install button disabled when no identifier is available', () => {+ renderInPopover([createChecklistItem({ pluginUniqueIdentifier: undefined })])++ const installButton = getInstallButton()+ expect(installButton).toBeDisabled()++ fireEvent.click(installButton)+ expect(usePluginDependencyStore.getState().dependencies).toEqual([])+ })++ it('should omit the version when the marketplace identifier does not include one', () => {+ renderInPopover([createChecklistItem({ pluginUniqueIdentifier: 'langgenius/test-plugin@sha256' })])++ fireEvent.click(getInstallButton())++ expect(usePluginDependencyStore.getState().dependencies).toEqual([+ {+ type: 'marketplace',+ value: {+ marketplace_plugin_unique_identifier: 'langgenius/test-plugin@sha256',+ plugin_unique_identifier: 'langgenius/test-plugin@sha256',+ version: undefined,+ },+ },+ ])+ })+})diff --git a/web/app/components/workflow/header/checklist/plugin-group.tsx b/web/app/components/workflow/header/checklist/plugin-group.tsxnew file mode 100644index 00000000000..122cd560bcd--- /dev/null+++ b/web/app/components/workflow/header/checklist/plugin-group.tsx@@ -0,0 +1,99 @@+import type { ChecklistItem } from '../../hooks/use-checklist'+import type { BlockEnum } from '../../types'+import type { Dependency } from '@/app/components/plugins/types'+import { memo, useMemo } from 'react'+import { useTranslation } from 'react-i18next'+import Button from '@/app/components/base/button'+import { PopoverClose } from '@/app/components/base/ui/popover'+import BlockIcon from '../../block-icon'+import { useStore as usePluginDependencyStore } from '../../plugin-dependency/store'+import { ItemIndicator } from './item-indicator'++function getVersionFromMarketplaceIdentifier(identifier: string): string | undefined {+ const withoutHash = identifier.split('@')[0]+ const [, version] = withoutHash.split(':')+ return version || undefined+}++export const ChecklistPluginGroup = memo(({+ items,+}: {+ items: ChecklistItem[]+}) => {+ const { t } = useTranslation()++ const identifiers = useMemo(+ () => Array.from(+ new Set(+ items+ .map(i => i.pluginUniqueIdentifier)+ .filter((id): id is string => Boolean(id)),+ ),+ ),+ [items],+ )++ const dependencies = useMemo<Dependency[]>(() => {+ return identifiers.map((identifier) => {+ return {+ type: 'marketplace',+ value: {+ marketplace_plugin_unique_identifier: identifier,+ plugin_unique_identifier: identifier,+ version: getVersionFromMarketplaceIdentifier(identifier),+ },+ }+ })+ }, [identifiers])++ const handleInstallAll = () => {+ if (dependencies.length === 0)+ return+ const { setDependencies } = usePluginDependencyStore.getState()+ setDependencies(dependencies)+ }++ return (+ <div className="overflow-clip rounded-[10px] bg-components-panel-on-panel-item-bg">+ <div className="flex items-center gap-2 px-2 pt-2">+ <div className="flex size-5 shrink-0 items-center justify-center rounded-md border-[0.5px] border-divider-regular bg-components-icon-bg-midnight-solid shadow-xs">+ <span className="i-ri-download-line size-3.5 text-white" />+ </div>+ <span className="min-w-0 grow truncate text-sm font-medium leading-5 text-text-primary">+ {t('nodes.common.pluginsNotInstalled', { ns: 'workflow', count: items.length })}+ </span>+ <PopoverClose+ render={(+ <Button+ variant="secondary"+ size="small"+ onClick={handleInstallAll}+ disabled={dependencies.length === 0}+ />+ )}+ >+ {t('nodes.agent.pluginInstaller.install', { ns: 'workflow' })}+ </PopoverClose>+ </div>+ <div className="p-1">+ {items.map(item => (+ <div+ key={item.id}+ className="flex items-center gap-2 rounded-lg px-1"+ >+ <ItemIndicator />+ <BlockIcon+ type={item.type as BlockEnum}+ size="xs"+ toolIcon={item.toolIcon}+ />+ <span className="min-w-0 grow truncate text-xs leading-4 text-text-warning">+ {item.title}+ </span>+ </div>+ ))}+ </div>+ </div>+ )+})+ChecklistPluginGroup.displayName = 'ChecklistPluginGroup'diff --git a/web/app/components/workflow/header/run-mode.spec.tsx b/web/app/components/workflow/header/run-mode.spec.tsxnew file mode 100644index 00000000000..2f44d4a21b3--- /dev/null+++ b/web/app/components/workflow/header/run-mode.spec.tsx@@ -0,0 +1,150 @@+import type { ReactNode } from 'react'+import { fireEvent, render, screen } from '@testing-library/react'+import * as React from 'react'+import { WorkflowRunningStatus } from '@/app/components/workflow/types'+import RunMode from './run-mode'+import { TriggerType } from './test-run-menu'++const mockHandleWorkflowStartRunInWorkflow = vi.fn()+const mockHandleWorkflowTriggerScheduleRunInWorkflow = vi.fn()+const mockHandleWorkflowTriggerWebhookRunInWorkflow = vi.fn()+const mockHandleWorkflowTriggerPluginRunInWorkflow = vi.fn()+const mockHandleWorkflowRunAllTriggersInWorkflow = vi.fn()+const mockHandleStopRun = vi.fn()+const mockNotify = vi.fn()+const mockTrackEvent = vi.fn()++let mockWarningNodes: Array<{ id: string }> = []+let mockWorkflowRunningData: { result: { status: WorkflowRunningStatus }, task_id: string } | undefined+let mockIsListening = false+let mockDynamicOptions = [+ { type: TriggerType.UserInput, nodeId: 'start-node' },+]++vi.mock('@/app/components/workflow/hooks', () => ({+ useWorkflowStartRun: () => ({+ handleWorkflowStartRunInWorkflow: mockHandleWorkflowStartRunInWorkflow,+ handleWorkflowTriggerScheduleRunInWorkflow: mockHandleWorkflowTriggerScheduleRunInWorkflow,+ handleWorkflowTriggerWebhookRunInWorkflow: mockHandleWorkflowTriggerWebhookRunInWorkflow,+ handleWorkflowTriggerPluginRunInWorkflow: mockHandleWorkflowTriggerPluginRunInWorkflow,+ handleWorkflowRunAllTriggersInWorkflow: mockHandleWorkflowRunAllTriggersInWorkflow,+ }),+ useWorkflowRun: () => ({+ handleStopRun: mockHandleStopRun,+ }),+ useWorkflowRunValidation: () => ({+ warningNodes: mockWarningNodes,+ }),+}))++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: { workflowRunningData?: unknown, isListening: boolean }) => unknown) =>+ selector({ workflowRunningData: mockWorkflowRunningData, isListening: mockIsListening }),+}))++vi.mock('../hooks/use-dynamic-test-run-options', () => ({+ useDynamicTestRunOptions: () => mockDynamicOptions,+}))++vi.mock('@/app/components/base/toast/context', () => ({+ useToastContext: () => ({+ notify: mockNotify,+ }),+}))++vi.mock('@/app/components/base/amplitude', () => ({+ trackEvent: (...args: unknown[]) => mockTrackEvent(...args),+}))++vi.mock('@/context/event-emitter', () => ({+ useEventEmitterContextContext: () => ({+ eventEmitter: {+ useSubscription: vi.fn(),+ },+ }),+}))++vi.mock('@/app/components/workflow/shortcuts-name', () => ({+ default: () => <span data-testid="shortcuts-name">Shortcut</span>,+}))++vi.mock('@/app/components/base/icons/src/vender/line/mediaAndDevices', () => ({+ StopCircle: () => <span data-testid="stop-circle" />,+}))++vi.mock('./test-run-menu', async (importOriginal) => {+ const actual = await importOriginal<typeof import('./test-run-menu')>()+ return {+ ...actual,+ default: React.forwardRef(({ children, options, onSelect }: { children: ReactNode, options: Array<{ type: TriggerType, nodeId?: string, relatedNodeIds?: string[] }>, onSelect: (option: { type: TriggerType, nodeId?: string, relatedNodeIds?: string[] }) => void }, ref) => {+ React.useImperativeHandle(ref, () => ({+ toggle: vi.fn(),+ }))+ return (+ <div>+ <button data-testid="trigger-option" onClick={() => onSelect(options[0])}>+ Trigger option+ </button>+ {children}+ </div>+ )+ }),+ }+})++describe('RunMode', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockWarningNodes = []+ mockWorkflowRunningData = undefined+ mockIsListening = false+ mockDynamicOptions = [+ { type: TriggerType.UserInput, nodeId: 'start-node' },+ ]+ })++ it('should render the run trigger and start the workflow when a valid trigger is selected', () => {+ render(<RunMode />)++ expect(screen.getByText(/run/i)).toBeInTheDocument()+ fireEvent.click(screen.getByTestId('trigger-option'))++ expect(mockHandleWorkflowStartRunInWorkflow).toHaveBeenCalledTimes(1)+ expect(mockTrackEvent).toHaveBeenCalledWith('app_start_action_time', { action_type: 'user_input' })+ })++ it('should show an error toast instead of running when the selected trigger has checklist warnings', () => {+ mockWarningNodes = [{ id: 'start-node' }]++ render(<RunMode />)+ fireEvent.click(screen.getByTestId('trigger-option'))++ expect(mockNotify).toHaveBeenCalledWith({+ type: 'error',+ message: 'workflow.panel.checklistTip',+ })+ expect(mockHandleWorkflowStartRunInWorkflow).not.toHaveBeenCalled()+ })++ it('should render the running state and stop the workflow when it is already running', () => {+ mockWorkflowRunningData = {+ result: { status: WorkflowRunningStatus.Running },+ task_id: 'task-1',+ }++ render(<RunMode />)++ expect(screen.getByText(/running/i)).toBeInTheDocument()+ fireEvent.click(screen.getByTestId('stop-circle').closest('button') as HTMLButtonElement)++ expect(mockHandleStopRun).toHaveBeenCalledWith('task-1')+ })++ it('should render the listening label when the workflow is listening', () => {+ mockIsListening = true++ render(<RunMode />)++ expect(screen.getByText(/listening/i)).toBeInTheDocument()+ })+})diff --git a/web/app/components/workflow/header/run-mode.tsx b/web/app/components/workflow/header/run-mode.tsxindex 943af13a927..86f998e0b7e 100644--- a/web/app/components/workflow/header/run-mode.tsx+++ b/web/app/components/workflow/header/run-mode.tsx@@ -114,7 +114,7 @@ const RunMode = ({<buttontype="button"className={cn(- 'system-xs-medium flex h-7 cursor-not-allowed items-center gap-x-1 rounded-l-md bg-state-accent-hover px-1.5 text-text-accent',+ 'flex h-7 cursor-not-allowed items-center gap-x-1 rounded-l-md bg-state-accent-hover px-1.5 text-text-accent system-xs-medium',)}disabled={true}>@@ -130,7 +130,7 @@ const RunMode = ({><divclassName={cn(- 'system-xs-medium flex h-7 cursor-pointer items-center gap-x-1 rounded-md px-1.5 text-text-accent hover:bg-state-accent-hover',+ 'flex h-7 cursor-pointer items-center gap-x-1 rounded-md px-1.5 text-text-accent system-xs-medium hover:bg-state-accent-hover',)}style={{ userSelect: 'none' }}>diff --git a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.tsindex 1b370551345..a11fe2c981b 100644--- a/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts+++ b/web/app/components/workflow/hooks/__tests__/use-checklist.spec.ts@@ -1,8 +1,12 @@import type { CommonNodeType, Node } from '../../types'import type { ChecklistItem } from '../use-checklist'+import { screen, waitFor } from '@testing-library/react'+import { createElement, Fragment } from 'react'+import { CollectionType } from '@/app/components/tools/types'import { createEdge, createNode, resetFixtureCounters } from '../../__tests__/fixtures'import { resetReactFlowMockState, rfState } from '../../__tests__/reactflow-mock-state'-import { renderWorkflowHook } from '../../__tests__/workflow-test-env'+import { renderWorkflowComponent, renderWorkflowHook } from '../../__tests__/workflow-test-env'+import { useStore } from '../../store'import { BlockEnum } from '../../types'import { useChecklist, useWorkflowRunValidation } from '../use-checklist'@@ -39,6 +43,9 @@ vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', ()type CheckValidFn = (data: CommonNodeType, t: unknown, extra?: unknown) => { errorMessage: string }const mockNodesMap: Record<string, { checkValid: CheckValidFn, metaData: { isStart: boolean, isRequired: boolean } }> = {}+let mockModelProviders: Array<{ provider: string }> = []+let mockUsedVars: string[][] = []+const mockAvailableVarMap: Record<string, { availableVars: Array<{ nodeId: string, vars: Array<{ variable: string }> }> }> = {}vi.mock('../use-nodes-meta-data', () => ({useNodesMetaData: () => ({@@ -49,10 +56,10 @@ vi.mock('../use-nodes-meta-data', () => ({vi.mock('../use-nodes-available-var-list', () => ({default: (nodes: Node[]) => {- const map: Record<string, { availableVars: never[] }> = {}+ const map: Record<string, { availableVars: Array<{ nodeId: string, vars: Array<{ variable: string }> }> }> = {}if (nodes) {for (const n of nodes)- map[n.id] = { availableVars: [] }+ map[n.id] = mockAvailableVarMap[n.id] ?? { availableVars: [] }}return map},@@ -60,7 +67,7 @@ vi.mock('../use-nodes-available-var-list', () => ({}))vi.mock('../../nodes/_base/components/variable/utils', () => ({- getNodeUsedVars: () => [],+ getNodeUsedVars: () => mockUsedVars,isSpecialVar: () => false,}))@@ -90,6 +97,11 @@ vi.mock('@/context/i18n', () => ({useGetLanguage: () => 'en',}))+vi.mock('@/context/provider-context', () => ({+ useProviderContextSelector: (selector: (state: { modelProviders: Array<{ provider: string }> }) => unknown) =>+ selector({ modelProviders: mockModelProviders }),+}))+// useWorkflowNodes reads from WorkflowContext (real store via renderWorkflowHook)// ---------------------------------------------------------------------------@@ -124,6 +136,9 @@ beforeEach(() => {resetReactFlowMockState()resetFixtureCounters()Object.keys(mockNodesMap).forEach(k => delete mockNodesMap[k])+ Object.keys(mockAvailableVarMap).forEach(k => delete mockAvailableVarMap[k])+ mockModelProviders = []+ mockUsedVars = []setupNodesMap()})@@ -195,7 +210,7 @@ describe('useChecklist', () => {const warning = result.current.find((item: ChecklistItem) => item.id === 'llm')expect(warning).toBeDefined()- expect(warning!.errorMessage).toBe('Model not configured')+ expect(warning!.errorMessages).toContain('Model not configured')})it('should report missing start node in workflow mode', () => {@@ -217,7 +232,9 @@ describe('useChecklist', () => {data: {type: BlockEnum.Tool,title: 'My Tool',- _pluginInstallLocked: true,+ provider_type: CollectionType.builtIn,+ provider_id: 'missing-provider',+ plugin_unique_identifier: 'plugin/[email protected]',},})@@ -233,6 +250,9 @@ describe('useChecklist', () => {expect(warning).toBeDefined()expect(warning!.canNavigate).toBe(false)expect(warning!.disableGoTo).toBe(true)+ expect(warning!.isPluginMissing).toBe(true)+ expect(warning!.pluginUniqueIdentifier).toBe('plugin/[email protected]')+ expect(warning!.errorMessages).toContain('workflow.nodes.common.pluginNotInstalled')})it('should report required node types that are missing', () => {@@ -279,6 +299,112 @@ describe('useChecklist', () => {const alienWarning = result.current.find((item: ChecklistItem) => item.id === 'alien')expect(alienWarning).toBeUndefined()})++ it('should report configure model errors when an llm model provider plugin is missing', () => {+ const startNode = createNode({ id: 'start', data: { type: BlockEnum.Start, title: 'Start' } })+ const llmNode = createNode({+ id: 'llm',+ data: {+ type: BlockEnum.LLM,+ title: 'LLM',+ model: {+ provider: 'langgenius/openai/openai',+ },+ },+ })++ const edges = [+ createEdge({ source: 'start', target: 'llm' }),+ ]++ const { result } = renderWorkflowHook(+ () => useChecklist([startNode, llmNode], edges),+ )++ const warning = result.current.find((item: ChecklistItem) => item.id === 'llm')+ expect(warning).toBeDefined()+ expect(warning!.errorMessages).toContain('workflow.errorMsg.configureModel')+ expect(warning!.canNavigate).toBe(true)+ })++ it('should accumulate validation and invalid variable errors for the same node', () => {+ mockNodesMap[BlockEnum.LLM] = {+ checkValid: () => ({ errorMessage: 'Model not configured' }),+ metaData: { isStart: false, isRequired: false },+ }+ mockUsedVars = [['start', 'missingVar']]+ mockAvailableVarMap.llm = {+ availableVars: [+ {+ nodeId: 'start',+ vars: [{ variable: 'existingVar' }],+ },+ ],+ }++ const startNode = createNode({ id: 'start', data: { type: BlockEnum.Start, title: 'Start' } })+ const llmNode = createNode({+ id: 'llm',+ data: {+ type: BlockEnum.LLM,+ title: 'LLM',+ },+ })++ const edges = [+ createEdge({ source: 'start', target: 'llm' }),+ ]++ const { result } = renderWorkflowHook(+ () => useChecklist([startNode, llmNode], edges),+ )++ const warning = result.current.find((item: ChecklistItem) => item.id === 'llm')+ expect(warning).toBeDefined()+ expect(warning!.errorMessages).toEqual([+ 'Model not configured',+ 'workflow.errorMsg.invalidVariable',+ ])+ })++ it('should sync checklist items to the workflow store without render phase update warnings', async () => {+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})+ try {+ const startNode = createNode({ id: 'start', data: { type: BlockEnum.Start, title: 'Start' } })+ const codeNode = createNode({ id: 'code', data: { type: BlockEnum.Code, title: 'Code' } })++ function Operator() {+ const checklistItems = useStore(state => state.checklistItems)+ return createElement('div', { 'data-testid': 'checklist-count' }, checklistItems.length)+ }++ function WorkflowChecklist() {+ useChecklist([startNode, codeNode], [])+ return null+ }++ const { store } = renderWorkflowComponent(+ createElement(+ Fragment,+ null,+ createElement(Operator),+ createElement(WorkflowChecklist),+ ),+ )++ await waitFor(() => {+ expect(store.getState().checklistItems).toHaveLength(1)+ })++ expect(screen.getByTestId('checklist-count')).toHaveTextContent('1')+ expect(errorSpy.mock.calls.some(call =>+ call.some(arg => typeof arg === 'string' && arg.includes('Cannot update a component')),+ )).toBe(false)+ }+ finally {+ errorSpy.mockRestore()+ }+ })})// ---------------------------------------------------------------------------diff --git a/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.ts b/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.tsnew file mode 100644index 00000000000..4577055098c--- /dev/null+++ b/web/app/components/workflow/hooks/__tests__/use-node-plugin-installation.spec.ts@@ -0,0 +1,253 @@+import type { CommonNodeType } from '../../types'+import { act } from '@testing-library/react'+import { CollectionType } from '@/app/components/tools/types'+import { renderWorkflowHook } from '../../__tests__/workflow-test-env'+import { BlockEnum } from '../../types'+import { useNodePluginInstallation } from '../use-node-plugin-installation'++const mockBuiltInTools = vi.fn()+const mockCustomTools = vi.fn()+const mockWorkflowTools = vi.fn()+const mockMcpTools = vi.fn()+const mockInvalidToolsByType = vi.fn()+const mockTriggerPlugins = vi.fn()+const mockInvalidateTriggers = vi.fn()+const mockInvalidDataSourceList = vi.fn()++vi.mock('@/service/use-tools', () => ({+ useAllBuiltInTools: (enabled: boolean) => mockBuiltInTools(enabled),+ useAllCustomTools: (enabled: boolean) => mockCustomTools(enabled),+ useAllWorkflowTools: (enabled: boolean) => mockWorkflowTools(enabled),+ useAllMCPTools: (enabled: boolean) => mockMcpTools(enabled),+ useInvalidToolsByType: (providerType?: string) => mockInvalidToolsByType(providerType),+}))++vi.mock('@/service/use-triggers', () => ({+ useAllTriggerPlugins: (enabled: boolean) => mockTriggerPlugins(enabled),+ useInvalidateAllTriggerPlugins: () => mockInvalidateTriggers,+}))++vi.mock('@/service/use-pipeline', () => ({+ useInvalidDataSourceList: () => mockInvalidDataSourceList,+}))++const makeToolNode = (overrides: Partial<CommonNodeType> = {}) => ({+ type: BlockEnum.Tool,+ title: 'Tool node',+ desc: '',+ provider_type: CollectionType.builtIn,+ provider_id: 'search',+ provider_name: 'search',+ plugin_id: 'plugin-search',+ plugin_unique_identifier: '[email protected]',+ ...overrides,+}) as CommonNodeType++const makeTriggerNode = (overrides: Partial<CommonNodeType> = {}) => ({+ type: BlockEnum.TriggerPlugin,+ title: 'Trigger node',+ desc: '',+ provider_id: 'trigger-provider',+ provider_name: 'trigger-provider',+ plugin_id: 'trigger-plugin',+ plugin_unique_identifier: '[email protected]',+ ...overrides,+}) as CommonNodeType++const makeDataSourceNode = (overrides: Partial<CommonNodeType> = {}) => ({+ type: BlockEnum.DataSource,+ title: 'Data source node',+ desc: '',+ provider_name: 'knowledge-provider',+ plugin_id: 'knowledge-plugin',+ plugin_unique_identifier: '[email protected]',+ ...overrides,+}) as CommonNodeType++const matchedTool = {+ plugin_id: 'plugin-search',+ provider: 'search',+ name: 'search',+ plugin_unique_identifier: '[email protected]',+}++const matchedTriggerProvider = {+ id: 'trigger-provider',+ name: 'trigger-provider',+ plugin_id: 'trigger-plugin',+}++const matchedDataSource = {+ provider: 'knowledge-provider',+ plugin_id: 'knowledge-plugin',+ plugin_unique_identifier: '[email protected]',+}++describe('useNodePluginInstallation', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockBuiltInTools.mockReturnValue({ data: undefined, isLoading: false })+ mockCustomTools.mockReturnValue({ data: undefined, isLoading: false })+ mockWorkflowTools.mockReturnValue({ data: undefined, isLoading: false })+ mockMcpTools.mockReturnValue({ data: undefined, isLoading: false })+ mockInvalidToolsByType.mockReturnValue(undefined)+ mockTriggerPlugins.mockReturnValue({ data: undefined, isLoading: false })+ mockInvalidateTriggers.mockReset()+ mockInvalidDataSourceList.mockReset()+ })++ it('should return the noop installation state for non plugin-dependent nodes', () => {+ const { result } = renderWorkflowHook(() =>+ useNodePluginInstallation({+ type: BlockEnum.LLM,+ title: 'LLM',+ desc: '',+ } as CommonNodeType),+ )++ expect(result.current).toEqual({+ isChecking: false,+ isMissing: false,+ uniqueIdentifier: undefined,+ canInstall: false,+ onInstallSuccess: expect.any(Function),+ shouldDim: false,+ })+ })++ it('should report loading and invalidate built-in tools while the collection is resolving', () => {+ const invalidateTools = vi.fn()+ mockBuiltInTools.mockReturnValue({ data: undefined, isLoading: true })+ mockInvalidToolsByType.mockReturnValue(invalidateTools)++ const { result } = renderWorkflowHook(() => useNodePluginInstallation(makeToolNode()))++ expect(mockBuiltInTools).toHaveBeenCalledWith(true)+ expect(result.current.isChecking).toBe(true)+ expect(result.current.isMissing).toBe(false)+ expect(result.current.uniqueIdentifier).toBe('[email protected]')+ expect(result.current.canInstall).toBe(true)+ expect(result.current.shouldDim).toBe(true)++ act(() => {+ result.current.onInstallSuccess()+ })++ expect(invalidateTools).toHaveBeenCalled()+ })++ it.each([+ [CollectionType.custom, mockCustomTools],+ [CollectionType.workflow, mockWorkflowTools],+ [CollectionType.mcp, mockMcpTools],+ ])('should resolve matched %s tool collections without dimming', (providerType, hookMock) => {+ hookMock.mockReturnValue({ data: [matchedTool], isLoading: false })++ const { result } = renderWorkflowHook(() =>+ useNodePluginInstallation(makeToolNode({ provider_type: providerType })),+ )++ expect(result.current.isChecking).toBe(false)+ expect(result.current.isMissing).toBe(false)+ expect(result.current.shouldDim).toBe(false)+ })++ it('should keep unknown tool collection types installable without collection state', () => {+ const { result } = renderWorkflowHook(() =>+ useNodePluginInstallation(makeToolNode({+ provider_type: 'unknown' as CollectionType,+ plugin_unique_identifier: undefined,+ plugin_id: undefined,+ provider_id: 'legacy-provider',+ })),+ )++ expect(result.current.isChecking).toBe(false)+ expect(result.current.isMissing).toBe(false)+ expect(result.current.uniqueIdentifier).toBe('legacy-provider')+ expect(result.current.canInstall).toBe(false)+ expect(result.current.shouldDim).toBe(false)+ })++ it('should flag missing trigger plugins and invalidate trigger data after installation', () => {+ mockTriggerPlugins.mockReturnValue({ data: [matchedTriggerProvider], isLoading: false })++ const { result } = renderWorkflowHook(() =>+ useNodePluginInstallation(makeTriggerNode({+ provider_id: 'missing-trigger',+ provider_name: 'missing-trigger',+ plugin_id: 'missing-trigger',+ })),+ )++ expect(mockTriggerPlugins).toHaveBeenCalledWith(true)+ expect(result.current.isChecking).toBe(false)+ expect(result.current.isMissing).toBe(true)+ expect(result.current.shouldDim).toBe(true)++ act(() => {+ result.current.onInstallSuccess()+ })++ expect(mockInvalidateTriggers).toHaveBeenCalled()+ })++ it('should treat the trigger plugin list as still loading when it has not resolved yet', () => {+ mockTriggerPlugins.mockReturnValue({ data: undefined, isLoading: true })++ const { result } = renderWorkflowHook(() =>+ useNodePluginInstallation(makeTriggerNode({ plugin_unique_identifier: undefined, plugin_id: 'trigger-plugin' })),+ )++ expect(result.current.isChecking).toBe(true)+ expect(result.current.isMissing).toBe(false)+ expect(result.current.uniqueIdentifier).toBe('trigger-plugin')+ expect(result.current.canInstall).toBe(false)+ expect(result.current.shouldDim).toBe(true)+ })++ it('should track missing and matched data source providers based on workflow store state', () => {+ const missingRender = renderWorkflowHook(+ () => useNodePluginInstallation(makeDataSourceNode({+ provider_name: 'missing-provider',+ plugin_id: 'missing-plugin',+ plugin_unique_identifier: '[email protected]',+ })),+ {+ initialStoreState: {+ dataSourceList: [matchedDataSource] as never,+ },+ },+ )++ expect(missingRender.result.current.isChecking).toBe(false)+ expect(missingRender.result.current.isMissing).toBe(true)+ expect(missingRender.result.current.shouldDim).toBe(true)++ const matchedRender = renderWorkflowHook(+ () => useNodePluginInstallation(makeDataSourceNode()),+ {+ initialStoreState: {+ dataSourceList: [matchedDataSource] as never,+ },+ },+ )++ expect(matchedRender.result.current.isMissing).toBe(false)+ expect(matchedRender.result.current.shouldDim).toBe(false)++ act(() => {+ matchedRender.result.current.onInstallSuccess()+ })++ expect(mockInvalidDataSourceList).toHaveBeenCalled()+ })++ it('should keep data sources in checking state before the list is loaded', () => {+ const { result } = renderWorkflowHook(() => useNodePluginInstallation(makeDataSourceNode()))++ expect(result.current.isChecking).toBe(true)+ expect(result.current.isMissing).toBe(false)+ expect(result.current.shouldDim).toBe(true)+ })+})diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.tsindex dd1d012aed3..029892c4d13 100644--- a/web/app/components/workflow/hooks/use-checklist.ts+++ b/web/app/components/workflow/hooks/use-checklist.ts@@ -8,14 +8,19 @@ import type {CommonEdgeType,CommonNodeType,Edge,+ ModelConfig,Node,ValueSelector,} from '../types'+import type { ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { Emoji } from '@/app/components/tools/types'import type { DataSet } from '@/models/datasets'import type { I18nKeysWithPrefix } from '@/types/i18n'+import { useQueries, useQueryClient } from '@tanstack/react-query'+import isDeepEqual from 'fast-deep-equal'import {useCallback,+ useEffect,useMemo,useRef,} from 'react'@@ -28,11 +33,14 @@ import { useModelList } from '@/app/components/header/account-setting/model-provimport useNodes from '@/app/components/workflow/store/workflow/use-nodes'import { MAX_TREE_DEPTH } from '@/config'import { useGetLanguage } from '@/context/i18n'+import { useProviderContextSelector } from '@/context/provider-context'+import { consoleQuery } from '@/service/client'import { fetchDatasets } from '@/service/datasets'import { useStrategyProviders } from '@/service/use-strategy'import {useAllBuiltInTools,useAllCustomTools,+ useAllMCPTools,useAllWorkflowTools,} from '@/service/use-tools'import { useAllTriggerPlugins } from '@/service/use-triggers'@@ -46,6 +54,8 @@ import {useNodesMetaData,} from '../hooks'import { getNodeUsedVars, isSpecialVar } from '../nodes/_base/components/variable/utils'+import { IndexMethodEnum } from '../nodes/knowledge-base/types'+import { getLLMModelIssue, isLLMModelProviderInstalled, LLMModelIssueCode } from '../nodes/llm/utils'import {useStore,useWorkflowStore,@@ -56,6 +66,8 @@ import {getToolCheckParams,getValidTreeNodes,} from '../utils'+import { extractPluginId } from '../utils/plugin'+import { isNodePluginMissing } from '../utils/plugin-install-check'import { getTriggerCheckParams } from '../utils/trigger'import useNodesAvailableVarList, { useGetNodesAvailableVarList } from './use-nodes-available-var-list'@@ -65,9 +77,11 @@ export type ChecklistItem = {title: stringtoolIcon?: string | EmojiunConnected?: boolean- errorMessage?: string+ errorMessages: string[]canNavigate: booleandisableGoTo?: boolean+ isPluginMissing?: boolean+ pluginUniqueIdentifier?: string}const START_NODE_TYPES: BlockEnum[] = [@@ -77,13 +91,6 @@ const START_NODE_TYPES: BlockEnum[] = [BlockEnum.TriggerPlugin,]-// Node types that depend on plugins-const PLUGIN_DEPENDENT_TYPES: BlockEnum[] = [- BlockEnum.Tool,- BlockEnum.DataSource,- BlockEnum.TriggerPlugin,-]-export const useChecklist = (nodes: Node[], edges: Edge[]) => {const { t } = useTranslation()const language = useGetLanguage()@@ -91,6 +98,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {const { data: buildInTools } = useAllBuiltInTools()const { data: customTools } = useAllCustomTools()const { data: workflowTools } = useAllWorkflowTools()+ const { data: mcpTools } = useAllMCPTools()const dataSourceList = useStore(s => s.dataSourceList)const { data: strategyProviders } = useStrategyProviders()const { data: triggerPlugins } = useAllTriggerPlugins()@@ -98,10 +106,49 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {const getToolIcon = useGetToolIcon()const appMode = useAppStore.getState().appDetail?.modeconst shouldCheckStartNode = appMode === AppModeEnum.WORKFLOW || appMode === AppModeEnum.ADVANCED_CHAT+ const modelProviders = useProviderContextSelector(s => s.modelProviders)+ const workflowStore = useWorkflowStore()const map = useNodesAvailableVarList(nodes)const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)+ const knowledgeBaseEmbeddingProviders = useMemo(() => {+ const providers = new Set<string>()++ nodes.forEach((node) => {+ if (node.type !== CUSTOM_NODE || node.data.type !== BlockEnum.KnowledgeBase)+ return++ const knowledgeBaseData = node.data as CommonNodeType<KnowledgeBaseNodeType>+ if (knowledgeBaseData.indexing_technique !== IndexMethodEnum.QUALIFIED)+ return++ const provider = knowledgeBaseData.embedding_model_provider+ if (provider)+ providers.add(provider)+ })++ return [...providers]+ }, [nodes])+ const knowledgeBaseProviderModelMap = useQueries({+ queries: knowledgeBaseEmbeddingProviders.map(provider =>+ consoleQuery.modelProviders.models.queryOptions({+ input: { params: { provider } },+ enabled: !!provider,+ refetchOnWindowFocus: false,+ select: response => response.data,+ }),+ ),+ combine: (results) => {+ const modelMap: Partial<Record<string, ModelItem[]>> = {}+ knowledgeBaseEmbeddingProviders.forEach((provider, index) => {+ const models = results[index]?.data+ if (models)+ modelMap[provider] = models+ })+ return modelMap+ },+ })const getCheckData = useCallback((data: CommonNodeType<{}>) => {let checkData = data@@ -118,19 +165,22 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {} as CommonNodeType<KnowledgeRetrievalNodeType>}else if (data.type === BlockEnum.KnowledgeBase) {+ const modelProviderName = (data as CommonNodeType<KnowledgeBaseNodeType>).embedding_model_providercheckData = {...data,_embeddingModelList: embeddingModelList,+ _embeddingProviderModelList: modelProviderName ? knowledgeBaseProviderModelMap[modelProviderName] : undefined,_rerankModelList: rerankModelList,} as CommonNodeType<KnowledgeBaseNodeType>}return checkData- }, [datasetsDetail, embeddingModelList, rerankModelList])+ }, [datasetsDetail, embeddingModelList, knowledgeBaseProviderModelMap, rerankModelList])const needWarningNodes = useMemo<ChecklistItem[]>(() => {const list: ChecklistItem[] = []const filteredNodes = nodes.filter(node => node.type === CUSTOM_NODE)const { validNodes } = getValidTreeNodes(filteredNodes, edges)+ const installedPluginIds = new Set(modelProviders.map(p => extractPluginId(p.provider)))for (let i = 0; i < filteredNodes.length; i++) {const node = filteredNodes[i]@@ -166,41 +216,50 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {if (node.type === CUSTOM_NODE) {const checkData = getCheckData(node.data)const validator = nodesExtraData?.[node.data.type as BlockEnum]?.checkValid- const isPluginMissing = PLUGIN_DEPENDENT_TYPES.includes(node.data.type as BlockEnum) && node.data._pluginInstallLocked+ const isPluginMissing = isNodePluginMissing(node.data, { builtInTools: buildInTools, customTools, workflowTools, mcpTools, triggerPlugins, dataSourceList })- // Check if plugin is installed for plugin-dependent nodes first- let errorMessage: string | undefined- if (isPluginMissing)- errorMessage = t('nodes.common.pluginNotInstalled', { ns: 'workflow' })- else if (validator)- errorMessage = validator(checkData, t, moreDataForCheckValid).errorMessage+ const errorMessages: string[] = []- if (!errorMessage) {- const availableVars = map[node.id].availableVars+ if (isPluginMissing) {+ errorMessages.push(t('nodes.common.pluginNotInstalled', { ns: 'workflow' }))+ }+ else {+ if (node.data.type === BlockEnum.LLM) {+ const modelProvider = (node.data as CommonNodeType<{ model?: ModelConfig }>).model?.provider+ const modelIssue = getLLMModelIssue({+ modelProvider,+ isModelProviderInstalled: isLLMModelProviderInstalled(modelProvider, installedPluginIds),+ })+ if (modelIssue === LLMModelIssueCode.providerPluginUnavailable)+ errorMessages.push(t('errorMsg.configureModel', { ns: 'workflow' }))+ }+ if (validator) {+ const validationError = validator(checkData, t, moreDataForCheckValid).errorMessage+ if (validationError)+ errorMessages.push(validationError)+ }++ const availableVars = map[node.id].availableVars+ let hasInvalidVar = falsefor (const variable of usedVars) {- const isSpecialVars = isSpecialVar(variable[0])- if (!isSpecialVars) {- const usedNode = availableVars.find(v => v.nodeId === variable?.[0])- if (usedNode) {- const usedVar = usedNode.vars.find(v => v.variable === variable?.[1])- if (!usedVar)- errorMessage = t('errorMsg.invalidVariable', { ns: 'workflow' })- }- else {- errorMessage = t('errorMsg.invalidVariable', { ns: 'workflow' })- }- }+ if (hasInvalidVar)+ break+ if (isSpecialVar(variable[0]))+ continue+ const usedNode = availableVars.find(v => v.nodeId === variable?.[0])+ if (!usedNode || !usedNode.vars.some(v => v.variable === variable?.[1]))+ hasInvalidVar = true}+ if (hasInvalidVar)+ errorMessages.push(t('errorMsg.invalidVariable', { ns: 'workflow' }))}- // Start nodes and Trigger nodes should not show unConnected error if they have validation errors- // or if they are valid start nodes (even without incoming connections)const isStartNodeMeta = nodesExtraData?.[node.data.type as BlockEnum]?.metaData.isStart ?? falseconst canSkipConnectionCheck = shouldCheckStartNode ? isStartNodeMeta : true- const isUnconnected = !validNodes.find(n => n.id === node.id)- const shouldShowError = errorMessage || (isUnconnected && !canSkipConnectionCheck)+ const isUnconnected = !validNodes.some(n => n.id === node.id)+ const shouldShowError = errorMessages.length > 0 || (isUnconnected && !canSkipConnectionCheck)if (shouldShowError) {list.push({@@ -209,9 +268,13 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {title: node.data.title,toolIcon,unConnected: isUnconnected && !canSkipConnectionCheck,- errorMessage,+ errorMessages,canNavigate: !isPluginMissing,disableGoTo: isPluginMissing,+ isPluginMissing,+ pluginUniqueIdentifier: isPluginMissing+ ? (node.data as { plugin_unique_identifier?: string }).plugin_unique_identifier+ : undefined,})}}@@ -225,7 +288,7 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {id: 'start-node-required',type: BlockEnum.Start,title: t('panel.startNode', { ns: 'workflow' }),- errorMessage: t('common.needStartNode', { ns: 'workflow' }),+ errorMessages: [t('common.needStartNode', { ns: 'workflow' })],canNavigate: false,})}@@ -234,22 +297,27 @@ export const useChecklist = (nodes: Node[], edges: Edge[]) => {const isRequiredNodesType = Object.keys(nodesExtraData!).filter((key: any) => (nodesExtraData as any)[key].metaData.isRequired)isRequiredNodesType.forEach((type: string) => {- if (!filteredNodes.find(node => node.data.type === type)) {+ if (!filteredNodes.some(node => node.data.type === type)) {list.push({id: `${type}-need-added`,type,- // We don't have enough type info for t() here-title: t(`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>, { ns: 'workflow' }),-- errorMessage: t('common.needAdd', { ns: 'workflow', node: t(`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>, { ns: 'workflow' }) }),+ errorMessages: [t('common.needAdd', { ns: 'workflow', node: t(`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>, { ns: 'workflow' }) })],canNavigate: false,})}})return list- }, [nodes, edges, shouldCheckStartNode, nodesExtraData, buildInTools, customTools, workflowTools, language, dataSourceList, triggerPlugins, getToolIcon, strategyProviders, getCheckData, t, map])+ }, [nodes, edges, shouldCheckStartNode, nodesExtraData, buildInTools, customTools, workflowTools, mcpTools, language, dataSourceList, triggerPlugins, getToolIcon, strategyProviders, getCheckData, t, map, modelProviders])++ useEffect(() => {+ const currentChecklistItems = workflowStore.getState().checklistItems+ if (isDeepEqual(currentChecklistItems, needWarningNodes))+ return++ workflowStore.setState({ checklistItems: needWarningNodes })+ }, [needWarningNodes, workflowStore])return needWarningNodes}@@ -258,11 +326,13 @@ export const useChecklistBeforePublish = () => {const { t } = useTranslation()const language = useGetLanguage()const { notify } = useToastContext()+ const queryClient = useQueryClient()const store = useStoreApi()const { nodesMap: nodesExtraData } = useNodesMetaData()const { data: strategyProviders } = useStrategyProviders()+ const modelProviders = useProviderContextSelector(s => s.modelProviders)const updateDatasetsDetail = useDatasetsDetailStore(s => s.updateDatasetsDetail)- const updateTime = useRef(0)+ const updateTimeRef = useRef(0)const workflowStore = useWorkflowStore()const { getNodesAvailableVarList } = useGetNodesAvailableVarList()const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)@@ -273,7 +343,11 @@ export const useChecklistBeforePublish = () => {const appMode = useAppStore.getState().appDetail?.modeconst shouldCheckStartNode = appMode === AppModeEnum.WORKFLOW || appMode === AppModeEnum.ADVANCED_CHAT- const getCheckData = useCallback((data: CommonNodeType<{}>, datasets: DataSet[]) => {+ const getCheckData = useCallback((+ data: CommonNodeType<object>,+ datasets: DataSet[],+ embeddingProviderModelMap?: Partial<Record<string, ModelItem[]>>,+ ) => {let checkData = dataif (data.type === BlockEnum.KnowledgeRetrieval) {const datasetIds = (data as CommonNodeType<KnowledgeRetrievalNodeType>).dataset_ids@@ -292,9 +366,11 @@ export const useChecklistBeforePublish = () => {} as CommonNodeType<KnowledgeRetrievalNodeType>}else if (data.type === BlockEnum.KnowledgeBase) {+ const modelProviderName = (data as CommonNodeType<KnowledgeBaseNodeType>).embedding_model_providercheckData = {...data,_embeddingModelList: embeddingModelList,+ _embeddingProviderModelList: modelProviderName ? embeddingProviderModelMap?.[modelProviderName] : undefined,_rerankModelList: rerankModelList,} as CommonNodeType<KnowledgeBaseNodeType>}@@ -317,24 +393,67 @@ export const useChecklistBeforePublish = () => {notify({ type: 'error', message: t('common.maxTreeDepth', { ns: 'workflow', depth: MAX_TREE_DEPTH }) })return false}- // Before publish, we need to fetch datasets detail, in case of the settings of datasets have been changed- const knowledgeRetrievalNodes = filteredNodes.filter(node => node.data.type === BlockEnum.KnowledgeRetrieval)- const allDatasetIds = knowledgeRetrievalNodes.reduce<string[]>((acc, node) => {- return Array.from(new Set([...acc, ...(node.data as CommonNodeType<KnowledgeRetrievalNodeType>).dataset_ids]))- }, [])- let datasets: DataSet[] = []- if (allDatasetIds.length > 0) {- updateTime.current = updateTime.current + 1- const currUpdateTime = updateTime.current- const { data: datasetsDetail } = await fetchDatasets({ url: '/datasets', params: { page: 1, ids: allDatasetIds } })- if (datasetsDetail && datasetsDetail.length > 0) {- // avoid old data to overwrite the new data- if (currUpdateTime < updateTime.current)- return false- datasets = datasetsDetail++ const knowledgeBaseEmbeddingProviders = [...new Set(+ filteredNodes+ .filter(node => node.data.type === BlockEnum.KnowledgeBase)+ .map(node => node.data as CommonNodeType<KnowledgeBaseNodeType>)+ .filter(node => node.indexing_technique === IndexMethodEnum.QUALIFIED)+ .map(node => node.embedding_model_provider)+ .filter((provider): provider is string => !!provider),+ )]++ const fetchKnowledgeBaseProviderModelMap = async () => {+ const modelMap: Partial<Record<string, ModelItem[]>> = {}+ await Promise.all(knowledgeBaseEmbeddingProviders.map(async (provider) => {+ try {+ const modelList = await queryClient.fetchQuery(+ consoleQuery.modelProviders.models.queryOptions({+ input: { params: { provider } },+ }),+ )++ if (modelList.data)+ modelMap[provider] = modelList.data+ }+ catch {+ }+ }))+ return modelMap+ }++ const fetchLatestDatasets = async (): Promise<DataSet[] | null> => {+ const allDatasetIds = new Set<string>()+ filteredNodes.forEach((node) => {+ if (node.data.type !== BlockEnum.KnowledgeRetrieval)+ return++ const datasetIds = (node.data as CommonNodeType<KnowledgeRetrievalNodeType>).dataset_ids+ datasetIds.forEach(id => allDatasetIds.add(id))+ })++ if (allDatasetIds.size === 0)+ return []++ updateTimeRef.current = updateTimeRef.current + 1+ const currUpdateTime = updateTimeRef.current+ const { data: datasetsDetail } = await fetchDatasets({ url: '/datasets', params: { page: 1, ids: [...allDatasetIds] } })+ if (currUpdateTime < updateTimeRef.current)+ return null+ if (datasetsDetail?.length)updateDatasetsDetail(datasetsDetail)- }+ return datasetsDetail || []}++ const [embeddingProviderModelMap, datasets] = await Promise.all([+ fetchKnowledgeBaseProviderModelMap(),+ fetchLatestDatasets(),+ ])++ if (datasets === null)+ return false++ const installedPluginIds = new Set(modelProviders.map(p => extractPluginId(p.provider)))const map = getNodesAvailableVarList(nodes)for (let i = 0; i < filteredNodes.length; i++) {const node = filteredNodes[i]@@ -361,7 +480,20 @@ export const useChecklistBeforePublish = () => {else {usedVars = getNodeUsedVars(node).filter(v => v.length > 0)}- const checkData = getCheckData(node.data, datasets)++ if (node.data.type === BlockEnum.LLM) {+ const modelProvider = (node.data as CommonNodeType<{ model?: ModelConfig }>).model?.provider+ const modelIssue = getLLMModelIssue({+ modelProvider,+ isModelProviderInstalled: isLLMModelProviderInstalled(modelProvider, installedPluginIds),+ })+ if (modelIssue === LLMModelIssueCode.providerPluginUnavailable) {+ notify({ type: 'error', message: `[${node.data.title}] ${t('errorMsg.configureModel', { ns: 'workflow' })}` })+ return false+ }+ }++ const checkData = getCheckData(node.data, datasets, embeddingProviderModelMap)const { errorMessage } = nodesExtraData![node.data.type as BlockEnum].checkValid(checkData, t, moreDataForCheckValid)if (errorMessage) {@@ -391,7 +523,7 @@ export const useChecklistBeforePublish = () => {const isStartNodeMeta = nodesExtraData?.[node.data.type as BlockEnum]?.metaData.isStart ?? falseconst canSkipConnectionCheck = shouldCheckStartNode ? isStartNodeMeta : true- const isUnconnected = !validNodes.find(n => n.id === node.id)+ const isUnconnected = !validNodes.some(n => n.id === node.id)if (isUnconnected && !canSkipConnectionCheck) {notify({ type: 'error', message: `[${node.data.title}] ${t('common.needConnectTip', { ns: 'workflow' })}` })@@ -412,14 +544,14 @@ export const useChecklistBeforePublish = () => {for (let i = 0; i < isRequiredNodesType.length; i++) {const type = isRequiredNodesType[i]- if (!filteredNodes.find(node => node.data.type === type)) {+ if (!filteredNodes.some(node => node.data.type === type)) {notify({ type: 'error', message: t('common.needAdd', { ns: 'workflow', node: t(`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>, { ns: 'workflow' }) }) })return false}}return true- }, [store, workflowStore, getNodesAvailableVarList, shouldCheckStartNode, nodesExtraData, notify, t, updateDatasetsDetail, buildInTools, customTools, workflowTools, language, getCheckData, strategyProviders])+ }, [store, workflowStore, getNodesAvailableVarList, shouldCheckStartNode, nodesExtraData, notify, t, updateDatasetsDetail, buildInTools, customTools, workflowTools, language, getCheckData, queryClient, strategyProviders, modelProviders])return {handleCheckBeforePublish,diff --git a/web/app/components/workflow/hooks/use-node-plugin-installation.ts b/web/app/components/workflow/hooks/use-node-plugin-installation.tsindex d275759cc0d..7c88685c985 100644--- a/web/app/components/workflow/hooks/use-node-plugin-installation.ts+++ b/web/app/components/workflow/hooks/use-node-plugin-installation.ts@@ -16,11 +16,15 @@ import {useAllTriggerPlugins,useInvalidateAllTriggerPlugins,} from '@/service/use-triggers'-import { canFindTool } from '@/utils'import { useStore } from '../store'import { BlockEnum } from '../types'+import {+ matchDataSource,+ matchToolInCollection,+ matchTriggerProvider,+} from '../utils/plugin-install-check'-type InstallationState = {+export type InstallationState = {isChecking: booleanisMissing: booleanuniqueIdentifier?: string@@ -29,14 +33,31 @@ type InstallationState = {shouldDim: boolean}-const useToolInstallation = (data: ToolNodeType): InstallationState => {- const builtInQuery = useAllBuiltInTools()- const customQuery = useAllCustomTools()- const workflowQuery = useAllWorkflowTools()- const mcpQuery = useAllMCPTools()- const invalidateTools = useInvalidToolsByType(data.provider_type)+const NOOP_INSTALLATION: InstallationState = {+ isChecking: false,+ isMissing: false,+ uniqueIdentifier: undefined,+ canInstall: false,+ onInstallSuccess: () => undefined,+ shouldDim: false,+}++const useToolInstallation = (data: ToolNodeType, enabled: boolean): InstallationState => {+ const isBuiltIn = enabled && data.provider_type === CollectionType.builtIn+ const isCustom = enabled && data.provider_type === CollectionType.custom+ const isWorkflow = enabled && data.provider_type === CollectionType.workflow+ const isMcp = enabled && data.provider_type === CollectionType.mcp++ const builtInQuery = useAllBuiltInTools(isBuiltIn)+ const customQuery = useAllCustomTools(isCustom)+ const workflowQuery = useAllWorkflowTools(isWorkflow)+ const mcpQuery = useAllMCPTools(isMcp)+ const invalidateTools = useInvalidToolsByType(enabled ? data.provider_type : undefined)const collectionInfo = useMemo(() => {+ if (!enabled)+ return undefined+switch (data.provider_type) {case CollectionType.builtIn:return {@@ -62,6 +83,7 @@ const useToolInstallation = (data: ToolNodeType): InstallationState => {return undefined}}, [+ enabled,builtInQuery.data,builtInQuery.isLoading,customQuery.data,@@ -77,20 +99,13 @@ const useToolInstallation = (data: ToolNodeType): InstallationState => {const isLoading = collectionInfo?.isLoading ?? falseconst isResolved = !!collectionInfo && !isLoading+ const { plugin_id, provider_id, provider_name } = dataconst matchedCollection = useMemo(() => {if (!collection || !collection.length)return undefined- return collection.find((toolWithProvider) => {- if (data.plugin_id && toolWithProvider.plugin_id === data.plugin_id)- return true- if (canFindTool(toolWithProvider.id, data.provider_id))- return true- if (toolWithProvider.name === data.provider_name)- return true- return false- })- }, [collection, data.plugin_id, data.provider_id, data.provider_name])+ return matchToolInCollection(collection, { plugin_id, provider_id, provider_name })+ }, [collection, plugin_id, provider_id, provider_name])const uniqueIdentifier = data.plugin_unique_identifier || data.plugin_id || data.provider_idconst canInstall = Boolean(data.plugin_unique_identifier)@@ -112,28 +127,20 @@ const useToolInstallation = (data: ToolNodeType): InstallationState => {}}-const useTriggerInstallation = (data: PluginTriggerNodeType): InstallationState => {- const triggerPluginsQuery = useAllTriggerPlugins()+const useTriggerInstallation = (data: PluginTriggerNodeType, enabled: boolean): InstallationState => {+ const triggerPluginsQuery = useAllTriggerPlugins(enabled)const invalidateTriggers = useInvalidateAllTriggerPlugins()const triggerProviders = triggerPluginsQuery.dataconst isLoading = triggerPluginsQuery.isLoading+ const { plugin_id, provider_id, provider_name } = dataconst matchedProvider = useMemo(() => {if (!triggerProviders || !triggerProviders.length)return undefined- return triggerProviders.find(provider =>- provider.name === data.provider_name- || provider.id === data.provider_id- || (data.plugin_id && provider.plugin_id === data.plugin_id),- )- }, [- data.plugin_id,- data.provider_id,- data.provider_name,- triggerProviders,- ])+ return matchTriggerProvider(triggerProviders, { plugin_id, provider_id, provider_name })+ }, [plugin_id, provider_id, provider_name, triggerProviders])const uniqueIdentifier = data.plugin_unique_identifier || data.plugin_id || data.provider_idconst canInstall = Boolean(data.plugin_unique_identifier)@@ -154,24 +161,17 @@ const useTriggerInstallation = (data: PluginTriggerNodeType): InstallationState}}-const useDataSourceInstallation = (data: DataSourceNodeType): InstallationState => {+const useDataSourceInstallation = (data: DataSourceNodeType, _enabled: boolean): InstallationState => {const dataSourceList = useStore(s => s.dataSourceList)const invalidateDataSourceList = useInvalidDataSourceList()+ const { plugin_unique_identifier, plugin_id, provider_name } = dataconst matchedPlugin = useMemo(() => {if (!dataSourceList || !dataSourceList.length)return undefined- return dataSourceList.find((item) => {- if (data.plugin_unique_identifier && item.plugin_unique_identifier === data.plugin_unique_identifier)- return true- if (data.plugin_id && item.plugin_id === data.plugin_id)- return true- if (data.provider_name && item.provider === data.provider_name)- return true- return false- })- }, [data.plugin_id, data.plugin_unique_identifier, data.provider_name, dataSourceList])+ return matchDataSource(dataSourceList, { plugin_unique_identifier, plugin_id, provider_name })+ }, [dataSourceList, plugin_id, plugin_unique_identifier, provider_name])const uniqueIdentifier = data.plugin_unique_identifier || data.plugin_idconst canInstall = Boolean(data.plugin_unique_identifier)@@ -195,25 +195,20 @@ const useDataSourceInstallation = (data: DataSourceNodeType): InstallationState}export const useNodePluginInstallation = (data: CommonNodeType): InstallationState => {- const toolInstallation = useToolInstallation(data as ToolNodeType)- const triggerInstallation = useTriggerInstallation(data as PluginTriggerNodeType)- const dataSourceInstallation = useDataSourceInstallation(data as DataSourceNodeType)-- switch (data.type as BlockEnum) {- case BlockEnum.Tool:- return toolInstallation- case BlockEnum.TriggerPlugin:- return triggerInstallation- case BlockEnum.DataSource:- return dataSourceInstallation- default:- return {- isChecking: false,- isMissing: false,- uniqueIdentifier: undefined,- canInstall: false,- onInstallSuccess: () => undefined,- shouldDim: false,- }- }+ const isTool = data.type === BlockEnum.Tool+ const isTrigger = data.type === BlockEnum.TriggerPlugin+ const isDataSource = data.type === BlockEnum.DataSource++ const toolInstallation = useToolInstallation(data as ToolNodeType, isTool)+ const triggerInstallation = useTriggerInstallation(data as PluginTriggerNodeType, isTrigger)+ const dataSourceInstallation = useDataSourceInstallation(data as DataSourceNodeType, isDataSource)++ if (isTool)+ return toolInstallation+ if (isTrigger)+ return triggerInstallation+ if (isDataSource)+ return dataSourceInstallation++ return NOOP_INSTALLATION}diff --git a/web/app/components/workflow/hooks/use-nodes-interactions.ts b/web/app/components/workflow/hooks/use-nodes-interactions.tsindex b0dd43eb1d1..cd35d2310f9 100644--- a/web/app/components/workflow/hooks/use-nodes-interactions.ts+++ b/web/app/components/workflow/hooks/use-nodes-interactions.ts@@ -420,8 +420,6 @@ export const useNodesInteractions = () => {returnif (node.data.type === BlockEnum.DataSourceEmpty)return- if (node.data._pluginInstallLocked)- returnhandleNodeSelect(node.id)},[handleNodeSelect],diff --git a/web/app/components/workflow/nodes/_base/components/field.spec.tsx b/web/app/components/workflow/nodes/_base/components/field.spec.tsxnew file mode 100644index 00000000000..a34a862118e--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/field.spec.tsx@@ -0,0 +1,56 @@+import { fireEvent, render, screen } from '@testing-library/react'+import Field from './field'++vi.mock('@/app/components/base/tooltip', () => ({+ default: ({ popupContent }: { popupContent: React.ReactNode }) => <div>{popupContent}</div>,+}))++describe('Field', () => {+ it('should render subtitle styling, tooltip, operations, warning dot and required marker', () => {+ const { container } = render(+ <Field+ title="Knowledge"+ tooltip="tooltip text"+ operations={<button type="button">operation</button>}+ required+ warningDot+ isSubTitle+ />,+ )++ expect(screen.getByText('Knowledge')).toBeInTheDocument()+ expect(screen.getByText('tooltip text')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'operation' })).toBeInTheDocument()+ expect(screen.getByText('*')).toBeInTheDocument()+ expect(container.querySelector('.system-xs-medium-uppercase')).not.toBeNull()+ expect(container.querySelector('.bg-text-warning-secondary')).not.toBeNull()+ })++ it('should toggle folded children when supportFold is enabled', () => {+ const { container } = render(+ <Field title="Foldable" supportFold>+ <div>folded content</div>+ </Field>,+ )++ expect(screen.queryByText('folded content')).not.toBeInTheDocument()++ fireEvent.click(screen.getByText('Foldable').closest('.cursor-pointer')!)+ expect(screen.getByText('folded content')).toBeInTheDocument()+ expect(container.querySelector('svg')).toHaveStyle({ transform: 'rotate(0deg)' })++ fireEvent.click(screen.getByText('Foldable').closest('.cursor-pointer')!)+ expect(screen.queryByText('folded content')).not.toBeInTheDocument()+ })++ it('should render inline children without folding support', () => {+ const { container } = render(+ <Field title="Inline" inline>+ <div>always visible</div>+ </Field>,+ )++ expect(screen.getByText('always visible')).toBeInTheDocument()+ expect(container.firstChild).toHaveClass('flex')+ })+})diff --git a/web/app/components/workflow/nodes/_base/components/field.tsx b/web/app/components/workflow/nodes/_base/components/field.tsxindex 948dcb603c2..3caa107c791 100644--- a/web/app/components/workflow/nodes/_base/components/field.tsx+++ b/web/app/components/workflow/nodes/_base/components/field.tsx@@ -18,6 +18,7 @@ type Props = {operations?: React.JSX.Elementinline?: booleanrequired?: boolean+ warningDot?: boolean}const Field: FC<Props> = ({@@ -30,6 +31,7 @@ const Field: FC<Props> = ({inline,supportFold,required,+ warningDot,}) => {const [fold, {toggle: toggleFold,@@ -41,7 +43,10 @@ const Field: FC<Props> = ({className={cn('flex items-center justify-between', supportFold && 'cursor-pointer')}><div className="flex h-6 items-center">- <div className={cn(isSubTitle ? 'system-xs-medium-uppercase text-text-tertiary' : 'system-sm-semibold-uppercase text-text-secondary')}>+ <div className={cn('relative', isSubTitle ? 'text-text-tertiary system-xs-medium-uppercase' : 'text-text-secondary system-sm-semibold-uppercase')}>+ {warningDot && (+ <span className="absolute -left-[9px] top-1/2 size-[5px] -translate-y-1/2 rounded-full bg-text-warning-secondary" />+ )}{title}{' '}{required && <span className="text-text-destructive">*</span>}diff --git a/web/app/components/workflow/nodes/_base/components/layout/field-title.spec.tsx b/web/app/components/workflow/nodes/_base/components/layout/field-title.spec.tsxnew file mode 100644index 00000000000..3b1be0040e6--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/layout/field-title.spec.tsx@@ -0,0 +1,67 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { FieldTitle } from './field-title'++vi.mock('@/app/components/base/ui/tooltip', () => ({+ Tooltip: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ TooltipTrigger: ({ render }: { render: React.ReactNode }) => <>{render}</>,+ TooltipContent: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+}))++describe('FieldTitle', () => {+ it('should render title, subtitle, operation, tooltip and warning dot', () => {+ render(+ <FieldTitle+ title="Embedding"+ subTitle={<div>subtitle</div>}+ operation={<button type="button">action</button>}+ tooltip="Tooltip copy"+ warningDot+ />,+ )++ expect(screen.getByText('Embedding')).toBeInTheDocument()+ expect(screen.getByText('subtitle')).toBeInTheDocument()+ expect(screen.getByText('Tooltip copy')).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'action' })).toBeInTheDocument()+ expect(document.querySelector('.bg-text-warning-secondary')).not.toBeNull()+ })++ it('should toggle local collapsed state and notify onCollapse when enabled', () => {+ const onCollapse = vi.fn()+ const { container } = render(+ <FieldTitle+ title="Models"+ showArrow+ onCollapse={onCollapse}+ />,+ )++ const header = screen.getByText('Models').closest('.group\\/collapse')+ const arrow = container.querySelector('[aria-hidden="true"]')++ expect(arrow).toHaveClass('rotate-[270deg]')++ fireEvent.click(header!)++ expect(onCollapse).toHaveBeenCalledWith(false)+ expect(arrow).not.toHaveClass('rotate-[270deg]')+ })++ it('should respect controlled collapsed state and ignore clicks when disabled', () => {+ const onCollapse = vi.fn()+ const { container } = render(+ <FieldTitle+ title="Controlled"+ showArrow+ collapsed={false}+ disabled+ onCollapse={onCollapse}+ />,+ )++ fireEvent.click(screen.getByText('Controlled').closest('.group\\/collapse')!)++ expect(onCollapse).not.toHaveBeenCalled()+ expect(container.querySelector('[aria-hidden="true"]')).not.toHaveClass('rotate-[270deg]')+ })+})diff --git a/web/app/components/workflow/nodes/_base/components/layout/field-title.tsx b/web/app/components/workflow/nodes/_base/components/layout/field-title.tsxindex e5e8fe950d0..856ef48e5d7 100644--- a/web/app/components/workflow/nodes/_base/components/layout/field-title.tsx+++ b/web/app/components/workflow/nodes/_base/components/layout/field-title.tsx@@ -3,8 +3,7 @@ import {memo,useState,} from 'react'-import { ArrowDownRoundFill } from '@/app/components/base/icons/src/vender/solid/general'-import Tooltip from '@/app/components/base/tooltip'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { cn } from '@/utils/classnames'export type FieldTitleProps = {@@ -12,6 +11,7 @@ export type FieldTitleProps = {operation?: ReactNodesubTitle?: string | ReactNodetooltip?: string+ warningDot?: booleanshowArrow?: booleandisabled?: booleancollapsed?: boolean@@ -22,6 +22,7 @@ export const FieldTitle = memo(({operation,subTitle,tooltip,+ warningDot,showArrow,disabled,collapsed,@@ -41,13 +42,19 @@ export const FieldTitle = memo(({}}}>- <div className="system-sm-semibold-uppercase flex items-center text-text-secondary">- {title}+ <div className="flex items-center text-text-secondary system-sm-semibold-uppercase">+ <span className="relative">+ {warningDot && (+ <span className="absolute -left-[9px] top-1/2 size-[5px] -translate-y-1/2 rounded-full bg-text-warning-secondary" />+ )}+ {title}+ </span>{showArrow && (- <ArrowDownRoundFill+ <span+ aria-hiddenclassName={cn(- 'h-4 w-4 cursor-pointer text-text-quaternary group-hover/collapse:text-text-secondary',+ 'i-custom-vender-solid-general-arrow-down-round-fill h-4 w-4 cursor-pointer text-text-quaternary group-hover/collapse:text-text-secondary',collapsedMerged && 'rotate-[270deg]',)}/>@@ -55,10 +62,19 @@ export const FieldTitle = memo(({}{tooltip && (- <Tooltip- popupContent={tooltip}- triggerClassName="w-4 h-4 ml-1"- />+ <Tooltip>+ <TooltipTrigger+ delay={0}+ render={(+ <span className="ml-1 flex h-4 w-4 shrink-0 items-center justify-center">+ <span aria-hidden className="i-ri-question-line h-3.5 w-3.5 text-text-quaternary hover:text-text-tertiary" />+ </span>+ )}+ />+ <TooltipContent>+ {tooltip}+ </TooltipContent>+ </Tooltip>)}</div>diff --git a/web/app/components/workflow/nodes/_base/components/node-control.spec.tsx b/web/app/components/workflow/nodes/_base/components/node-control.spec.tsxnew file mode 100644index 00000000000..a76eba69ef9--- /dev/null+++ b/web/app/components/workflow/nodes/_base/components/node-control.spec.tsx@@ -0,0 +1,137 @@+import type { CommonNodeType } from '../../../types'+import { fireEvent, render, screen } from '@testing-library/react'+import { BlockEnum, NodeRunningStatus } from '../../../types'+import NodeControl from './node-control'++const {+ mockHandleNodeSelect,+ mockSetInitShowLastRunTab,+ mockSetPendingSingleRun,+ mockCanRunBySingle,+} = vi.hoisted(() => ({+ mockHandleNodeSelect: vi.fn(),+ mockSetInitShowLastRunTab: vi.fn(),+ mockSetPendingSingleRun: vi.fn(),+ mockCanRunBySingle: vi.fn(() => true),+}))++vi.mock('react-i18next', () => ({+ useTranslation: () => ({+ t: (key: string) => key,+ }),+}))++vi.mock('@/app/components/base/tooltip', () => ({+ default: ({ children, popupContent }: { children: React.ReactNode, popupContent: string }) => (+ <div data-testid="tooltip" data-content={popupContent}>{children}</div>+ ),+}))++vi.mock('@/app/components/base/icons/src/vender/line/mediaAndDevices', () => ({+ Stop: ({ className }: { className?: string }) => <div data-testid="stop-icon" className={className} />,+}))++vi.mock('../../../hooks', () => ({+ useNodesInteractions: () => ({+ handleNodeSelect: mockHandleNodeSelect,+ }),+}))++vi.mock('@/app/components/workflow/store', () => ({+ useWorkflowStore: () => ({+ getState: () => ({+ setInitShowLastRunTab: mockSetInitShowLastRunTab,+ setPendingSingleRun: mockSetPendingSingleRun,+ }),+ }),+}))++vi.mock('../../../utils', () => ({+ canRunBySingle: mockCanRunBySingle,+}))++vi.mock('./panel-operator', () => ({+ default: ({ onOpenChange }: { onOpenChange: (open: boolean) => void }) => (+ <>+ <button type="button" onClick={() => onOpenChange(true)}>open panel</button>+ <button type="button" onClick={() => onOpenChange(false)}>close panel</button>+ </>+ ),+}))++const makeData = (overrides: Partial<CommonNodeType> = {}): CommonNodeType => ({+ type: BlockEnum.Code,+ title: 'Node',+ desc: '',+ selected: false,+ _singleRunningStatus: undefined,+ isInIteration: false,+ isInLoop: false,+ ...overrides,+})++describe('NodeControl', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCanRunBySingle.mockReturnValue(true)+ })++ it('should trigger a single run and show the hover control when plugins are not locked', () => {+ const { container } = render(+ <NodeControl+ id="node-1"+ data={makeData()}+ />,+ )++ const wrapper = container.firstChild as HTMLElement+ expect(wrapper.className).toContain('group-hover:flex')+ expect(screen.getByTestId('tooltip')).toHaveAttribute('data-content', 'panel.runThisStep')++ fireEvent.click(screen.getByTestId('tooltip').parentElement!)++ expect(mockSetInitShowLastRunTab).toHaveBeenCalledWith(true)+ expect(mockSetPendingSingleRun).toHaveBeenCalledWith({ nodeId: 'node-1', action: 'run' })+ expect(mockHandleNodeSelect).toHaveBeenCalledWith('node-1')+ })++ it('should render the stop action, keep locked controls hidden by default, and stay open when panel operator opens', () => {+ const { container } = render(+ <NodeControl+ id="node-2"+ pluginInstallLocked+ data={makeData({+ selected: true,+ _singleRunningStatus: NodeRunningStatus.Running,+ isInIteration: true,+ })}+ />,+ )++ const wrapper = container.firstChild as HTMLElement+ expect(wrapper.className).not.toContain('group-hover:flex')+ expect(wrapper.className).toContain('!flex')+ expect(screen.getByTestId('stop-icon')).toBeInTheDocument()++ fireEvent.click(screen.getByTestId('stop-icon').parentElement!)++ expect(mockSetPendingSingleRun).toHaveBeenCalledWith({ nodeId: 'node-2', action: 'stop' })++ fireEvent.click(screen.getByRole('button', { name: 'open panel' }))+ expect(wrapper.className).toContain('!flex')+ })++ it('should hide the run control when single-node execution is not supported', () => {+ mockCanRunBySingle.mockReturnValue(false)++ render(+ <NodeControl+ id="node-3"+ data={makeData()}+ />,+ )++ expect(screen.queryByTestId('tooltip')).not.toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'open panel' })).toBeInTheDocument()+ })+})diff --git a/web/app/components/workflow/nodes/_base/components/node-control.tsx b/web/app/components/workflow/nodes/_base/components/node-control.tsxindex 0c705191d59..1ae697dfc47 100644--- a/web/app/components/workflow/nodes/_base/components/node-control.tsx+++ b/web/app/components/workflow/nodes/_base/components/node-control.tsx@@ -21,10 +21,13 @@ import { NodeRunningStatus } from '../../../types'import { canRunBySingle } from '../../../utils'import PanelOperator from './panel-operator'-type NodeControlProps = Pick<Node, 'id' | 'data'>+type NodeControlProps = Pick<Node, 'id' | 'data'> & {+ pluginInstallLocked?: boolean+}const NodeControl: FC<NodeControlProps> = ({id,data,+ pluginInstallLocked,}) => {const { t } = useTranslation()const [open, setOpen] = useState(false)@@ -40,7 +43,7 @@ const NodeControl: FC<NodeControlProps> = ({<divclassName={`absolute -top-7 right-0 hidden h-7 pb-1- ${!data._pluginInstallLocked && 'group-hover:flex'}+ ${!pluginInstallLocked && 'group-hover:flex'}${data.selected && '!flex'}${open && '!flex'}`}diff --git a/web/app/components/workflow/nodes/_base/components/prompt/editor.tsx b/web/app/components/workflow/nodes/_base/components/prompt/editor.tsxindex ceb60e7cdb4..2f957658c8a 100644--- a/web/app/components/workflow/nodes/_base/components/prompt/editor.tsx+++ b/web/app/components/workflow/nodes/_base/components/prompt/editor.tsx@@ -240,7 +240,7 @@ const Editor: FC<Props> = ({<div className={cn('pb-2', isExpand && 'flex grow flex-col')}>{!(isSupportJinja && editionType === EditionType.jinja2)? (- <div className={cn(isExpand ? 'grow' : 'max-h-[536px]', 'relative min-h-[56px] overflow-y-auto px-3', editorContainerClassName)}>+ <div className={cn(isExpand ? 'grow' : 'max-h-[536px]', 'relative min-h-[56px] overflow-y-auto px-3', editorContainerClassName)}><PromptEditorkey={controlPromptEditorRerenderKey}placeholder={placeholder}@@ -278,6 +278,9 @@ const Editor: FC<Props> = ({width: node.width,height: node.height,position: node.position,+ ...(node.data.type === BlockEnum.LLM && {+ modelProvider: (node.data as { model?: ModelConfig }).model?.provider,+ }),}if (node.data.type === BlockEnum.Start) {acc.sys = {@@ -301,7 +304,7 @@ const Editor: FC<Props> = ({</div>): (- <div className={cn(isExpand ? 'grow' : 'max-h-[536px]', 'relative min-h-[56px] overflow-y-auto px-3', editorContainerClassName)}>+ <div className={cn(isExpand ? 'grow' : 'max-h-[536px]', 'relative min-h-[56px] overflow-y-auto px-3', editorContainerClassName)}><CodeEditoravailableVars={nodesOutputVars || []}varList={varList}diff --git a/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx b/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsxindex 7f07a814914..35ef72eb0b4 100644--- a/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx+++ b/web/app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx@@ -1,11 +1,8 @@import type { VariablePayload } from '../types'-import {- RiErrorWarningFill,- RiMoreLine,-} from '@remixicon/react'import { capitalize } from 'es-toolkit/string'import { memo } from 'react'-import Tooltip from '@/app/components/base/tooltip'+import { Warning } from '@/app/components/base/icons/src/vender/line/alertsAndFeedback'+import { Tooltip, TooltipContent, TooltipTrigger } from '@/app/components/base/ui/tooltip'import { cn } from '@/utils/classnames'import { isConversationVar, isENV, isGlobalVar, isRagVariableVar } from '../../utils'import { useVarColor } from '../hooks'@@ -28,7 +25,8 @@ const VariableLabel = ({}: VariablePayload) => {const varColorClassName = useVarColor(variables, isExceptionVariable)const isShowNodeLabel = !(isENV(variables) || isConversationVar(variables) || isGlobalVar(variables) || isRagVariableVar(variables))- return (++ const badge = (<divclassName={cn('inline-flex h-6 max-w-full items-center space-x-0.5 rounded-md border-[0.5px] border-components-panel-border-subtle bg-components-badge-white-to-dark px-1.5 shadow-xs',@@ -47,7 +45,7 @@ const VariableLabel = ({{notShowFullPath && (<>- <RiMoreLine className="h-3 w-3 shrink-0 text-text-secondary" />+ <span className="i-ri-more-line h-3 w-3 shrink-0 text-text-secondary" /><div className="shrink-0 text-divider-deep system-xs-regular">/</div></>)@@ -70,12 +68,7 @@ const VariableLabel = ({}{!!errorMsg && (- <Tooltip- popupContent={errorMsg}- asChild- >- <RiErrorWarningFill className="h-3 w-3 shrink-0 text-text-destructive" />- </Tooltip>+ <Warning className="h-3 w-3 shrink-0 text-text-warning" />)}{@@ -83,6 +76,16 @@ const VariableLabel = ({}</div>)++ if (!errorMsg)+ return badge++ return (+ <Tooltip>+ <TooltipTrigger render={badge} />+ <TooltipContent>{errorMsg}</TooltipContent>+ </Tooltip>+ )}export default memo(VariableLabel)diff --git a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.tsindex bf8649111d5..db7833af2b4 100644--- a/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts+++ b/web/app/components/workflow/nodes/_base/components/workflow-panel/last-run/use-last-run.ts@@ -28,8 +28,8 @@ import useQuestionClassifierSingleRunFormParams from '@/app/components/workflow/import useStartSingleRunFormParams from '@/app/components/workflow/nodes/start/use-single-run-form-params'import useTemplateTransformSingleRunFormParams from '@/app/components/workflow/nodes/template-transform/use-single-run-form-params'-import useToolGetDataForCheckMore from '@/app/components/workflow/nodes/tool/use-get-data-for-check-more'-import useToolSingleRunFormParams from '@/app/components/workflow/nodes/tool/use-single-run-form-params'+import useToolGetDataForCheckMore from '@/app/components/workflow/nodes/tool/hooks/use-get-data-for-check-more'+import useToolSingleRunFormParams from '@/app/components/workflow/nodes/tool/hooks/use-single-run-form-params'import useTriggerPluginGetDataForCheckMore from '@/app/components/workflow/nodes/trigger-plugin/use-check-params'import useVariableAggregatorSingleRunFormParams from '@/app/components/workflow/nodes/variable-assigner/use-single-run-form-params'@@ -159,10 +159,10 @@ const useLastRun = <T>({if (!warningForNode)return false- if (warningForNode.unConnected && !warningForNode.errorMessage)+ if (warningForNode.unConnected && warningForNode.errorMessages.length === 0)return false- const message = warningForNode.errorMessage || 'This node has unresolved checklist issues'+ const message = warningForNode.errorMessages[0] || 'This node has unresolved checklist issues'Toast.notify({ type: 'error', message })return true}, [warningNodes, id])diff --git a/web/app/components/workflow/nodes/_base/node.tsx b/web/app/components/workflow/nodes/_base/node.tsxindex 019f38ca0e6..858d690a028 100644--- a/web/app/components/workflow/nodes/_base/node.tsx+++ b/web/app/components/workflow/nodes/_base/node.tsx@@ -17,6 +17,7 @@ import BlockIcon from '@/app/components/workflow/block-icon'import { ToolTypeEnum } from '@/app/components/workflow/block-selector/types'import { useNodesReadOnly, useToolIcon } from '@/app/components/workflow/hooks'import useInspectVarsCrud from '@/app/components/workflow/hooks/use-inspect-vars-crud'+import { useNodePluginInstallation } from '@/app/components/workflow/hooks/use-node-plugin-installation'import { useNodeIterationInteractions } from '@/app/components/workflow/nodes/iteration/use-interactions'import { useNodeLoopInteractions } from '@/app/components/workflow/nodes/loop/use-interactions'import CopyID from '@/app/components/workflow/nodes/tool/components/copy-id'@@ -61,6 +62,8 @@ const BaseNode: FC<BaseNodeProps> = ({const { handleNodeIterationChildSizeChange } = useNodeIterationInteractions()const { handleNodeLoopChildSizeChange } = useNodeLoopInteractions()const toolIcon = useToolIcon(data)+ const { shouldDim: pluginDimmed, isChecking: pluginIsChecking, isMissing: pluginIsMissing, canInstall: pluginCanInstall, uniqueIdentifier: pluginUniqueIdentifier } = useNodePluginInstallation(data)+ const pluginInstallLocked = !pluginIsChecking && pluginIsMissing && pluginCanInstall && Boolean(pluginUniqueIdentifier)useEffect(() => {if (nodeRef.current && data.selected && data.isInIteration) {@@ -138,7 +141,7 @@ const BaseNode: FC<BaseNodeProps> = ({'relative flex rounded-2xl border',showSelectedBorder ? 'border-components-option-card-option-selected-border' : 'border-transparent',data._waitingRun && 'opacity-70',- data._pluginInstallLocked && 'cursor-not-allowed',+ pluginInstallLocked && 'cursor-not-allowed',)}ref={nodeRef}style={{@@ -146,14 +149,15 @@ const BaseNode: FC<BaseNodeProps> = ({height: (data.type === BlockEnum.Iteration || data.type === BlockEnum.Loop) ? data.height : 'auto',}}>- {(data._dimmed || data._pluginInstallLocked) && (+ {(data._dimmed || pluginDimmed || pluginInstallLocked) && (<divclassName={cn('absolute inset-0 rounded-2xl transition-opacity',- data._pluginInstallLocked+ pluginInstallLocked? 'pointer-events-auto z-30 bg-workflow-block-parma-bg opacity-80 backdrop-blur-[2px]': 'pointer-events-none z-20 bg-workflow-block-parma-bg opacity-50',)}+ onClick={pluginInstallLocked ? e => e.stopPropagation() : undefined}data-testid="workflow-node-install-overlay"/>)}@@ -229,6 +233,7 @@ const BaseNode: FC<BaseNodeProps> = ({<NodeControlid={id}data={data}+ pluginInstallLocked={pluginInstallLocked}/>)}diff --git a/web/app/components/workflow/nodes/data-source/node.tsx b/web/app/components/workflow/nodes/data-source/node.tsxindex be8a2c50b26..2793194bded 100644--- a/web/app/components/workflow/nodes/data-source/node.tsx+++ b/web/app/components/workflow/nodes/data-source/node.tsx@@ -1,13 +1,11 @@import type { FC } from 'react'import type { DataSourceNodeType } from './types'import type { NodeProps } from '@/app/components/workflow/types'-import { memo, useEffect } from 'react'-import { useNodeDataUpdate } from '@/app/components/workflow/hooks/use-node-data-update'+import { memo } from 'react'import { useNodePluginInstallation } from '@/app/components/workflow/hooks/use-node-plugin-installation'import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'const Node: FC<NodeProps<DataSourceNodeType>> = ({- id,data,}) => {const {@@ -16,22 +14,7 @@ const Node: FC<NodeProps<DataSourceNodeType>> = ({uniqueIdentifier,canInstall,onInstallSuccess,- shouldDim,} = useNodePluginInstallation(data)- const { handleNodeDataUpdate } = useNodeDataUpdate()- const shouldLock = !isChecking && isMissing && canInstall && Boolean(uniqueIdentifier)-- useEffect(() => {- if (data._pluginInstallLocked === shouldLock && data._dimmed === shouldDim)- return- handleNodeDataUpdate({- id,- data: {- _pluginInstallLocked: shouldLock,- _dimmed: shouldDim,- },- })- }, [data._pluginInstallLocked, data._dimmed, handleNodeDataUpdate, id, shouldDim, shouldLock])const showInstallButton = !isChecking && isMissing && canInstall && uniqueIdentifierdiff --git a/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.spec.tsx b/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.spec.tsxnew file mode 100644index 00000000000..f93344ca606--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.spec.tsx@@ -0,0 +1,77 @@+import type { ReactNode } from 'react'+import { render, screen } from '@testing-library/react'+import { ChunkStructureEnum } from '../../types'+import ChunkStructure from './index'++const mockUseChunkStructure = vi.hoisted(() => vi.fn())++vi.mock('@/app/components/workflow/nodes/_base/components/layout', () => ({+ Field: ({ children, fieldTitleProps }: { children: ReactNode, fieldTitleProps: { title: string, warningDot?: boolean, operation?: ReactNode } }) => (+ <div data-testid="field" data-warning-dot={String(!!fieldTitleProps.warningDot)}>+ <div>{fieldTitleProps.title}</div>+ {fieldTitleProps.operation}+ {children}+ </div>+ ),+}))++vi.mock('./hooks', () => ({+ useChunkStructure: mockUseChunkStructure,+}))++vi.mock('../option-card', () => ({+ default: ({ title }: { title: string }) => <div data-testid="option-card">{title}</div>,+}))++vi.mock('./selector', () => ({+ default: ({ trigger, value }: { trigger?: ReactNode, value?: string }) => (+ <div data-testid="selector">+ {value ?? 'no-value'}+ {trigger}+ </div>+ ),+}))++vi.mock('./instruction', () => ({+ default: ({ className }: { className?: string }) => <div data-testid="instruction" className={className}>Instruction</div>,+}))++describe('ChunkStructure', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseChunkStructure.mockReturnValue({+ options: [{ value: ChunkStructureEnum.general, label: 'General' }],+ optionMap: {+ [ChunkStructureEnum.general]: {+ title: 'General Chunk Structure',+ },+ },+ })+ })++ it('should render the selected option and warning dot metadata when a chunk structure is chosen', () => {+ render(+ <ChunkStructure+ chunkStructure={ChunkStructureEnum.general}+ warningDot+ onChunkStructureChange={vi.fn()}+ />,+ )++ expect(screen.getByTestId('field')).toHaveAttribute('data-warning-dot', 'true')+ expect(screen.getByTestId('selector')).toHaveTextContent(ChunkStructureEnum.general)+ expect(screen.getByTestId('option-card')).toHaveTextContent('General Chunk Structure')+ expect(screen.queryByTestId('instruction')).not.toBeInTheDocument()+ })++ it('should render the add trigger and instruction when no chunk structure is selected', () => {+ render(+ <ChunkStructure+ onChunkStructureChange={vi.fn()}+ />,+ )++ expect(screen.getByRole('button', { name: /chooseChunkStructure/i })).toBeInTheDocument()+ expect(screen.getByTestId('instruction')).toBeInTheDocument()+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.tsx b/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.tsxindex f246194d052..88b71286b36 100644--- a/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/components/chunk-structure/index.tsx@@ -1,5 +1,4 @@import type { ChunkStructureEnum } from '../../types'-import { RiAddLine } from '@remixicon/react'import { memo } from 'react'import { useTranslation } from 'react-i18next'import Button from '@/app/components/base/button'@@ -12,11 +11,13 @@ import Selector from './selector'type ChunkStructureProps = {chunkStructure?: ChunkStructureEnumonChunkStructureChange: (value: ChunkStructureEnum) => void+ warningDot?: booleanreadonly?: boolean}const ChunkStructure = ({chunkStructure,onChunkStructureChange,+ warningDot = false,readonly = false,}: ChunkStructureProps) => {const { t } = useTranslation()@@ -30,6 +31,7 @@ const ChunkStructure = ({fieldTitleProps={{title: t('nodes.knowledgeBase.chunkStructure', { ns: 'workflow' }),tooltip: t('nodes.knowledgeBase.chunkStructureTip.message', { ns: 'workflow' }),+ warningDot,operation: chunkStructure && (<Selectoroptions={options}@@ -62,7 +64,7 @@ const ChunkStructure = ({className="w-full"variant="secondary-accent">- <RiAddLine className="mr-1 h-4 w-4" />+ <span className="i-ri-add-line mr-1 h-4 w-4" />{t('nodes.knowledgeBase.chooseChunkStructure', { ns: 'workflow' })}</Button>)}diff --git a/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.spec.tsx b/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.spec.tsxnew file mode 100644index 00000000000..fe8cacd76ef--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.spec.tsx@@ -0,0 +1,62 @@+import type { ReactNode } from 'react'+import { render } from '@testing-library/react'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import EmbeddingModel from './embedding-model'++const mockUseModelList = vi.hoisted(() => vi.fn())+const mockModelSelector = vi.hoisted(() => vi.fn(() => <div data-testid="model-selector">selector</div>))++vi.mock('@/app/components/workflow/nodes/_base/components/layout', () => ({+ Field: ({ children, fieldTitleProps }: { children: ReactNode, fieldTitleProps: { warningDot?: boolean } }) => (+ <div data-testid="field" data-warning-dot={String(!!fieldTitleProps.warningDot)}>+ {children}+ </div>+ ),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useModelList: mockUseModelList,+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({+ default: mockModelSelector,+}))++describe('EmbeddingModel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseModelList.mockReturnValue({ data: [{ provider: 'openai', model: 'text-embedding-3-large' }] })+ })++ it('should pass the selected model configuration and warning state to the selector field', () => {+ const onEmbeddingModelChange = vi.fn()++ render(+ <EmbeddingModel+ embeddingModel="text-embedding-3-large"+ embeddingModelProvider="openai"+ warningDot+ onEmbeddingModelChange={onEmbeddingModelChange}+ />,+ )++ expect(mockUseModelList).toHaveBeenCalledWith(ModelTypeEnum.textEmbedding)+ expect(mockModelSelector).toHaveBeenCalledWith(expect.objectContaining({+ defaultModel: {+ provider: 'openai',+ model: 'text-embedding-3-large',+ },+ modelList: [{ provider: 'openai', model: 'text-embedding-3-large' }],+ readonly: false,+ showDeprecatedWarnIcon: true,+ }), undefined)+ })++ it('should pass an undefined default model when the embedding model is incomplete', () => {+ render(<EmbeddingModel embeddingModel="text-embedding-3-large" />)++ expect(mockModelSelector).toHaveBeenCalledWith(expect.objectContaining({+ defaultModel: undefined,+ }), undefined)+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.tsx b/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.tsxindex f2b174ac21a..81fe7223c28 100644--- a/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/components/embedding-model.tsx@@ -17,12 +17,14 @@ type EmbeddingModelProps = {embeddingModel: stringembeddingModelProvider: string}) => void+ warningDot?: booleanreadonly?: boolean}const EmbeddingModel = ({embeddingModel,embeddingModelProvider,onEmbeddingModelChange,+ warningDot = false,readonly = false,}: EmbeddingModelProps) => {const { t } = useTranslation()@@ -50,6 +52,7 @@ const EmbeddingModel = ({<FieldfieldTitleProps={{title: t('form.embeddingModel', { ns: 'datasetSettings' }),+ warningDot,}}><ModelSelectordiff --git a/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.spec.tsx b/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.spec.tsxnew file mode 100644index 00000000000..300de76c2e4--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.spec.tsx@@ -0,0 +1,121 @@+import type {+ DefaultModel,+ Model,+ ModelItem,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import { fireEvent, render, screen } from '@testing-library/react'+import {+ ConfigurationMethodEnum,+ ModelStatusEnum,+ ModelTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import RerankingModelSelector from './reranking-model-selector'++type MockModelSelectorProps = {+ defaultModel?: DefaultModel+ modelList: Model[]+ onSelect?: (model: DefaultModel) => void+}++const mockUseModelListAndDefaultModel = vi.hoisted(() => vi.fn())++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useModelListAndDefaultModel: mockUseModelListAndDefaultModel,+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/model-selector', () => ({+ default: ({ defaultModel, modelList, onSelect }: MockModelSelectorProps) => (+ <div>+ <div data-testid="default-model">+ {defaultModel ? `${defaultModel.provider}/${defaultModel.model}` : 'no-default-model'}+ </div>+ <div data-testid="model-list-count">{modelList.length}</div>+ <button type="button" onClick={() => onSelect?.({ provider: 'cohere', model: 'rerank-v3' })}>+ select-model+ </button>+ </div>+ ),+}))++const createModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({+ model: 'rerank-v3',+ label: { en_US: 'Rerank V3', zh_Hans: 'Rerank V3' },+ model_type: ModelTypeEnum.rerank,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status: ModelStatusEnum.active,+ model_properties: {},+ load_balancing_enabled: false,+ ...overrides,+})++const createModel = (overrides: Partial<Model> = {}): Model => ({+ provider: 'cohere',+ icon_small: {+ en_US: 'https://example.com/cohere.png',+ zh_Hans: 'https://example.com/cohere.png',+ },+ icon_small_dark: {+ en_US: 'https://example.com/cohere-dark.png',+ zh_Hans: 'https://example.com/cohere-dark.png',+ },+ label: { en_US: 'Cohere', zh_Hans: 'Cohere' },+ models: [createModelItem()],+ status: ModelStatusEnum.active,+ ...overrides,+})++describe('RerankingModelSelector', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseModelListAndDefaultModel.mockReturnValue({+ modelList: [createModel()],+ defaultModel: undefined,+ })+ })++ // Rendering behavior for mapped rerank model state.+ describe('Rendering', () => {+ it('should not pass a default model when reranking model fields are empty strings', () => {+ render(+ <RerankingModelSelector+ rerankingModel={{+ reranking_provider_name: '',+ reranking_model_name: '',+ }}+ />,+ )++ expect(screen.getByTestId('default-model')).toHaveTextContent('no-default-model')+ expect(screen.getByTestId('model-list-count')).toHaveTextContent('1')+ })++ it('should map reranking model to default model when both fields exist', () => {+ render(+ <RerankingModelSelector+ rerankingModel={{+ reranking_provider_name: 'cohere',+ reranking_model_name: 'rerank-v3',+ }}+ />,+ )++ expect(screen.getByTestId('default-model')).toHaveTextContent('cohere/rerank-v3')+ })+ })++ // Selection behavior should convert back to workflow reranking model shape.+ describe('Interactions', () => {+ it('should map selected model back to reranking model fields', () => {+ const onRerankingModelChange = vi.fn()++ render(<RerankingModelSelector onRerankingModelChange={onRerankingModelChange} />)++ fireEvent.click(screen.getByRole('button', { name: 'select-model' }))++ expect(onRerankingModelChange).toHaveBeenCalledWith({+ reranking_provider_name: 'cohere',+ reranking_model_name: 'rerank-v3',+ })+ })+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.tsx b/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.tsxindex 3e0bea2b28d..7ee18a82e51 100644--- a/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/components/retrieval-setting/reranking-model-selector.tsx@@ -22,12 +22,12 @@ const RerankingModelSelector = ({modelList: rerankModelList,} = useModelListAndDefaultModel(ModelTypeEnum.rerank)const rerankModel = useMemo(() => {- if (!rerankingModel)+ if (!rerankingModel?.reranking_provider_name || !rerankingModel?.reranking_model_name)return undefinedreturn {- providerName: rerankingModel.reranking_provider_name,- modelName: rerankingModel.reranking_model_name,+ provider: rerankingModel.reranking_provider_name,+ model: rerankingModel.reranking_model_name,}}, [rerankingModel])@@ -40,7 +40,7 @@ const RerankingModelSelector = ({return (<ModelSelector- defaultModel={rerankModel && { provider: rerankModel.providerName, model: rerankModel.modelName }}+ defaultModel={rerankModel}modelList={rerankModelList}onSelect={handleRerankingModelChange}readonly={readonly}diff --git a/web/app/components/workflow/nodes/knowledge-base/default.spec.ts b/web/app/components/workflow/nodes/knowledge-base/default.spec.tsnew file mode 100644index 00000000000..becc6cb9d87--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/default.spec.ts@@ -0,0 +1,74 @@+import type { KnowledgeBaseNodeType } from './types'+import type { Model, ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'+import {+ ConfigurationMethodEnum,+ ModelStatusEnum,+ ModelTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import nodeDefault from './default'+import { ChunkStructureEnum, IndexMethodEnum, RetrievalSearchMethodEnum } from './types'++const t = (key: string) => key++const makeEmbeddingModelList = (status: ModelStatusEnum): Model[] => [{+ provider: 'openai',+ icon_small: { en_US: '', zh_Hans: '' },+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [{+ model: 'text-embedding-3-large',+ label: { en_US: 'Text Embedding 3 Large', zh_Hans: 'Text Embedding 3 Large' },+ model_type: ModelTypeEnum.textEmbedding,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status,+ model_properties: {},+ load_balancing_enabled: false,+ }],+ status,+}]++const makeEmbeddingProviderModelList = (status: ModelStatusEnum): ModelItem[] => [{+ model: 'text-embedding-3-large',+ label: { en_US: 'Text Embedding 3 Large', zh_Hans: 'Text Embedding 3 Large' },+ model_type: ModelTypeEnum.textEmbedding,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status,+ model_properties: {},+ load_balancing_enabled: false,+}]++const createPayload = (overrides: Partial<KnowledgeBaseNodeType> = {}): KnowledgeBaseNodeType => ({+ ...nodeDefault.defaultValue,+ index_chunk_variable_selector: ['chunks', 'results'],+ chunk_structure: ChunkStructureEnum.general,+ indexing_technique: IndexMethodEnum.QUALIFIED,+ embedding_model: 'text-embedding-3-large',+ embedding_model_provider: 'openai',+ retrieval_model: {+ ...nodeDefault.defaultValue.retrieval_model,+ search_method: RetrievalSearchMethodEnum.semantic,+ },+ _embeddingModelList: makeEmbeddingModelList(ModelStatusEnum.active),+ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.active),+ _rerankModelList: [],+ ...overrides,+}) as KnowledgeBaseNodeType++describe('knowledge-base default node validation', () => {+ it('should return an invalid result when the payload has a validation issue', () => {+ const result = nodeDefault.checkValid(createPayload({ chunk_structure: undefined }), t)++ expect(result).toEqual({+ isValid: false,+ errorMessage: 'nodes.knowledgeBase.chunkIsRequired',+ })+ })++ it('should return a valid result when the payload is complete', () => {+ const result = nodeDefault.checkValid(createPayload(), t)++ expect(result).toEqual({+ isValid: true,+ errorMessage: '',+ })+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/default.ts b/web/app/components/workflow/nodes/knowledge-base/default.tsindex f481fa55878..b1ddea49ec9 100644--- a/web/app/components/workflow/nodes/knowledge-base/default.ts+++ b/web/app/components/workflow/nodes/knowledge-base/default.ts@@ -1,8 +1,11 @@import type { NodeDefault } from '../../types'import type { KnowledgeBaseNodeType } from './types'-import { IndexingType } from '@/app/components/datasets/create/step-two'import { BlockEnum } from '@/app/components/workflow/types'import { genNodeMetaData } from '@/app/components/workflow/utils'+import {+ getKnowledgeBaseValidationIssue,+ getKnowledgeBaseValidationMessage,+} from './utils'const metaData = genNodeMetaData({sort: 3.1,@@ -24,86 +27,9 @@ const nodeDefault: NodeDefault<KnowledgeBaseNodeType> = {},},checkValid(payload, t) {- const {- chunk_structure,- indexing_technique,- retrieval_model,- embedding_model,- embedding_model_provider,- index_chunk_variable_selector,- _embeddingModelList,- _rerankModelList,- } = payload-- const {- search_method,- reranking_enable,- reranking_model,- } = retrieval_model || {}-- const currentEmbeddingModelProvider = _embeddingModelList?.find(provider => provider.provider === embedding_model_provider)- const currentEmbeddingModel = currentEmbeddingModelProvider?.models.find(model => model.model === embedding_model)-- const currentRerankingModelProvider = _rerankModelList?.find(provider => provider.provider === reranking_model?.reranking_provider_name)- const currentRerankingModel = currentRerankingModelProvider?.models.find(model => model.model === reranking_model?.reranking_model_name)-- if (!chunk_structure) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.chunkIsRequired', { ns: 'workflow' }),- }- }-- if (index_chunk_variable_selector.length === 0) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.chunksVariableIsRequired', { ns: 'workflow' }),- }- }-- if (!indexing_technique) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.indexMethodIsRequired', { ns: 'workflow' }),- }- }-- if (indexing_technique === IndexingType.QUALIFIED) {- if (!embedding_model || !embedding_model_provider) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.embeddingModelIsRequired', { ns: 'workflow' }),- }- }- else if (!currentEmbeddingModel) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.embeddingModelIsInvalid', { ns: 'workflow' }),- }- }- }-- if (!retrieval_model || !search_method) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.retrievalSettingIsRequired', { ns: 'workflow' }),- }- }-- if (reranking_enable) {- if (!reranking_model || !reranking_model.reranking_provider_name || !reranking_model.reranking_model_name) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.rerankingModelIsRequired', { ns: 'workflow' }),- }- }- else if (!currentRerankingModel) {- return {- isValid: false,- errorMessage: t('nodes.knowledgeBase.rerankingModelIsInvalid', { ns: 'workflow' }),- }- }- }+ const issue = getKnowledgeBaseValidationIssue(payload)+ if (issue)+ return { isValid: false, errorMessage: getKnowledgeBaseValidationMessage(issue, t) }return {isValid: true,diff --git a/web/app/components/workflow/nodes/knowledge-base/hooks/use-embedding-model-status.ts b/web/app/components/workflow/nodes/knowledge-base/hooks/use-embedding-model-status.tsnew file mode 100644index 00000000000..b32d998ada0--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/hooks/use-embedding-model-status.ts@@ -0,0 +1,61 @@+import type {+ Model,+ ModelItem,+ ModelProvider,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useMemo } from 'react'+import { deriveModelStatus } from '@/app/components/header/account-setting/model-provider-page/derive-model-status'+import { useCredentialPanelState } from '@/app/components/header/account-setting/model-provider-page/provider-added-card/use-credential-panel-state'+import { useProviderContext } from '@/context/provider-context'++type UseEmbeddingModelStatusProps = {+ embeddingModel?: string+ embeddingModelProvider?: string+ embeddingModelList: Model[]+}++type UseEmbeddingModelStatusResult = {+ providerMeta: ModelProvider | undefined+ modelProvider: Model | undefined+ currentModel: ModelItem | undefined+ status: ReturnType<typeof deriveModelStatus>+}++export const useEmbeddingModelStatus = ({+ embeddingModel,+ embeddingModelProvider,+ embeddingModelList,+}: UseEmbeddingModelStatusProps): UseEmbeddingModelStatusResult => {+ const { modelProviders } = useProviderContext()++ const providerMeta = useMemo(() => {+ return modelProviders.find(provider => provider.provider === embeddingModelProvider)+ }, [embeddingModelProvider, modelProviders])++ const modelProvider = useMemo(() => {+ return embeddingModelList.find(provider => provider.provider === embeddingModelProvider)+ }, [embeddingModelList, embeddingModelProvider])++ const currentModel = useMemo(() => {+ return modelProvider?.models.find(model => model.model === embeddingModel)+ }, [embeddingModel, modelProvider])++ const credentialState = useCredentialPanelState(providerMeta)++ const status = useMemo(() => {+ return deriveModelStatus(+ embeddingModel,+ embeddingModelProvider,+ providerMeta,+ currentModel,+ credentialState,+ )+ }, [credentialState, currentModel, embeddingModel, embeddingModelProvider, providerMeta])++ return {+ providerMeta,+ modelProvider,+ currentModel,+ status,+ }+}diff --git a/web/app/components/workflow/nodes/knowledge-base/node.spec.tsx b/web/app/components/workflow/nodes/knowledge-base/node.spec.tsxnew file mode 100644index 00000000000..19cf6a0626a--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/node.spec.tsx@@ -0,0 +1,233 @@+import type { KnowledgeBaseNodeType } from './types'+import type { ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { CommonNodeType } from '@/app/components/workflow/types'+import { render, screen } from '@testing-library/react'+import {+ ConfigurationMethodEnum,+ ModelStatusEnum,+ ModelTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import { BlockEnum } from '@/app/components/workflow/types'+import Node from './node'+import {+ ChunkStructureEnum,+ IndexMethodEnum,+ RetrievalSearchMethodEnum,+} from './types'++const mockUseModelList = vi.hoisted(() => vi.fn())+const mockUseSettingsDisplay = vi.hoisted(() => vi.fn())+const mockUseEmbeddingModelStatus = vi.hoisted(() => vi.fn())++vi.mock('@tanstack/react-query', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@tanstack/react-query')>()+ return {+ ...actual,+ useQuery: () => ({ data: undefined }),+ }+})++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/app/components/header/account-setting/model-provider-page/hooks')>()+ return {+ ...actual,+ useLanguage: () => 'en_US',+ useModelList: mockUseModelList,+ }+})++vi.mock('./hooks/use-settings-display', () => ({+ useSettingsDisplay: mockUseSettingsDisplay,+}))++vi.mock('./hooks/use-embedding-model-status', () => ({+ useEmbeddingModelStatus: mockUseEmbeddingModelStatus,+}))++const createModelItem = (overrides: Partial<ModelItem> = {}): ModelItem => ({+ model: 'text-embedding-3-large',+ label: { en_US: 'Text Embedding 3 Large', zh_Hans: 'Text Embedding 3 Large' },+ model_type: ModelTypeEnum.textEmbedding,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status: ModelStatusEnum.active,+ model_properties: {},+ load_balancing_enabled: false,+ ...overrides,+})++const createNodeData = (overrides: Partial<CommonNodeType<KnowledgeBaseNodeType>> = {}): CommonNodeType<KnowledgeBaseNodeType> => ({+ title: 'Knowledge Base',+ desc: '',+ type: BlockEnum.KnowledgeBase,+ index_chunk_variable_selector: ['result'],+ chunk_structure: ChunkStructureEnum.general,+ indexing_technique: IndexMethodEnum.QUALIFIED,+ embedding_model: 'text-embedding-3-large',+ embedding_model_provider: 'openai',+ keyword_number: 10,+ retrieval_model: {+ top_k: 3,+ score_threshold_enabled: false,+ score_threshold: 0.5,+ search_method: RetrievalSearchMethodEnum.semantic,+ },+ ...overrides,+})++describe('KnowledgeBaseNode', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseModelList.mockReturnValue({ data: [] })+ mockUseSettingsDisplay.mockReturnValue({+ [IndexMethodEnum.QUALIFIED]: 'High Quality',+ [RetrievalSearchMethodEnum.semantic]: 'Vector Search',+ })+ mockUseEmbeddingModelStatus.mockReturnValue({+ providerMeta: undefined,+ modelProvider: undefined,+ currentModel: createModelItem(),+ status: 'active',+ })+ })++ // Embedding model row should mirror the selector status labels.+ describe('Embedding Model Status', () => {+ it('should render active embedding model label when the model is available', () => {+ render(<Node id="knowledge-base-1" data={createNodeData()} />)++ expect(screen.getByText('Text Embedding 3 Large')).toBeInTheDocument()+ })++ it('should render configure required when embedding model status requires configuration', () => {+ mockUseEmbeddingModelStatus.mockReturnValue({+ providerMeta: undefined,+ modelProvider: undefined,+ currentModel: createModelItem({ status: ModelStatusEnum.noConfigure }),+ status: 'configure-required',+ })++ render(<Node id="knowledge-base-1" data={createNodeData()} />)++ expect(screen.getByText('common.modelProvider.selector.configureRequired')).toBeInTheDocument()+ })++ it('should render disabled when embedding model status is disabled', () => {+ mockUseEmbeddingModelStatus.mockReturnValue({+ providerMeta: undefined,+ modelProvider: undefined,+ currentModel: createModelItem({ status: ModelStatusEnum.disabled }),+ status: 'disabled',+ })++ render(<Node id="knowledge-base-1" data={createNodeData()} />)++ expect(screen.getByText('common.modelProvider.selector.disabled')).toBeInTheDocument()+ })++ it('should render incompatible when embedding model status is incompatible', () => {+ mockUseEmbeddingModelStatus.mockReturnValue({+ providerMeta: undefined,+ modelProvider: undefined,+ currentModel: undefined,+ status: 'incompatible',+ })++ render(<Node id="knowledge-base-1" data={createNodeData()} />)++ expect(screen.getByText('common.modelProvider.selector.incompatible')).toBeInTheDocument()+ })++ it('should render configure model prompt when no embedding model is selected', () => {+ mockUseEmbeddingModelStatus.mockReturnValue({+ providerMeta: undefined,+ modelProvider: undefined,+ currentModel: undefined,+ status: 'empty',+ })++ render(+ <Node+ id="knowledge-base-1"+ data={createNodeData({+ embedding_model: undefined,+ embedding_model_provider: undefined,+ })}+ />,+ )++ expect(screen.getByText('plugin.detailPanel.configureModel')).toBeInTheDocument()+ })+ })++ describe('Validation warnings', () => {+ it('should render a warning banner when chunk structure is missing', () => {+ render(+ <Node+ id="knowledge-base-1"+ data={createNodeData({+ chunk_structure: undefined,+ })}+ />,+ )++ expect(screen.getByText(/chunkIsRequired/i)).toBeInTheDocument()+ })++ it('should render a warning value for the chunks input row when no chunk variable is selected', () => {+ render(+ <Node+ id="knowledge-base-1"+ data={createNodeData({+ index_chunk_variable_selector: [],+ })}+ />,+ )++ expect(screen.getByText(/chunksVariableIsRequired/i)).toBeInTheDocument()+ })++ it('should render a warning value for retrieval settings when reranking is incomplete', () => {+ mockUseModelList.mockImplementation((modelType: ModelTypeEnum) => {+ if (modelType === ModelTypeEnum.textEmbedding) {+ return {+ data: [{+ provider: 'openai',+ models: [createModelItem()],+ }],+ }+ }+ return { data: [] }+ })++ render(+ <Node+ id="knowledge-base-1"+ data={createNodeData({+ retrieval_model: {+ top_k: 3,+ score_threshold_enabled: false,+ score_threshold: 0.5,+ search_method: RetrievalSearchMethodEnum.semantic,+ reranking_enable: true,+ },+ })}+ />,+ )++ expect(screen.getByText(/rerankingModelIsRequired/i)).toBeInTheDocument()+ })++ it('should hide the embedding model row when the index method is not qualified', () => {+ render(+ <Node+ id="knowledge-base-1"+ data={createNodeData({+ indexing_technique: IndexMethodEnum.ECONOMICAL,+ })}+ />,+ )++ expect(screen.queryByText('Text Embedding 3 Large')).not.toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/node.tsx b/web/app/components/workflow/nodes/knowledge-base/node.tsxindex 861cd08448f..4aa10ad2085 100644--- a/web/app/components/workflow/nodes/knowledge-base/node.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/node.tsx@@ -1,38 +1,210 @@import type { FC } from 'react'import type { KnowledgeBaseNodeType } from './types'import type { NodeProps } from '@/app/components/workflow/types'-import { memo } from 'react'+import { useQuery } from '@tanstack/react-query'+import {+ memo,+ useMemo,+} from 'react'import { useTranslation } from 'react-i18next'+import {+ ModelTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import { DERIVED_MODEL_STATUS_BADGE_I18N } from '@/app/components/header/account-setting/model-provider-page/derive-model-status'+import {+ useLanguage,+ useModelList,+} from '@/app/components/header/account-setting/model-provider-page/hooks'+import { consoleQuery } from '@/service/client'+import { cn } from '@/utils/classnames'+import { useEmbeddingModelStatus } from './hooks/use-embedding-model-status'import { useSettingsDisplay } from './hooks/use-settings-display'+import {+ IndexMethodEnum,+} from './types'+import {+ getKnowledgeBaseValidationIssue,+ getKnowledgeBaseValidationMessage,+ KnowledgeBaseValidationIssueCode,+} from './utils'++type SettingRowProps = {+ label: string+ value: string+ warning?: boolean+}++const SettingRow = memo(({+ label,+ value,+ warning = false,+}: SettingRowProps) => {+ return (+ <div+ className={cn(+ 'flex h-6 items-center rounded-md px-1.5',+ warning+ ? 'border-[0.5px] border-state-warning-active bg-state-warning-hover'+ : 'bg-workflow-block-parma-bg',+ )}+ >+ <div className="mr-2 shrink-0 text-text-tertiary system-xs-medium-uppercase">+ {label}+ </div>+ <div+ className={cn('grow truncate text-right system-xs-medium', warning ? 'text-text-warning' : 'text-text-secondary')}+ title={value}+ >+ {value}+ </div>+ </div>+ )+})++const RETRIEVAL_WARNING_CODES = new Set<KnowledgeBaseValidationIssueCode>([+ KnowledgeBaseValidationIssueCode.retrievalSettingRequired,+ KnowledgeBaseValidationIssueCode.rerankingModelRequired,+ KnowledgeBaseValidationIssueCode.rerankingModelInvalid,+])const Node: FC<NodeProps<KnowledgeBaseNodeType>> = ({ data }) => {const { t } = useTranslation()+ const language = useLanguage()const settingsDisplay = useSettingsDisplay()+ const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)+ const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)+ const chunkStructure = data.chunk_structure+ const indexChunkVariableSelector = data.index_chunk_variable_selector+ const indexingTechnique = data.indexing_technique+ const embeddingModel = data.embedding_model+ const retrievalModel = data.retrieval_model+ const retrievalSearchMethod = retrievalModel?.search_method+ const retrievalRerankingEnable = retrievalModel?.reranking_enable+ const embeddingModelProvider = data.embedding_model_provider+ const { data: embeddingProviderModelList } = useQuery(+ consoleQuery.modelProviders.models.queryOptions({+ input: { params: { provider: embeddingModelProvider || '' } },+ enabled: indexingTechnique === IndexMethodEnum.QUALIFIED && !!embeddingModelProvider,+ refetchOnWindowFocus: false,+ select: response => response.data,+ }),+ )- return (- <div className="mb-1 space-y-0.5 px-3 py-1">- <div className="flex h-6 items-center rounded-md bg-workflow-block-parma-bg px-1.5">- <div className="system-xs-medium-uppercase mr-2 shrink-0 text-text-tertiary">- {t('stepTwo.indexMode', { ns: 'datasetCreation' })}- </div>- <div- className="system-xs-medium grow truncate text-right text-text-secondary"- title={data.indexing_technique}- >- {settingsDisplay[data.indexing_technique as keyof typeof settingsDisplay]}- </div>- </div>- <div className="flex h-6 items-center rounded-md bg-workflow-block-parma-bg px-1.5">- <div className="system-xs-medium-uppercase mr-2 shrink-0 text-text-tertiary">- {t('form.retrievalSetting.title', { ns: 'datasetSettings' })}- </div>- <div- className="system-xs-medium grow truncate text-right text-text-secondary"- title={data.retrieval_model?.search_method}- >- {settingsDisplay[data.retrieval_model?.search_method as keyof typeof settingsDisplay]}+ const validationPayload = useMemo(() => {+ return {+ chunk_structure: chunkStructure,+ index_chunk_variable_selector: indexChunkVariableSelector,+ indexing_technique: indexingTechnique,+ embedding_model: embeddingModel,+ embedding_model_provider: embeddingModelProvider,+ retrieval_model: {+ search_method: retrievalSearchMethod,+ reranking_enable: retrievalRerankingEnable,+ reranking_model: retrievalModel?.reranking_model,+ },+ _embeddingModelList: embeddingModelList,+ _embeddingProviderModelList: embeddingProviderModelList,+ _rerankModelList: rerankModelList,+ }+ }, [+ chunkStructure,+ indexChunkVariableSelector,+ indexingTechnique,+ embeddingModel,+ embeddingModelProvider,+ retrievalSearchMethod,+ retrievalRerankingEnable,+ retrievalModel?.reranking_model,+ embeddingModelList,+ embeddingProviderModelList,+ rerankModelList,+ ])++ const validationIssue = useMemo(() => {+ return getKnowledgeBaseValidationIssue({+ ...validationPayload,+ })+ }, [validationPayload])++ const validationIssueMessage = useMemo(() => {+ return getKnowledgeBaseValidationMessage(validationIssue, t)+ }, [validationIssue, t])+ const { currentModel: currentEmbeddingModel, status: embeddingModelStatus } = useEmbeddingModelStatus({+ embeddingModel: data.embedding_model,+ embeddingModelProvider: data.embedding_model_provider,+ embeddingModelList,+ })++ const chunksDisplayValue = useMemo(() => {+ if (!data.index_chunk_variable_selector?.length)+ return '-'++ const chunkVar = data.index_chunk_variable_selector.at(-1)+ return chunkVar || '-'+ }, [data.index_chunk_variable_selector])++ const embeddingModelDisplay = useMemo(() => {+ if (data.indexing_technique !== IndexMethodEnum.QUALIFIED)+ return '-'++ if (embeddingModelStatus === 'empty')+ return t('detailPanel.configureModel', { ns: 'plugin' })++ if (embeddingModelStatus !== 'active') {+ const statusI18nKey = DERIVED_MODEL_STATUS_BADGE_I18N[embeddingModelStatus as keyof typeof DERIVED_MODEL_STATUS_BADGE_I18N]+ if (statusI18nKey)+ return t(statusI18nKey as 'modelProvider.selector.incompatible', { ns: 'common' })+ }++ return currentEmbeddingModel?.label[language] || currentEmbeddingModel?.label.en_US || data.embedding_model || '-'+ }, [currentEmbeddingModel, data.embedding_model, data.indexing_technique, embeddingModelStatus, language, t])++ const indexMethodDisplay = settingsDisplay[data.indexing_technique as keyof typeof settingsDisplay] || '-'+ const retrievalMethodDisplay = settingsDisplay[data.retrieval_model?.search_method as keyof typeof settingsDisplay] || '-'++ const chunksWarning = validationIssue?.code === KnowledgeBaseValidationIssueCode.chunksVariableRequired+ const indexMethodWarning = validationIssue?.code === KnowledgeBaseValidationIssueCode.indexMethodRequired+ const embeddingWarning = data.indexing_technique === IndexMethodEnum.QUALIFIED && embeddingModelStatus !== 'active'+ const showEmbeddingModelRow = data.indexing_technique === IndexMethodEnum.QUALIFIED+ const retrievalWarning = !!(validationIssue && RETRIEVAL_WARNING_CODES.has(validationIssue.code))++ if (!data.chunk_structure) {+ return (+ <div className="mb-1 space-y-0.5 px-3 py-1">+ <div className="flex h-6 items-center rounded-md border-[0.5px] border-state-warning-active bg-state-warning-hover px-1.5">+ <span className="mr-1 size-[4px] shrink-0 rounded-[2px] bg-text-warning-secondary" />+ <div className="grow truncate text-text-warning system-xs-medium" title={validationIssueMessage}>+ {validationIssueMessage}+ </div></div></div>+ )+ }++ return (+ <div className="mb-1 space-y-0.5 px-3 py-1">+ <SettingRow+ label={t('nodes.knowledgeBase.chunksInput', { ns: 'workflow' })}+ value={chunksWarning ? validationIssueMessage : chunksDisplayValue}+ warning={chunksWarning}+ />+ <SettingRow+ label={t('stepTwo.indexMode', { ns: 'datasetCreation' })}+ value={indexMethodWarning ? validationIssueMessage : indexMethodDisplay}+ warning={indexMethodWarning}+ />+ {showEmbeddingModelRow && (+ <SettingRow+ label={t('form.embeddingModel', { ns: 'datasetSettings' })}+ value={embeddingModelDisplay}+ warning={embeddingWarning}+ />+ )}+ <SettingRow+ label={t('form.retrievalSetting.method', { ns: 'datasetSettings' })}+ value={retrievalWarning ? validationIssueMessage : retrievalMethodDisplay}+ warning={retrievalWarning}+ /></div>)}diff --git a/web/app/components/workflow/nodes/knowledge-base/panel.spec.tsx b/web/app/components/workflow/nodes/knowledge-base/panel.spec.tsxnew file mode 100644index 00000000000..2f76449b6c3--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/panel.spec.tsx@@ -0,0 +1,198 @@+import type { ReactNode } from 'react'+import type { PanelProps } from '@/types/workflow'+import { render, screen } from '@testing-library/react'+import { ModelTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import Panel from './panel'+import { ChunkStructureEnum, IndexMethodEnum, RetrievalSearchMethodEnum } from './types'++const mockUseModelList = vi.hoisted(() => vi.fn())+const mockUseQuery = vi.hoisted(() => vi.fn())+const mockUseEmbeddingModelStatus = vi.hoisted(() => vi.fn())+const mockChunkStructure = vi.hoisted(() => vi.fn(() => <div data-testid="chunk-structure" />))+const mockEmbeddingModel = vi.hoisted(() => vi.fn(() => <div data-testid="embedding-model" />))+const mockSummaryIndexSetting = vi.hoisted(() => vi.fn(() => <div data-testid="summary-index-setting" />))+const mockQueryOptions = vi.hoisted(() => vi.fn((options: unknown) => options))++vi.mock('@tanstack/react-query', () => ({+ useQuery: mockUseQuery,+}))++vi.mock('@/service/client', () => ({+ consoleQuery: {+ modelProviders: {+ models: {+ queryOptions: mockQueryOptions,+ },+ },+ },+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useModelList: mockUseModelList,+}))++vi.mock('@/app/components/workflow/hooks', () => ({+ useNodesReadOnly: () => ({ nodesReadOnly: false }),+}))++vi.mock('./hooks/use-config', () => ({+ useConfig: () => ({+ handleChunkStructureChange: vi.fn(),+ handleIndexMethodChange: vi.fn(),+ handleKeywordNumberChange: vi.fn(),+ handleEmbeddingModelChange: vi.fn(),+ handleRetrievalSearchMethodChange: vi.fn(),+ handleHybridSearchModeChange: vi.fn(),+ handleRerankingModelEnabledChange: vi.fn(),+ handleWeighedScoreChange: vi.fn(),+ handleRerankingModelChange: vi.fn(),+ handleTopKChange: vi.fn(),+ handleScoreThresholdChange: vi.fn(),+ handleScoreThresholdEnabledChange: vi.fn(),+ handleInputVariableChange: vi.fn(),+ handleSummaryIndexSettingChange: vi.fn(),+ }),+}))++vi.mock('./hooks/use-embedding-model-status', () => ({+ useEmbeddingModelStatus: mockUseEmbeddingModelStatus,+}))++vi.mock('@/app/components/datasets/settings/utils', () => ({+ checkShowMultiModalTip: () => false,+}))++vi.mock('@/config', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/config')>()+ return {+ ...actual,+ IS_CE_EDITION: true,+ }+})++vi.mock('@/app/components/workflow/nodes/_base/components/layout', () => ({+ Group: ({ children }: { children: ReactNode }) => <div data-testid="group">{children}</div>,+ BoxGroup: ({ children }: { children: ReactNode }) => <div data-testid="box-group">{children}</div>,+ BoxGroupField: ({ children, fieldProps }: { children: ReactNode, fieldProps: { fieldTitleProps: { warningDot?: boolean } } }) => (+ <div data-testid="box-group-field" data-warning-dot={String(!!fieldProps.fieldTitleProps.warningDot)}>+ {children}+ </div>+ ),+}))++vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-reference-picker', () => ({+ default: () => <div data-testid="var-reference-picker" />,+}))++vi.mock('@/app/components/workflow/nodes/_base/components/split', () => ({+ default: () => <div data-testid="split" />,+}))++vi.mock('@/app/components/datasets/settings/summary-index-setting', () => ({+ default: mockSummaryIndexSetting,+}))++vi.mock('./components/chunk-structure', () => ({+ default: mockChunkStructure,+}))++vi.mock('./components/index-method', () => ({+ default: () => <div data-testid="index-method" />,+}))++vi.mock('./components/embedding-model', () => ({+ default: mockEmbeddingModel,+}))++vi.mock('./components/retrieval-setting', () => ({+ default: () => <div data-testid="retrieval-setting" />,+}))++const createData = (overrides: Record<string, unknown> = {}) => ({+ index_chunk_variable_selector: ['chunks', 'results'],+ chunk_structure: ChunkStructureEnum.general,+ indexing_technique: IndexMethodEnum.QUALIFIED,+ embedding_model: 'text-embedding-3-large',+ embedding_model_provider: 'openai',+ keyword_number: 10,+ retrieval_model: {+ search_method: RetrievalSearchMethodEnum.semantic,+ reranking_enable: false,+ top_k: 3,+ score_threshold_enabled: false,+ score_threshold: 0.5,+ },+ ...overrides,+})++const panelProps: PanelProps = {+ getInputVars: () => [],+ toVarInputs: () => [],+ runInputData: {},+ runInputDataRef: { current: {} },+ setRunInputData: vi.fn(),+ runResult: undefined,+}++describe('KnowledgeBasePanel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseQuery.mockReturnValue({ data: undefined })+ mockUseModelList.mockImplementation((modelType: ModelTypeEnum) => {+ if (modelType === ModelTypeEnum.textEmbedding) {+ return {+ data: [{+ provider: 'openai',+ models: [{ model: 'text-embedding-3-large' }],+ }],+ }+ }+ return { data: [] }+ })+ mockUseEmbeddingModelStatus.mockReturnValue({ status: 'active' })+ })++ it('should show a warning dot on chunk structure and skip nested sections when chunk structure is missing', () => {+ render(<Panel id="knowledge-base-1" data={createData({ chunk_structure: undefined }) as never} panelProps={panelProps} />)++ expect(mockChunkStructure).toHaveBeenCalledWith(expect.objectContaining({+ warningDot: true,+ }), undefined)+ expect(screen.queryByTestId('box-group-field')).not.toBeInTheDocument()+ expect(mockQueryOptions).toHaveBeenCalledWith(expect.objectContaining({+ enabled: true,+ }))+ })++ it('should pass warning dots and render summary settings when the qualified configuration needs attention', () => {+ mockUseEmbeddingModelStatus.mockReturnValue({ status: 'disabled' })++ render(<Panel id="knowledge-base-1" data={createData({ index_chunk_variable_selector: [] }) as never} panelProps={panelProps} />)++ expect(screen.getByTestId('box-group-field')).toHaveAttribute('data-warning-dot', 'true')+ expect(mockEmbeddingModel).toHaveBeenCalledWith(expect.objectContaining({+ warningDot: true,+ }), undefined)+ expect(mockQueryOptions).toHaveBeenCalledWith(expect.objectContaining({+ input: { params: { provider: 'openai' } },+ enabled: true,+ }))+ expect(screen.getByTestId('summary-index-setting')).toBeInTheDocument()+ })++ it('should hide embedding and summary settings for non-qualified index methods', () => {+ render(+ <Panel+ id="knowledge-base-1"+ data={createData({ indexing_technique: IndexMethodEnum.ECONOMICAL }) as never}+ panelProps={panelProps}+ />,+ )++ expect(screen.queryByTestId('embedding-model')).not.toBeInTheDocument()+ expect(screen.queryByTestId('summary-index-setting')).not.toBeInTheDocument()+ expect(mockQueryOptions).toHaveBeenCalledWith(expect.objectContaining({+ enabled: false,+ }))+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/panel.tsx b/web/app/components/workflow/nodes/knowledge-base/panel.tsxindex 2845d605bf2..d6041f67468 100644--- a/web/app/components/workflow/nodes/knowledge-base/panel.tsx+++ b/web/app/components/workflow/nodes/knowledge-base/panel.tsx@@ -1,6 +1,7 @@import type { FC } from 'react'import type { KnowledgeBaseNodeType } from './types'import type { NodePanelProps, Var } from '@/app/components/workflow/types'+import { useQuery } from '@tanstack/react-query'import {memo,useCallback,@@ -19,16 +20,22 @@ import {} from '@/app/components/workflow/nodes/_base/components/layout'import VarReferencePicker from '@/app/components/workflow/nodes/_base/components/variable/var-reference-picker'import { IS_CE_EDITION } from '@/config'+import { consoleQuery } from '@/service/client'import Split from '../_base/components/split'import ChunkStructure from './components/chunk-structure'import EmbeddingModel from './components/embedding-model'import IndexMethod from './components/index-method'import RetrievalSetting from './components/retrieval-setting'import { useConfig } from './hooks/use-config'+import { useEmbeddingModelStatus } from './hooks/use-embedding-model-status'import {ChunkStructureEnum,IndexMethodEnum,} from './types'+import {+ getKnowledgeBaseValidationIssue,+ KnowledgeBaseValidationIssueCode,+} from './utils'const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({id,@@ -38,6 +45,22 @@ const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({const { nodesReadOnly } = useNodesReadOnly()const { data: embeddingModelList } = useModelList(ModelTypeEnum.textEmbedding)const { data: rerankModelList } = useModelList(ModelTypeEnum.rerank)+ const chunkStructure = data.chunk_structure+ const indexChunkVariableSelector = data.index_chunk_variable_selector+ const indexingTechnique = data.indexing_technique+ const embeddingModel = data.embedding_model+ const retrievalModel = data.retrieval_model+ const retrievalSearchMethod = retrievalModel?.search_method+ const retrievalRerankingEnable = retrievalModel?.reranking_enable+ const embeddingModelProvider = data.embedding_model_provider+ const { data: embeddingProviderModelList } = useQuery(+ consoleQuery.modelProviders.models.queryOptions({+ input: { params: { provider: embeddingModelProvider || '' } },+ enabled: indexingTechnique === IndexMethodEnum.QUALIFIED && !!embeddingModelProvider,+ refetchOnWindowFocus: false,+ select: response => response.data,+ }),+ )const {handleChunkStructureChange,@@ -108,6 +131,49 @@ const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({})}, [data.embedding_model_provider, data.embedding_model, data.retrieval_model?.reranking_enable, data.retrieval_model?.reranking_model, data.indexing_technique, embeddingModelList, rerankModelList])+ const validationPayload = useMemo(() => {+ return {+ chunk_structure: chunkStructure,+ index_chunk_variable_selector: indexChunkVariableSelector,+ indexing_technique: indexingTechnique,+ embedding_model: embeddingModel,+ embedding_model_provider: embeddingModelProvider,+ retrieval_model: {+ search_method: retrievalSearchMethod,+ reranking_enable: retrievalRerankingEnable,+ reranking_model: retrievalModel?.reranking_model,+ },+ _embeddingModelList: embeddingModelList,+ _embeddingProviderModelList: embeddingProviderModelList,+ _rerankModelList: rerankModelList,+ }+ }, [+ chunkStructure,+ indexChunkVariableSelector,+ indexingTechnique,+ embeddingModel,+ embeddingModelProvider,+ retrievalSearchMethod,+ retrievalRerankingEnable,+ retrievalModel?.reranking_model,+ embeddingModelList,+ embeddingProviderModelList,+ rerankModelList,+ ])++ const validationIssue = useMemo(() => {+ return getKnowledgeBaseValidationIssue(validationPayload)+ }, [validationPayload])+ const { status: embeddingModelStatus } = useEmbeddingModelStatus({+ embeddingModel,+ embeddingModelProvider,+ embeddingModelList,+ })++ const chunkStructureWarning = validationIssue?.code === KnowledgeBaseValidationIssueCode.chunkStructureRequired+ const chunksInputWarning = validationIssue?.code === KnowledgeBaseValidationIssueCode.chunksVariableRequired+ const embeddingModelWarning = indexingTechnique === IndexMethodEnum.QUALIFIED && embeddingModelStatus !== 'active'+return (<div><Group@@ -117,6 +183,7 @@ const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({<ChunkStructurechunkStructure={data.chunk_structure}onChunkStructureChange={handleChunkStructureChange}+ warningDot={chunkStructureWarning}readonly={nodesReadOnly}/></Group>@@ -131,6 +198,7 @@ const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({fieldTitleProps: {title: t('nodes.knowledgeBase.chunksInput', { ns: 'workflow' }),tooltip: t('nodes.knowledgeBase.chunksInputTip', { ns: 'workflow' }),+ warningDot: chunksInputWarning,},}}>@@ -163,6 +231,7 @@ const Panel: FC<NodePanelProps<KnowledgeBaseNodeType>> = ({embeddingModel={data.embedding_model}embeddingModelProvider={data.embedding_model_provider}onEmbeddingModelChange={handleEmbeddingModelChange}+ warningDot={embeddingModelWarning}readonly={nodesReadOnly}/>)diff --git a/web/app/components/workflow/nodes/knowledge-base/types.ts b/web/app/components/workflow/nodes/knowledge-base/types.tsindex aca59d5516c..dbcc926ee3b 100644--- a/web/app/components/workflow/nodes/knowledge-base/types.ts+++ b/web/app/components/workflow/nodes/knowledge-base/types.ts@@ -1,5 +1,5 @@import type { IndexingType } from '@/app/components/datasets/create/step-two'-import type { Model } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { Model, ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'import type { CommonNodeType } from '@/app/components/workflow/types'import type { RerankingModeEnum, WeightedScoreEnum } from '@/models/datasets'import type { RETRIEVE_METHOD } from '@/types/app'@@ -57,6 +57,7 @@ export type KnowledgeBaseNodeType = CommonNodeType & {keyword_number: numberretrieval_model: RetrievalSetting_embeddingModelList?: Model[]+ _embeddingProviderModelList?: ModelItem[]_rerankModelList?: Model[]summary_index_setting?: SummaryIndexSetting}diff --git a/web/app/components/workflow/nodes/knowledge-base/utils.spec.ts b/web/app/components/workflow/nodes/knowledge-base/utils.spec.tsnew file mode 100644index 00000000000..fc911e0133d--- /dev/null+++ b/web/app/components/workflow/nodes/knowledge-base/utils.spec.ts@@ -0,0 +1,226 @@+import type { KnowledgeBaseNodeType } from './types'+import type { Model, ModelItem } from '@/app/components/header/account-setting/model-provider-page/declarations'+import {+ ConfigurationMethodEnum,+ ModelStatusEnum,+ ModelTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import {+ ChunkStructureEnum,+ IndexMethodEnum,+ RetrievalSearchMethodEnum,+} from './types'+import {+ getKnowledgeBaseValidationIssue,+ getKnowledgeBaseValidationMessage,+ isHighQualitySearchMethod,+ isKnowledgeBaseEmbeddingIssue,+ KnowledgeBaseValidationIssueCode,+} from './utils'++const makeEmbeddingModelList = (status: ModelStatusEnum): Model[] => {+ return [+ {+ provider: 'openai',+ icon_small: { en_US: '', zh_Hans: '' },+ label: { en_US: 'OpenAI', zh_Hans: 'OpenAI' },+ models: [{+ model: 'gpt-4o',+ label: { en_US: 'GPT-4o', zh_Hans: 'GPT-4o' },+ model_type: ModelTypeEnum.textEmbedding,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status,+ model_properties: {},+ load_balancing_enabled: false,+ }],+ status,+ },+ ]+}++const makeEmbeddingProviderModelList = (status: ModelStatusEnum): ModelItem[] => {+ return [{+ model: 'gpt-4o',+ label: { en_US: 'GPT-4o', zh_Hans: 'GPT-4o' },+ model_type: ModelTypeEnum.textEmbedding,+ fetch_from: ConfigurationMethodEnum.predefinedModel,+ status,+ model_properties: {},+ load_balancing_enabled: false,+ }]+}++const makePayload = (overrides: Partial<KnowledgeBaseNodeType> = {}): KnowledgeBaseNodeType => {+ return {+ index_chunk_variable_selector: ['general_chunks', 'results'],+ chunk_structure: ChunkStructureEnum.general,+ indexing_technique: IndexMethodEnum.QUALIFIED,+ embedding_model: 'gpt-4o',+ embedding_model_provider: 'openai',+ keyword_number: 10,+ retrieval_model: {+ top_k: 3,+ score_threshold_enabled: false,+ score_threshold: 0.5,+ search_method: RetrievalSearchMethodEnum.semantic,+ },+ _embeddingModelList: makeEmbeddingModelList(ModelStatusEnum.active),+ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.active),+ _rerankModelList: [],+ ...overrides,+ } as KnowledgeBaseNodeType+}++describe('knowledge-base validation issue', () => {+ it('identifies high quality retrieval methods', () => {+ expect(isHighQualitySearchMethod(RetrievalSearchMethodEnum.semantic)).toBe(true)+ expect(isHighQualitySearchMethod(RetrievalSearchMethodEnum.hybrid)).toBe(true)+ expect(isHighQualitySearchMethod(RetrievalSearchMethodEnum.fullText)).toBe(true)+ expect(isHighQualitySearchMethod('unknown-method' as RetrievalSearchMethodEnum)).toBe(false)+ })++ it('returns chunk structure issue when chunk structure is missing', () => {+ const issue = getKnowledgeBaseValidationIssue(makePayload({ chunk_structure: undefined }))+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.chunkStructureRequired)+ })++ it('returns chunks variable issue when chunks selector is empty', () => {+ const issue = getKnowledgeBaseValidationIssue(makePayload({ index_chunk_variable_selector: [] }))+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.chunksVariableRequired)+ })++ it('maps no-configure to configure required', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.noConfigure) }),+ )+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelConfigureRequired)+ })++ it('maps credential-removed to API key unavailable', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.credentialRemoved) }),+ )+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelApiKeyUnavailable)+ })++ it('maps quota-exceeded to credits exhausted', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.quotaExceeded) }),+ )+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelCreditsExhausted)+ })++ it('maps disabled to disabled', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.disabled) }),+ )+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelDisabled)+ })++ it('maps missing provider plugin to incompatible when embedding model is already configured', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({+ embedding_model_provider: 'missing-provider',+ _embeddingProviderModelList: undefined,+ }),+ )+ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelIncompatible)+ })++ it('falls back to provider model list when provider scoped model list is empty', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ _embeddingProviderModelList: [] }),+ )+ expect(issue).toBeNull()+ })++ it('returns embedding-model-not-configured when the qualified index is missing provider details', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ embedding_model: undefined }),+ )++ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelNotConfigured)+ })++ it('maps no-permission embedding models to incompatible', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ _embeddingProviderModelList: makeEmbeddingProviderModelList(ModelStatusEnum.noPermission) }),+ )++ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.embeddingModelIncompatible)+ })++ it('returns retrieval-setting-required when retrieval search method is missing', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({ retrieval_model: undefined as never }),+ )++ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.retrievalSettingRequired)+ })++ it('returns reranking-model-required when reranking is enabled without a model', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({+ retrieval_model: {+ ...makePayload().retrieval_model,+ reranking_enable: true,+ },+ }),+ )++ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.rerankingModelRequired)+ })++ it('returns reranking-model-invalid when the configured reranking model is unavailable', () => {+ const issue = getKnowledgeBaseValidationIssue(+ makePayload({+ retrieval_model: {+ ...makePayload().retrieval_model,+ reranking_enable: true,+ reranking_model: {+ reranking_provider_name: 'missing-provider',+ reranking_model_name: 'missing-model',+ },+ },+ }),+ )++ expect(issue?.code).toBe(KnowledgeBaseValidationIssueCode.rerankingModelInvalid)+ })+})++describe('knowledge-base validation messaging', () => {+ const t = (key: string) => key++ it.each([+ [KnowledgeBaseValidationIssueCode.chunkStructureRequired, 'nodes.knowledgeBase.chunkIsRequired'],+ [KnowledgeBaseValidationIssueCode.chunksVariableRequired, 'nodes.knowledgeBase.chunksVariableIsRequired'],+ [KnowledgeBaseValidationIssueCode.indexMethodRequired, 'nodes.knowledgeBase.indexMethodIsRequired'],+ [KnowledgeBaseValidationIssueCode.embeddingModelNotConfigured, 'nodes.knowledgeBase.embeddingModelNotConfigured'],+ [KnowledgeBaseValidationIssueCode.embeddingModelConfigureRequired, 'modelProvider.selector.configureRequired'],+ [KnowledgeBaseValidationIssueCode.embeddingModelApiKeyUnavailable, 'modelProvider.selector.apiKeyUnavailable'],+ [KnowledgeBaseValidationIssueCode.embeddingModelCreditsExhausted, 'modelProvider.selector.creditsExhausted'],+ [KnowledgeBaseValidationIssueCode.embeddingModelDisabled, 'modelProvider.selector.disabled'],+ [KnowledgeBaseValidationIssueCode.embeddingModelIncompatible, 'modelProvider.selector.incompatible'],+ [KnowledgeBaseValidationIssueCode.retrievalSettingRequired, 'nodes.knowledgeBase.retrievalSettingIsRequired'],+ [KnowledgeBaseValidationIssueCode.rerankingModelRequired, 'nodes.knowledgeBase.rerankingModelIsRequired'],+ [KnowledgeBaseValidationIssueCode.rerankingModelInvalid, 'nodes.knowledgeBase.rerankingModelIsInvalid'],+ ] as const)('maps %s to the expected translation key', (code, expectedKey) => {+ expect(getKnowledgeBaseValidationMessage({ code }, t as never)).toBe(expectedKey)+ })++ it('returns an empty string when there is no issue', () => {+ expect(getKnowledgeBaseValidationMessage(undefined, t as never)).toBe('')+ })+})++describe('isKnowledgeBaseEmbeddingIssue', () => {+ it('returns true for embedding-related issues', () => {+ expect(isKnowledgeBaseEmbeddingIssue({ code: KnowledgeBaseValidationIssueCode.embeddingModelDisabled })).toBe(true)+ })++ it('returns false for non-embedding issues and missing values', () => {+ expect(isKnowledgeBaseEmbeddingIssue({ code: KnowledgeBaseValidationIssueCode.rerankingModelInvalid })).toBe(false)+ expect(isKnowledgeBaseEmbeddingIssue(undefined)).toBe(false)+ })+})diff --git a/web/app/components/workflow/nodes/knowledge-base/utils.ts b/web/app/components/workflow/nodes/knowledge-base/utils.tsindex c05721c0985..d38ae6a565c 100644--- a/web/app/components/workflow/nodes/knowledge-base/utils.ts+++ b/web/app/components/workflow/nodes/knowledge-base/utils.ts@@ -1,3 +1,11 @@+import type { TFunction } from 'i18next'+import type { KnowledgeBaseNodeType } from './types'+import {+ IndexingType,+} from '@/app/components/datasets/create/step-two'+import {+ ModelStatusEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'import {RetrievalSearchMethodEnum,} from './types'@@ -7,3 +15,174 @@ export const isHighQualitySearchMethod = (searchMethod: RetrievalSearchMethodEnu|| searchMethod === RetrievalSearchMethodEnum.hybrid|| searchMethod === RetrievalSearchMethodEnum.fullText}++export enum KnowledgeBaseValidationIssueCode {+ chunkStructureRequired = 'chunk-structure-required',+ chunksVariableRequired = 'chunks-variable-required',+ indexMethodRequired = 'index-method-required',+ embeddingModelNotConfigured = 'embedding-model-not-configured',+ embeddingModelConfigureRequired = 'embedding-model-configure-required',+ embeddingModelApiKeyUnavailable = 'embedding-model-api-key-unavailable',+ embeddingModelCreditsExhausted = 'embedding-model-credits-exhausted',+ embeddingModelDisabled = 'embedding-model-disabled',+ embeddingModelIncompatible = 'embedding-model-incompatible',+ retrievalSettingRequired = 'retrieval-setting-required',+ rerankingModelRequired = 'reranking-model-required',+ rerankingModelInvalid = 'reranking-model-invalid',+}++type KnowledgeBaseValidationIssue = {+ code: KnowledgeBaseValidationIssueCode+}++type KnowledgeBaseValidationPayload = Pick<KnowledgeBaseNodeType, 'chunk_structure' | 'index_chunk_variable_selector' | 'indexing_technique' | 'embedding_model' | 'embedding_model_provider' | '_embeddingModelList' | '_embeddingProviderModelList' | '_rerankModelList'> & {+ retrieval_model?: Pick<KnowledgeBaseNodeType['retrieval_model'], 'search_method' | 'reranking_enable' | 'reranking_model'>+}++const EMBEDDING_ISSUE_CODES = new Set<KnowledgeBaseValidationIssueCode>([+ KnowledgeBaseValidationIssueCode.embeddingModelNotConfigured,+ KnowledgeBaseValidationIssueCode.embeddingModelConfigureRequired,+ KnowledgeBaseValidationIssueCode.embeddingModelApiKeyUnavailable,+ KnowledgeBaseValidationIssueCode.embeddingModelCreditsExhausted,+ KnowledgeBaseValidationIssueCode.embeddingModelDisabled,+ KnowledgeBaseValidationIssueCode.embeddingModelIncompatible,+])++const resolveIssue = (code: KnowledgeBaseValidationIssueCode): KnowledgeBaseValidationIssue => ({+ code,+})++const resolveEmbeddingIssue = (payload: KnowledgeBaseValidationPayload): KnowledgeBaseValidationIssue | null => {+ const {+ embedding_model,+ embedding_model_provider,+ _embeddingModelList,+ _embeddingProviderModelList,+ } = payload++ if (!embedding_model || !embedding_model_provider)+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelNotConfigured)++ const currentEmbeddingModelProvider = _embeddingModelList?.find(provider => provider.provider === embedding_model_provider)+ const hasProviderScopedModelList = !!_embeddingProviderModelList && _embeddingProviderModelList.length > 0+ const embeddingModelCandidates = hasProviderScopedModelList+ ? _embeddingProviderModelList+ : currentEmbeddingModelProvider?.models+ const currentEmbeddingModel = embeddingModelCandidates?.find(model => model.model === embedding_model)++ if (!currentEmbeddingModel) {+ if (!currentEmbeddingModelProvider)+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelIncompatible)++ const providerExists = hasProviderScopedModelList || currentEmbeddingModelProvider+ return resolveIssue(providerExists+ ? KnowledgeBaseValidationIssueCode.embeddingModelIncompatible+ : KnowledgeBaseValidationIssueCode.embeddingModelNotConfigured)+ }++ switch (currentEmbeddingModel.status) {+ case ModelStatusEnum.active:+ return null+ case ModelStatusEnum.noConfigure:+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelConfigureRequired)+ case ModelStatusEnum.credentialRemoved:+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelApiKeyUnavailable)+ case ModelStatusEnum.quotaExceeded:+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelCreditsExhausted)+ case ModelStatusEnum.disabled:+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelDisabled)+ case ModelStatusEnum.noPermission:+ default:+ return resolveIssue(KnowledgeBaseValidationIssueCode.embeddingModelIncompatible)+ }+}++export const getKnowledgeBaseValidationIssue = (payload: KnowledgeBaseValidationPayload): KnowledgeBaseValidationIssue | null => {+ const {+ chunk_structure,+ indexing_technique,+ retrieval_model,+ index_chunk_variable_selector,+ _rerankModelList,+ } = payload++ const {+ search_method,+ reranking_enable,+ reranking_model,+ } = retrieval_model || {}++ if (!chunk_structure)+ return resolveIssue(KnowledgeBaseValidationIssueCode.chunkStructureRequired)++ if (index_chunk_variable_selector.length === 0)+ return resolveIssue(KnowledgeBaseValidationIssueCode.chunksVariableRequired)++ if (!indexing_technique)+ return resolveIssue(KnowledgeBaseValidationIssueCode.indexMethodRequired)++ if (indexing_technique === IndexingType.QUALIFIED) {+ const embeddingIssue = resolveEmbeddingIssue(payload)+ if (embeddingIssue)+ return embeddingIssue+ }++ if (!retrieval_model || !search_method)+ return resolveIssue(KnowledgeBaseValidationIssueCode.retrievalSettingRequired)++ if (reranking_enable) {+ if (!reranking_model || !reranking_model.reranking_provider_name || !reranking_model.reranking_model_name)+ return resolveIssue(KnowledgeBaseValidationIssueCode.rerankingModelRequired)++ const currentRerankingModelProvider = _rerankModelList?.find(provider => provider.provider === reranking_model.reranking_provider_name)+ const currentRerankingModel = currentRerankingModelProvider?.models.find(model => model.model === reranking_model.reranking_model_name)+ if (!currentRerankingModel)+ return resolveIssue(KnowledgeBaseValidationIssueCode.rerankingModelInvalid)+ }++ return null+}++export const getKnowledgeBaseValidationMessage = (+ issue: KnowledgeBaseValidationIssue | null | undefined,+ t: TFunction,+) => {+ if (!issue)+ return ''++ switch (issue.code) {+ case KnowledgeBaseValidationIssueCode.chunkStructureRequired:+ return t('nodes.knowledgeBase.chunkIsRequired', { ns: 'workflow' })+ case KnowledgeBaseValidationIssueCode.chunksVariableRequired:+ return t('nodes.knowledgeBase.chunksVariableIsRequired', { ns: 'workflow' })+ case KnowledgeBaseValidationIssueCode.indexMethodRequired:+ return t('nodes.knowledgeBase.indexMethodIsRequired', { ns: 'workflow' })+ case KnowledgeBaseValidationIssueCode.embeddingModelNotConfigured:+ return t('nodes.knowledgeBase.embeddingModelNotConfigured', { ns: 'workflow' })+ case KnowledgeBaseValidationIssueCode.embeddingModelConfigureRequired:+ return t('modelProvider.selector.configureRequired', { ns: 'common' })+ case KnowledgeBaseValidationIssueCode.embeddingModelApiKeyUnavailable:+ return t('modelProvider.selector.apiKeyUnavailable', { ns: 'common' })+ case KnowledgeBaseValidationIssueCode.embeddingModelCreditsExhausted:+ return t('modelProvider.selector.creditsExhausted', { ns: 'common' })+ case KnowledgeBaseValidationIssueCode.embeddingModelDisabled:+ return t('modelProvider.selector.disabled', { ns: 'common' })+ case KnowledgeBaseValidationIssueCode.embeddingModelIncompatible:+ return t('modelProvider.selector.incompatible', { ns: 'common' })+ case KnowledgeBaseValidationIssueCode.retrievalSettingRequired:+ return t('nodes.knowledgeBase.retrievalSettingIsRequired', { ns: 'workflow' })+ case KnowledgeBaseValidationIssueCode.rerankingModelRequired:+ return t('nodes.knowledgeBase.rerankingModelIsRequired', { ns: 'workflow' })+ case KnowledgeBaseValidationIssueCode.rerankingModelInvalid:+ return t('nodes.knowledgeBase.rerankingModelIsInvalid', { ns: 'workflow' })+ default:+ return ''+ }+}++export const isKnowledgeBaseEmbeddingIssue = (issue: KnowledgeBaseValidationIssue | null | undefined) => {+ if (!issue)+ return false++ return EMBEDDING_ISSUE_CODES.has(issue.code)+}diff --git a/web/app/components/workflow/nodes/llm/default.spec.ts b/web/app/components/workflow/nodes/llm/default.spec.tsnew file mode 100644index 00000000000..938b20be104--- /dev/null+++ b/web/app/components/workflow/nodes/llm/default.spec.ts@@ -0,0 +1,47 @@+import type { LLMNodeType } from './types'+import { AppModeEnum } from '@/types/app'+import { EditionType, PromptRole } from '../../types'+import nodeDefault from './default'++const t = (key: string) => key++const createPayload = (overrides: Partial<LLMNodeType> = {}): LLMNodeType => ({+ ...nodeDefault.defaultValue,+ model: {+ ...nodeDefault.defaultValue.model,+ provider: 'langgenius/openai/gpt-4.1',+ mode: AppModeEnum.CHAT,+ },+ prompt_template: [{+ role: PromptRole.system,+ text: 'You are helpful.',+ edition_type: EditionType.basic,+ }],+ ...overrides,+}) as LLMNodeType++describe('llm default node validation', () => {+ it('should require a model provider before validating the prompt', () => {+ const result = nodeDefault.checkValid(createPayload({+ model: {+ ...nodeDefault.defaultValue.model,+ provider: '',+ name: 'gpt-4.1',+ mode: AppModeEnum.CHAT,+ completion_params: {+ temperature: 0.7,+ },+ },+ }), t)++ expect(result.isValid).toBe(false)+ expect(result.errorMessage).toBe('errorMsg.fieldRequired')+ })++ it('should return a valid result when the provider and prompt are configured', () => {+ const result = nodeDefault.checkValid(createPayload(), t)++ expect(result.isValid).toBe(true)+ expect(result.errorMessage).toBe('')+ })+})diff --git a/web/app/components/workflow/nodes/llm/default.ts b/web/app/components/workflow/nodes/llm/default.tsindex cdd5bfbe6ac..bd6027ec21c 100644--- a/web/app/components/workflow/nodes/llm/default.ts+++ b/web/app/components/workflow/nodes/llm/default.ts@@ -4,6 +4,7 @@ import { genNodeMetaData } from '@/app/components/workflow/utils'// import { RETRIEVAL_OUTPUT_STRUCT } from '../../constants'import { AppModeEnum } from '@/types/app'import { BlockEnum, EditionType, PromptRole } from '../../types'+import { getLLMModelIssue, LLMModelIssueCode } from './utils'const RETRIEVAL_OUTPUT_STRUCT = `{"content": "",@@ -60,7 +61,8 @@ const nodeDefault: NodeDefault<LLMNodeType> = {},checkValid(payload: LLMNodeType, t: any) {let errorMessages = ''- if (!errorMessages && !payload.model.provider)+ const modelIssue = getLLMModelIssue({ modelProvider: payload.model.provider })+ if (!errorMessages && modelIssue === LLMModelIssueCode.providerRequired)errorMessages = t(`${i18nPrefix}.fieldRequired`, { ns: 'workflow', field: t(`${i18nPrefix}.fields.model`, { ns: 'workflow' }) })if (!errorMessages && !payload.memory) {diff --git a/web/app/components/workflow/nodes/llm/panel.spec.tsx b/web/app/components/workflow/nodes/llm/panel.spec.tsxnew file mode 100644index 00000000000..109174e7d2e--- /dev/null+++ b/web/app/components/workflow/nodes/llm/panel.spec.tsx@@ -0,0 +1,248 @@+import type { LLMNodeType } from './types'+import type { ModelProvider } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { ProviderContextState } from '@/context/provider-context'+import type { PanelProps } from '@/types/workflow'+import { render, screen } from '@testing-library/react'+import * as React from 'react'+import { defaultPlan } from '@/app/components/billing/config'+import {+ ConfigurationMethodEnum,+ CurrentSystemQuotaTypeEnum,+ CustomConfigurationStatusEnum,+ ModelTypeEnum,+ PreferredProviderTypeEnum,+} from '@/app/components/header/account-setting/model-provider-page/declarations'+import { useProviderContextSelector } from '@/context/provider-context'+import { AppModeEnum } from '@/types/app'+import { BlockEnum } from '../../types'+import Panel from './panel'++const mockUseConfig = vi.fn()++vi.mock('@/context/provider-context', () => ({+ useProviderContextSelector: vi.fn(),+}))++vi.mock('./use-config', () => ({+ default: (...args: unknown[]) => mockUseConfig(...args),+}))++vi.mock('@/app/components/header/account-setting/model-provider-page/model-parameter-modal', () => ({+ default: () => <div data-testid="model-parameter-modal" />,+}))++vi.mock('./components/config-prompt', () => ({+ default: () => <div data-testid="config-prompt" />,+}))++vi.mock('../_base/components/config-vision', () => ({+ default: () => null,+}))++vi.mock('../_base/components/memory-config', () => ({+ default: () => null,+}))++vi.mock('../_base/components/variable/var-reference-picker', () => ({+ default: () => null,+}))++vi.mock('@/app/components/workflow/nodes/_base/components/prompt/editor', () => ({+ default: () => null,+}))++vi.mock('@/app/components/workflow/nodes/_base/components/variable/var-list', () => ({+ default: () => null,+}))++vi.mock('./components/reasoning-format-config', () => ({+ default: () => null,+}))++vi.mock('./components/structure-output', () => ({+ default: () => null,+}))++vi.mock('@/app/components/workflow/nodes/_base/components/output-vars', () => ({+ default: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,+ VarItem: () => null,+}))++type MockUseConfigReturn = ReturnType<typeof mockUseConfig>++const modelProviderSelector = vi.mocked(useProviderContextSelector)++const createProviderContextState = (modelProviders: ModelProvider[]): ProviderContextState => ({+ modelProviders,+ refreshModelProviders: vi.fn(),+ textGenerationModelList: [],+ supportRetrievalMethods: [],+ isAPIKeySet: true,+ plan: defaultPlan,+ isFetchedPlan: true,+ enableBilling: false,+ onPlanInfoChanged: vi.fn(),+ enableReplaceWebAppLogo: false,+ modelLoadBalancingEnabled: false,+ datasetOperatorEnabled: false,+ enableEducationPlan: false,+ isEducationWorkspace: false,+ isEducationAccount: false,+ allowRefreshEducationVerify: false,+ educationAccountExpireAt: null,+ isLoadingEducationAccountInfo: false,+ isFetchingEducationAccountInfo: false,+ webappCopyrightEnabled: false,+ licenseLimit: {+ workspace_members: {+ size: 0,+ limit: 0,+ },+ },+ refreshLicenseLimit: vi.fn(),+ isAllowTransferWorkspace: false,+ isAllowPublishAsCustomKnowledgePipelineTemplate: false,+ humanInputEmailDeliveryEnabled: false,+})++const createMockModelProvider = (provider: string): ModelProvider => ({+ provider,+ label: { en_US: provider, zh_Hans: provider },+ help: {+ title: { en_US: provider, zh_Hans: provider },+ url: { en_US: '', zh_Hans: '' },+ },+ icon_small: { en_US: '', zh_Hans: '' },+ supported_model_types: [ModelTypeEnum.textGeneration],+ configurate_methods: [ConfigurationMethodEnum.predefinedModel],+ provider_credential_schema: {+ credential_form_schemas: [],+ },+ model_credential_schema: {+ model: {+ label: { en_US: '', zh_Hans: '' },+ placeholder: { en_US: '', zh_Hans: '' },+ },+ credential_form_schemas: [],+ },+ preferred_provider_type: PreferredProviderTypeEnum.system,+ custom_configuration: {+ status: CustomConfigurationStatusEnum.active,+ },+ system_configuration: {+ enabled: true,+ current_quota_type: CurrentSystemQuotaTypeEnum.free,+ quota_configurations: [],+ },+})++const baseNodeData: LLMNodeType = {+ type: BlockEnum.LLM,+ title: 'LLM',+ desc: '',+ model: {+ provider: 'openai',+ name: 'gpt-4o',+ mode: AppModeEnum.CHAT,+ completion_params: {},+ },+ prompt_template: [],+ context: {+ enabled: false,+ variable_selector: [],+ },+ vision: {+ enabled: false,+ },+}++const panelProps = {} as PanelProps++const buildUseConfigResult = (overrides?: Partial<MockUseConfigReturn>) => ({+ readOnly: false,+ inputs: baseNodeData,+ isChatModel: true,+ isChatMode: true,+ isCompletionModel: false,+ shouldShowContextTip: false,+ isVisionModel: false,+ handleModelChanged: vi.fn(),+ hasSetBlockStatus: false,+ handleCompletionParamsChange: vi.fn(),+ handleContextVarChange: vi.fn(),+ filterInputVar: vi.fn(),+ filterVar: vi.fn(),+ availableVars: [],+ availableNodesWithParent: [],+ isShowVars: false,+ handlePromptChange: vi.fn(),+ handleAddEmptyVariable: vi.fn(),+ handleAddVariable: vi.fn(),+ handleVarListChange: vi.fn(),+ handleVarNameChange: vi.fn(),+ handleSyeQueryChange: vi.fn(),+ handleMemoryChange: vi.fn(),+ handleVisionResolutionEnabledChange: vi.fn(),+ handleVisionResolutionChange: vi.fn(),+ isModelSupportStructuredOutput: false,+ structuredOutputCollapsed: false,+ setStructuredOutputCollapsed: vi.fn(),+ handleStructureOutputEnableChange: vi.fn(),+ handleStructureOutputChange: vi.fn(),+ filterJinja2InputVar: vi.fn(),+ handleReasoningFormatChange: vi.fn(),+ ...overrides,+})++const renderPanel = (data?: Partial<LLMNodeType>) => {+ return render(+ <Panel+ id="llm-node"+ data={{ ...baseNodeData, ...data }}+ panelProps={panelProps}+ />,+ )+}++describe('LLM Panel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ modelProviderSelector.mockImplementation(selector => selector(+ createProviderContextState([createMockModelProvider('openai')]),+ ))+ mockUseConfig.mockReturnValue(buildUseConfigResult())+ })++ describe('Model Warning Dot', () => {+ it('should not show the model warning dot when the node only has a connection checklist issue', () => {+ renderPanel()++ const modelField = screen.getByText('workflow.nodes.llm.model').parentElement+ expect(modelField?.querySelector('.bg-text-warning-secondary')).not.toBeInTheDocument()+ })++ it('should show the model warning dot when the model is not configured', () => {+ mockUseConfig.mockReturnValue(buildUseConfigResult({+ inputs: {+ ...baseNodeData,+ model: {+ ...baseNodeData.model,+ provider: '',+ name: '',+ },+ },+ }))++ renderPanel({+ model: {+ ...baseNodeData.model,+ provider: '',+ name: '',+ },+ })++ const modelField = screen.getByText('workflow.nodes.llm.model').parentElement+ expect(modelField?.querySelector('.bg-text-warning-secondary')).toBeInTheDocument()+ })+ })+})diff --git a/web/app/components/workflow/nodes/llm/panel.tsx b/web/app/components/workflow/nodes/llm/panel.tsxindex 5948ee7ac54..b712ceca576 100644--- a/web/app/components/workflow/nodes/llm/panel.tsx+++ b/web/app/components/workflow/nodes/llm/panel.tsx@@ -15,7 +15,9 @@ import OutputVars, { VarItem } from '@/app/components/workflow/nodes/_base/compoimport Editor from '@/app/components/workflow/nodes/_base/components/prompt/editor'import Split from '@/app/components/workflow/nodes/_base/components/split'import VarList from '@/app/components/workflow/nodes/_base/components/variable/var-list'+import { useProviderContextSelector } from '@/context/provider-context'import { fetchAndMergeValidCompletionParams } from '@/utils/completion-params'+import { extractPluginId } from '../../utils/plugin'import ConfigVision from '../_base/components/config-vision'import MemoryConfig from '../_base/components/memory-config'import VarReferencePicker from '../_base/components/variable/var-reference-picker'@@ -23,6 +25,7 @@ import ConfigPrompt from './components/config-prompt'import ReasoningFormatConfig from './components/reasoning-format-config'import StructureOutput from './components/structure-output'import useConfig from './use-config'+import { getLLMModelIssue, LLMModelIssueCode } from './utils'const i18nPrefix = 'nodes.llm'@@ -67,6 +70,18 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({} = useConfig(id, data)const model = inputs.model+ const isModelProviderInstalled = useProviderContextSelector((state) => {+ const modelIssue = getLLMModelIssue({ modelProvider: model?.provider })+ if (modelIssue === LLMModelIssueCode.providerRequired)+ return true++ const modelProviderPluginId = extractPluginId(model.provider)+ return state.modelProviders.some(provider => extractPluginId(provider.provider) === modelProviderPluginId)+ })+ const hasModelWarning = getLLMModelIssue({+ modelProvider: model?.provider,+ isModelProviderInstalled,+ }) !== nullconst handleModelChange = useCallback((model: {provider: string@@ -102,6 +117,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({<Fieldtitle={t(`${i18nPrefix}.model`, { ns: 'workflow' })}required+ warningDot={hasModelWarning}><ModelParameterModalpopupClassName="!w-[387px]"@@ -264,8 +280,8 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({noDecorationpopupContent={(<div className="w-[232px] rounded-xl border-[0.5px] border-components-panel-border bg-components-tooltip-bg px-4 py-3.5 shadow-lg backdrop-blur-[5px]">- <div className="title-xs-semi-bold text-text-primary">{t('structOutput.modelNotSupported', { ns: 'app' })}</div>- <div className="body-xs-regular mt-1 text-text-secondary">{t('structOutput.modelNotSupportedTip', { ns: 'app' })}</div>+ <div className="text-text-primary title-xs-semi-bold">{t('structOutput.modelNotSupported', { ns: 'app' })}</div>+ <div className="mt-1 text-text-secondary body-xs-regular">{t('structOutput.modelNotSupportedTip', { ns: 'app' })}</div></div>)}>@@ -274,7 +290,7 @@ const Panel: FC<NodePanelProps<LLMNodeType>> = ({</div></Tooltip>)}- <div className="system-xs-medium-uppercase mr-0.5 text-text-tertiary">{t('structOutput.structured', { ns: 'app' })}</div>+ <div className="mr-0.5 text-text-tertiary system-xs-medium-uppercase">{t('structOutput.structured', { ns: 'app' })}</div><Tooltip popupContent={<div className="max-w-[150px]">{t('structOutput.structuredTip', { ns: 'app' })}</div>}diff --git a/web/app/components/workflow/nodes/llm/utils.spec.ts b/web/app/components/workflow/nodes/llm/utils.spec.tsnew file mode 100644index 00000000000..4c916651f67--- /dev/null+++ b/web/app/components/workflow/nodes/llm/utils.spec.ts@@ -0,0 +1,43 @@+import { getLLMModelIssue, isLLMModelProviderInstalled, LLMModelIssueCode } from './utils'++describe('llm utils', () => {+ describe('getLLMModelIssue', () => {+ it('returns provider-required when the model provider is missing', () => {+ expect(getLLMModelIssue({ modelProvider: undefined })).toBe(LLMModelIssueCode.providerRequired)+ })++ it('returns provider-plugin-unavailable when the provider plugin is not installed', () => {+ expect(getLLMModelIssue({+ modelProvider: 'langgenius/openai/gpt-4.1',+ isModelProviderInstalled: false,+ })).toBe(LLMModelIssueCode.providerPluginUnavailable)+ })++ it('returns null when the provider is present and installed', () => {+ expect(getLLMModelIssue({+ modelProvider: 'langgenius/openai/gpt-4.1',+ isModelProviderInstalled: true,+ })).toBeNull()+ })+ })++ describe('isLLMModelProviderInstalled', () => {+ it('returns true when the model provider is missing', () => {+ expect(isLLMModelProviderInstalled(undefined, new Set())).toBe(true)+ })++ it('matches installed plugin ids using the provider plugin prefix', () => {+ expect(isLLMModelProviderInstalled(+ 'langgenius/openai/gpt-4.1',+ new Set(['langgenius/openai']),+ )).toBe(true)+ })++ it('returns false when the provider plugin id is not installed', () => {+ expect(isLLMModelProviderInstalled(+ 'langgenius/openai/gpt-4.1',+ new Set(['langgenius/anthropic']),+ )).toBe(false)+ })+ })+})diff --git a/web/app/components/workflow/nodes/llm/utils.ts b/web/app/components/workflow/nodes/llm/utils.tsindex 31b942ee645..662a1cae267 100644--- a/web/app/components/workflow/nodes/llm/utils.ts+++ b/web/app/components/workflow/nodes/llm/utils.ts@@ -2,12 +2,41 @@ import type { ValidationError } from 'jsonschema'import type { ArrayItems, Field, LLMNodeType } from './types'import * as z from 'zod'import { draft07Validator, forbidBooleanProperties } from '@/utils/validators'+import { extractPluginId } from '../../utils/plugin'import { ArrayType, Type } from './types'export const checkNodeValid = (_payload: LLMNodeType) => {return true}+export enum LLMModelIssueCode {+ providerRequired = 'provider-required',+ providerPluginUnavailable = 'provider-plugin-unavailable',+}++export const getLLMModelIssue = ({+ modelProvider,+ isModelProviderInstalled = true,+}: {+ modelProvider?: string+ isModelProviderInstalled?: boolean+}) => {+ if (!modelProvider)+ return LLMModelIssueCode.providerRequired++ if (!isModelProviderInstalled)+ return LLMModelIssueCode.providerPluginUnavailable++ return null+}++export const isLLMModelProviderInstalled = (modelProvider: string | undefined, installedPluginIds: ReadonlySet<string>) => {+ if (!modelProvider)+ return true++ return installedPluginIds.has(extractPluginId(modelProvider))+}+export const getFieldType = (field: Field) => {const { type, items, enum: enums } = fieldif (field.schemaType === 'file')diff --git a/web/app/components/workflow/nodes/tool/__tests__/auth.spec.ts b/web/app/components/workflow/nodes/tool/__tests__/auth.spec.tsnew file mode 100644index 00000000000..d8ae232404b--- /dev/null+++ b/web/app/components/workflow/nodes/tool/__tests__/auth.spec.ts@@ -0,0 +1,33 @@+import { CollectionType } from '@/app/components/tools/types'+import { isToolAuthorizationRequired } from '../auth'++describe('isToolAuthorizationRequired', () => {+ it('should return true for built-in tools that require authorization and are not authorized', () => {+ expect(isToolAuthorizationRequired(CollectionType.builtIn, {+ allow_delete: true,+ is_team_authorization: false,+ })).toBe(true)+ })++ it('should return false when the built-in tool is already authorized', () => {+ expect(isToolAuthorizationRequired(CollectionType.builtIn, {+ allow_delete: true,+ is_team_authorization: true,+ })).toBe(false)+ })++ it('should return false for non-built-in tools even if the provider is unauthorized', () => {+ expect(isToolAuthorizationRequired(CollectionType.custom, {+ allow_delete: true,+ is_team_authorization: false,+ })).toBe(false)+ })++ it('should return false when the collection is missing or authorization is not required', () => {+ expect(isToolAuthorizationRequired(CollectionType.builtIn)).toBe(false)+ expect(isToolAuthorizationRequired(CollectionType.builtIn, {+ allow_delete: false,+ is_team_authorization: false,+ })).toBe(false)+ })+})diff --git a/web/app/components/workflow/nodes/tool/__tests__/node.spec.tsx b/web/app/components/workflow/nodes/tool/__tests__/node.spec.tsxnew file mode 100644index 00000000000..cc7c6b4e0d1--- /dev/null+++ b/web/app/components/workflow/nodes/tool/__tests__/node.spec.tsx@@ -0,0 +1,99 @@+import type { ToolNodeType } from '../types'+import { render, screen } from '@testing-library/react'+import { CollectionType } from '@/app/components/tools/types'+import { BlockEnum } from '@/app/components/workflow/types'+import Node from '../node'++const mockUseNodePluginInstallation = vi.hoisted(() => vi.fn())+const mockUseCurrentToolCollection = vi.hoisted(() => vi.fn())++vi.mock('@/app/components/workflow/hooks/use-node-plugin-installation', () => ({+ useNodePluginInstallation: mockUseNodePluginInstallation,+}))++vi.mock('../hooks/use-current-tool-collection', () => ({+ __esModule: true,+ default: mockUseCurrentToolCollection,+}))++vi.mock('@/app/components/workflow/nodes/_base/components/install-plugin-button', () => ({+ InstallPluginButton: () => <button type="button">Install Plugin</button>,+}))++const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType => ({+ title: 'Google Search',+ desc: '',+ type: BlockEnum.Tool,+ provider_id: 'google_search',+ provider_type: CollectionType.builtIn,+ provider_name: 'Google Search',+ tool_name: 'google_search',+ tool_label: 'Google Search',+ tool_parameters: {},+ tool_configurations: {},+ ...overrides,+})++describe('ToolNode', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseNodePluginInstallation.mockReturnValue({+ isChecking: false,+ isMissing: false,+ uniqueIdentifier: undefined,+ canInstall: false,+ onInstallSuccess: vi.fn(),+ shouldDim: false,+ })+ mockUseCurrentToolCollection.mockReturnValue({+ currentTools: [],+ currCollection: undefined,+ })+ })++ describe('Authorization Warning', () => {+ it('should render the authorization warning when the tool requires authorization and is not authorized', () => {+ mockUseCurrentToolCollection.mockReturnValue({+ currentTools: [],+ currCollection: {+ allow_delete: true,+ is_team_authorization: false,+ },+ })++ render(<Node id="tool-node-1" data={createNodeData()} />)++ expect(screen.getByText('workflow.nodes.tool.authorizationRequired')).toBeInTheDocument()+ })++ it('should keep configuration rows visible when the authorization warning is shown', () => {+ mockUseCurrentToolCollection.mockReturnValue({+ currentTools: [],+ currCollection: {+ allow_delete: true,+ is_team_authorization: false,+ },+ })++ render(+ <Node+ id="tool-node-1"+ data={createNodeData({+ tool_configurations: {+ region: { value: 'us' },+ },+ })}+ />,+ )++ expect(screen.getByText('region')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.tool.authorizationRequired')).toBeInTheDocument()+ })++ it('should render nothing when there are no configs, no install action and no authorization warning', () => {+ const { container } = render(<Node id="tool-node-1" data={createNodeData()} />)++ expect(container).toBeEmptyDOMElement()+ })+ })+})diff --git a/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx b/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsxnew file mode 100644index 00000000000..d15c8a44782--- /dev/null+++ b/web/app/components/workflow/nodes/tool/__tests__/panel.spec.tsx@@ -0,0 +1,309 @@+import type { ReactNode } from 'react'+import type { ToolNodeType } from '../types'+import type { CredentialFormSchema } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { NodePanelProps } from '@/app/components/workflow/types'+import { fireEvent, render, screen } from '@testing-library/react'+import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import { CollectionType } from '@/app/components/tools/types'+import { BlockEnum } from '@/app/components/workflow/types'+import Panel from '../panel'++const mockUseConfig = vi.hoisted(() => vi.fn())+const mockUseStore = vi.hoisted(() => vi.fn())+const mockUseMatchSchemaType = vi.hoisted(() => vi.fn())+const mockGetMatchedSchemaType = vi.hoisted(() => vi.fn())+const mockWrapStructuredVarItem = vi.hoisted(() => vi.fn())+const mockToolForm = vi.hoisted(() => vi.fn())+const mockStructureOutputItem = vi.hoisted(() => vi.fn())+const mockSplit = vi.hoisted(() => vi.fn())++vi.mock('../hooks/use-config', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockUseConfig(...args),+}))++vi.mock('@/app/components/workflow/store', () => ({+ useStore: (selector: (state: typeof mockWorkflowStoreState) => unknown) => mockUseStore(selector),+}))++vi.mock('../../_base/components/variable/use-match-schema-type', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockUseMatchSchemaType(...args),+ getMatchedSchemaType: (...args: unknown[]) => mockGetMatchedSchemaType(...args),+}))++vi.mock('@/app/components/workflow/utils/tool', () => ({+ wrapStructuredVarItem: (...args: unknown[]) => mockWrapStructuredVarItem(...args),+}))++vi.mock('@/app/components/workflow/nodes/_base/components/output-vars', () => ({+ __esModule: true,+ default: (props: {+ title?: string+ children: ReactNode+ collapsed?: boolean+ onCollapse?: (collapsed: boolean) => void+ }) => (+ <div data-testid="output-vars">+ <div>{props.title ?? 'workflow.nodes.common.outputVars'}</div>+ {props.onCollapse && (+ <button type="button" onClick={() => props.onCollapse?.(!props.collapsed)}>+ toggle-output-vars+ </button>+ )}+ <div>{props.children}</div>+ </div>+ ),+ VarItem: (props: {+ name: string+ type: string+ description: string+ }) => (+ <div data-testid={`var-item-${props.name}`}>+ <span>{props.name}</span>+ <span>{props.type}</span>+ <span>{props.description}</span>+ </div>+ ),+}))++vi.mock('../components/tool-form', () => ({+ __esModule: true,+ default: (props: {+ schema: CredentialFormSchema[]+ showManageInputField?: boolean+ onManageInputField?: () => void+ }) => {+ mockToolForm(props)+ return (+ <div data-testid={`tool-form-${props.schema.map(item => item.variable).join('-') || 'empty'}`}>+ {props.showManageInputField && props.onManageInputField && (+ <button type="button" onClick={props.onManageInputField}>+ Manage Input Field+ </button>+ )}+ </div>+ )+ },+}))++vi.mock('@/app/components/workflow/nodes/_base/components/variable/object-child-tree-panel/show', () => ({+ __esModule: true,+ default: (props: { payload: { id: string } }) => {+ mockStructureOutputItem(props)+ return <div data-testid="structured-output">{props.payload.id}</div>+ },+}))++vi.mock('../../_base/components/split', () => ({+ __esModule: true,+ default: (props: { className?: string }) => {+ mockSplit(props)+ return <div data-testid="split">{props.className ?? 'default'}</div>+ },+}))++const mockWorkflowStoreState = {+ pipelineId: undefined as string | undefined,+ setShowInputFieldPanel: vi.fn(),+}++const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType => ({+ title: 'Google Search',+ desc: '',+ type: BlockEnum.Tool,+ provider_id: 'google_search',+ provider_type: CollectionType.builtIn,+ provider_name: 'Google Search',+ tool_name: 'google_search',+ tool_label: 'Google Search',+ tool_parameters: {},+ tool_configurations: {},+ ...overrides,+})++const createSchemaItem = (variable: string): CredentialFormSchema => ({+ name: variable,+ variable,+ label: { en_US: variable, zh_Hans: variable },+ type: FormTypeEnum.textInput,+ required: false,+ show_on: [],+})++const renderPanel = (data: ToolNodeType = createNodeData()) => {+ const props: NodePanelProps<ToolNodeType> = {+ id: 'tool-node-1',+ data,+ panelProps: {+ getInputVars: vi.fn(() => []),+ toVarInputs: vi.fn(() => []),+ runInputData: {},+ runInputDataRef: { current: {} },+ setRunInputData: vi.fn(),+ runResult: null,+ },+ }++ return render(<Panel {...props} />)+}++const createConfigResult = (overrides: Record<string, unknown> = {}) => ({+ readOnly: false,+ inputs: {+ tool_parameters: {},+ tool_configurations: {},+ },+ toolInputVarSchema: [] as CredentialFormSchema[],+ setInputVar: vi.fn(),+ toolSettingSchema: [] as CredentialFormSchema[],+ toolSettingValue: {},+ setToolSettingValue: vi.fn(),+ currCollection: { name: 'google_search' },+ isShowAuthBtn: false,+ isLoading: false,+ outputSchema: [],+ hasObjectOutput: false,+ currTool: { name: 'google_search' },+ ...overrides,+})++describe('ToolPanel', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockWorkflowStoreState.pipelineId = undefined+ mockWorkflowStoreState.setShowInputFieldPanel = vi.fn()+ mockUseStore.mockImplementation(selector => selector(mockWorkflowStoreState))+ mockUseMatchSchemaType.mockReturnValue({+ schemaTypeDefinitions: [{ name: 'structured' }],+ })+ mockGetMatchedSchemaType.mockReturnValue('')+ mockWrapStructuredVarItem.mockImplementation((outputItem, schemaType) => ({+ id: `${outputItem.name}-${schemaType || 'plain'}`,+ }))+ mockUseConfig.mockReturnValue(createConfigResult())+ })++ describe('Loading State', () => {+ it('should render loading when config data is still loading', () => {+ mockUseConfig.mockReturnValue(createConfigResult({+ isLoading: true,+ }))++ renderPanel()++ expect(screen.getByRole('status')).toBeInTheDocument()+ expect(screen.queryByText('workflow.nodes.tool.inputVars')).not.toBeInTheDocument()+ expect(mockToolForm).not.toHaveBeenCalled()+ })+ })++ describe('Form Rendering', () => {+ it('should render input and settings forms and forward the manage input field action', () => {+ mockWorkflowStoreState.pipelineId = 'pipeline-1'+ mockUseConfig.mockReturnValue(createConfigResult({+ inputs: {+ tool_parameters: { query: { value: 'weather' } },+ tool_configurations: {},+ },+ toolInputVarSchema: [createSchemaItem('query')],+ toolSettingSchema: [createSchemaItem('region')],+ toolSettingValue: { region: 'us' },+ }))++ renderPanel()++ expect(screen.getByText('workflow.nodes.tool.inputVars')).toBeInTheDocument()+ expect(screen.getByText('workflow.nodes.tool.settings')).toBeInTheDocument()+ expect(screen.getAllByTestId('split')).toHaveLength(2)++ fireEvent.click(screen.getByRole('button', { name: 'Manage Input Field' }))++ expect(mockToolForm).toHaveBeenCalledTimes(2)+ expect(mockToolForm.mock.calls[0][0]).toEqual(expect.objectContaining({+ nodeId: 'tool-node-1',+ showManageInputField: true,+ }))+ expect(mockToolForm.mock.calls[1][0]).toEqual(expect.objectContaining({+ nodeId: 'tool-node-1',+ }))+ expect(mockToolForm.mock.calls[1][0]).not.toHaveProperty('showManageInputField')+ expect(mockWorkflowStoreState.setShowInputFieldPanel).toHaveBeenCalledWith(true)+ })++ it('should hide editable forms when the auth button is shown but keep output variables visible', () => {+ mockUseConfig.mockReturnValue(createConfigResult({+ isShowAuthBtn: true,+ toolInputVarSchema: [createSchemaItem('query')],+ toolSettingSchema: [createSchemaItem('region')],+ }))++ renderPanel()++ expect(screen.queryByText('workflow.nodes.tool.inputVars')).not.toBeInTheDocument()+ expect(screen.queryByText('workflow.nodes.tool.settings')).not.toBeInTheDocument()+ expect(screen.getByText('text')).toBeInTheDocument()+ expect(screen.getByText('files')).toBeInTheDocument()+ expect(screen.getByText('json')).toBeInTheDocument()+ expect(mockToolForm).not.toHaveBeenCalled()+ })+ })++ describe('Output Schema', () => {+ it('should render scalar and structured outputs with matched schema types', () => {+ mockGetMatchedSchemaType.mockImplementation((value: { type?: string }) => {+ return value?.type === 'string' ? 'qa_structured' : 'object_structured'+ })+ mockUseConfig.mockReturnValue(createConfigResult({+ hasObjectOutput: true,+ outputSchema: [+ {+ name: 'summary',+ type: 'String',+ description: 'Summary field',+ value: { type: 'string' },+ },+ {+ name: 'details',+ type: 'Object',+ description: 'Details field',+ value: { type: 'object', properties: {} },+ },+ ],+ }))++ renderPanel()++ expect(screen.getByText('summary')).toBeInTheDocument()+ expect(screen.getByText('string (qa_structured)')).toBeInTheDocument()+ expect(screen.getByText('Summary field')).toBeInTheDocument()+ expect(screen.getByTestId('structured-output')).toHaveTextContent('details-object_structured')+ expect(mockWrapStructuredVarItem).toHaveBeenCalledWith(expect.objectContaining({+ name: 'details',+ }), 'object_structured')+ expect(mockStructureOutputItem).toHaveBeenCalledWith(expect.objectContaining({+ payload: { id: 'details-object_structured' },+ }))+ })++ it('should render scalar outputs without a schema suffix when no schema type matches', () => {+ mockGetMatchedSchemaType.mockReturnValue('')+ mockUseConfig.mockReturnValue(createConfigResult({+ outputSchema: [+ {+ name: 'summary',+ type: 'String',+ description: 'Summary field',+ value: { type: 'string' },+ },+ ],+ }))++ renderPanel()++ expect(screen.getByTestId('var-item-summary')).toHaveTextContent('summary')+ expect(screen.getByTestId('var-item-summary')).toHaveTextContent('String'.toLowerCase())+ expect(screen.getByTestId('var-item-summary')).not.toHaveTextContent('qa_structured')+ })+ })+})diff --git a/web/app/components/workflow/nodes/tool/auth.ts b/web/app/components/workflow/nodes/tool/auth.tsnew file mode 100644index 00000000000..fa1c1dfb0fe--- /dev/null+++ b/web/app/components/workflow/nodes/tool/auth.ts@@ -0,0 +1,14 @@+import type { ToolWithProvider } from '../../types'+import type { ToolNodeType } from './types'+import { CollectionType } from '@/app/components/tools/types'++type ToolAuthorizationCollection = Pick<ToolWithProvider, 'allow_delete' | 'is_team_authorization'>++export const isToolAuthorizationRequired = (+ providerType: ToolNodeType['provider_type'],+ collection?: ToolAuthorizationCollection,+) => {+ return providerType === CollectionType.builtIn+ && !!collection?.allow_delete+ && collection?.is_team_authorization === false+}diff --git a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsx b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsxnew file mode 100644index 00000000000..51b30d501e6--- /dev/null+++ b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-config.spec.tsx@@ -0,0 +1,194 @@+import type { ToolNodeType } from '../../types'+import { renderHook } from '@testing-library/react'+import { CollectionType } from '@/app/components/tools/types'+import { BlockEnum } from '@/app/components/workflow/types'+import { VarType } from '../../types'+import useConfig from '../use-config'++const mockSetInputs = vi.hoisted(() => vi.fn())+const mockSetControlPromptEditorRerenderKey = vi.hoisted(() => vi.fn())+const mockUseCurrentToolCollection = vi.hoisted(() => vi.fn())+const mockGetConfiguredValue = vi.hoisted(() => vi.fn())+const mockToolParametersToFormSchemas = vi.hoisted(() => vi.fn())++vi.mock('@/app/components/header/account-setting/model-provider-page/hooks', () => ({+ useLanguage: () => 'en_US',+}))++vi.mock('@/app/components/workflow/hooks', () => ({+ useNodesReadOnly: () => ({ nodesReadOnly: false }),+}))++vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({+ __esModule: true,+ default: (_id: string, data: ToolNodeType) => ({+ inputs: data,+ setInputs: mockSetInputs,+ }),+}))++vi.mock('@/app/components/tools/utils/to-form-schema', () => ({+ getConfiguredValue: (...args: unknown[]) => mockGetConfiguredValue(...args),+ toolParametersToFormSchemas: (...args: unknown[]) => mockToolParametersToFormSchemas(...args),+}))++vi.mock('@/service/tools', () => ({+ updateBuiltInToolCredential: vi.fn(),+}))++vi.mock('@/service/use-tools', () => ({+ useInvalidToolsByType: () => vi.fn(),+}))++vi.mock('@/app/components/workflow/store', () => ({+ useWorkflowStore: () => ({+ getState: () => ({+ setControlPromptEditorRerenderKey: mockSetControlPromptEditorRerenderKey,+ }),+ }),+}))++vi.mock('../use-current-tool-collection', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockUseCurrentToolCollection(...args),+}))++const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType => ({+ title: 'Google Search',+ desc: '',+ type: BlockEnum.Tool,+ provider_id: 'google_search',+ provider_type: CollectionType.builtIn,+ provider_name: 'Google Search',+ tool_name: 'google_search',+ tool_label: 'Google Search',+ tool_parameters: {},+ tool_configurations: {},+ ...overrides,+})++const currentTool = {+ name: 'google_search',+ parameters: [+ {+ variable: 'query',+ form: 'llm',+ label: { en_US: 'Query' },+ type: 'string',+ required: true,+ default: 'default query',+ },+ {+ variable: 'api_key',+ form: 'credential',+ label: { en_US: 'API Key' },+ type: 'string',+ required: true,+ default: 'default secret',+ },+ ],+}++const currentToolWithoutDefaults = {+ name: 'google_search',+ parameters: [+ {+ variable: 'query',+ form: 'llm',+ label: { en_US: 'Query' },+ type: 'string',+ required: true,+ },+ {+ variable: 'api_key',+ form: 'credential',+ label: { en_US: 'API Key' },+ type: 'string',+ required: true,+ },+ ],+}++const createToolVarInput = (value: string) => ({+ type: VarType.mixed,+ value,+})++describe('useConfig', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.useFakeTimers()++ mockUseCurrentToolCollection.mockReturnValue({+ currCollection: {+ name: 'google_search',+ allow_delete: true,+ is_team_authorization: false,+ tools: [currentTool],+ },+ })++ mockToolParametersToFormSchemas.mockImplementation(parameters => parameters)+ mockGetConfiguredValue.mockImplementation((_value, schema: Array<{ variable: string, default?: string }>) => {+ return schema.reduce<Record<string, ReturnType<typeof createToolVarInput>>>((acc, item) => {+ acc[item.variable] = createToolVarInput(item.default || '')+ return acc+ }, {} as Record<string, ReturnType<typeof createToolVarInput>>)+ })+ })++ afterEach(() => {+ vi.runOnlyPendingTimers()+ vi.useRealTimers()+ })++ describe('Default Value Sync', () => {+ it('should apply default values only once when the current payload is initially empty', () => {+ const emptyPayload = createNodeData()+ const syncedPayload = createNodeData({+ tool_parameters: { query: createToolVarInput('default query') },+ tool_configurations: { api_key: createToolVarInput('default secret') },+ })++ const { rerender } = renderHook(+ ({ payload }) => useConfig('tool-node-1', payload),+ { initialProps: { payload: emptyPayload } },+ )++ expect(mockSetInputs).toHaveBeenCalledTimes(1)+ expect(mockSetInputs).toHaveBeenCalledWith(expect.objectContaining({+ tool_parameters: { query: createToolVarInput('default query') },+ tool_configurations: { api_key: createToolVarInput('default secret') },+ }))++ rerender({ payload: syncedPayload })++ expect(mockSetInputs).toHaveBeenCalledTimes(1)+ })++ it('should not update inputs when tool values are already populated on first render', () => {+ renderHook(() => useConfig('tool-node-1', createNodeData({+ tool_parameters: { query: createToolVarInput('existing query') },+ tool_configurations: { api_key: createToolVarInput('existing secret') },+ })))++ expect(mockSetInputs).not.toHaveBeenCalled()+ })++ it('should not update inputs when empty schemas do not provide any default values', () => {+ mockUseCurrentToolCollection.mockReturnValue({+ currCollection: {+ name: 'google_search',+ allow_delete: true,+ is_team_authorization: false,+ tools: [currentToolWithoutDefaults],+ },+ })+ mockGetConfiguredValue.mockReturnValue({})++ renderHook(() => useConfig('tool-node-1', createNodeData()))++ expect(mockSetInputs).not.toHaveBeenCalled()+ })+ })+})diff --git a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-current-tool-collection.spec.tsx b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-current-tool-collection.spec.tsxnew file mode 100644index 00000000000..939d0b1bb20--- /dev/null+++ b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-current-tool-collection.spec.tsx@@ -0,0 +1,84 @@+import type { ToolWithProvider } from '@/app/components/workflow/types'+import { renderHook } from '@testing-library/react'+import { CollectionType } from '@/app/components/tools/types'+import useCurrentToolCollection from '../use-current-tool-collection'++const mockUseAllBuiltInTools = vi.hoisted(() => vi.fn())+const mockUseAllCustomTools = vi.hoisted(() => vi.fn())+const mockUseAllWorkflowTools = vi.hoisted(() => vi.fn())+const mockUseAllMCPTools = vi.hoisted(() => vi.fn())+const mockCanFindTool = vi.hoisted(() => vi.fn())++vi.mock('@/service/use-tools', () => ({+ useAllBuiltInTools: () => mockUseAllBuiltInTools(),+ useAllCustomTools: () => mockUseAllCustomTools(),+ useAllWorkflowTools: () => mockUseAllWorkflowTools(),+ useAllMCPTools: () => mockUseAllMCPTools(),+}))++vi.mock('@/utils', () => ({+ canFindTool: (...args: unknown[]) => mockCanFindTool(...args),+}))++const createToolCollection = (overrides: Partial<ToolWithProvider> = {}): ToolWithProvider => ({+ id: 'builtin-search',+ name: 'Google Search',+ type: CollectionType.builtIn,+ label: { en_US: 'Google Search' },+ description: { en_US: 'Search provider' },+ icon: '',+ icon_dark: '',+ background: '',+ tags: [],+ tools: [],+ allow_delete: true,+ is_team_authorization: false,+ meta: {} as ToolWithProvider['meta'],+ ...overrides,+}) as ToolWithProvider++describe('useCurrentToolCollection', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockCanFindTool.mockImplementation((collectionId: string, providerId: string) => collectionId === providerId)+ mockUseAllBuiltInTools.mockReturnValue({ data: [] })+ mockUseAllCustomTools.mockReturnValue({ data: [] })+ mockUseAllWorkflowTools.mockReturnValue({ data: [] })+ mockUseAllMCPTools.mockReturnValue({ data: [] })+ })++ it('should return the built-in collection list and matched provider for built-in tools', () => {+ const builtInCollection = createToolCollection({ id: 'builtin-search' })+ mockUseAllBuiltInTools.mockReturnValue({ data: [builtInCollection] })++ const { result } = renderHook(() => useCurrentToolCollection(CollectionType.builtIn, 'builtin-search'))++ expect(result.current.currentTools).toEqual([builtInCollection])+ expect(result.current.currCollection).toBe(builtInCollection)+ expect(mockCanFindTool).toHaveBeenCalledWith('builtin-search', 'builtin-search')+ })++ it('should select the custom tool collection when the provider type is custom', () => {+ const customCollection = createToolCollection({+ id: 'custom-search',+ type: CollectionType.custom,+ })+ mockUseAllCustomTools.mockReturnValue({ data: [customCollection] })++ const { result } = renderHook(() => useCurrentToolCollection(CollectionType.custom, 'custom-search'))++ expect(result.current.currentTools).toEqual([customCollection])+ expect(result.current.currCollection).toBe(customCollection)+ })++ it('should return undefined when no collection matches the provider id', () => {+ mockUseAllBuiltInTools.mockReturnValue({+ data: [createToolCollection({ id: 'another-tool' })],+ })++ const { result } = renderHook(() => useCurrentToolCollection(CollectionType.builtIn, 'builtin-search'))++ expect(result.current.currentTools).toHaveLength(1)+ expect(result.current.currCollection).toBeUndefined()+ })+})diff --git a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-get-data-for-check-more.spec.ts b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-get-data-for-check-more.spec.tsnew file mode 100644index 00000000000..917adf23970--- /dev/null+++ b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-get-data-for-check-more.spec.ts@@ -0,0 +1,49 @@+import type { ToolNodeType } from '../../types'+import { renderHook } from '@testing-library/react'+import { CollectionType } from '@/app/components/tools/types'+import { BlockEnum } from '@/app/components/workflow/types'+import useGetDataForCheckMore from '../use-get-data-for-check-more'++const mockUseConfig = vi.hoisted(() => vi.fn())++vi.mock('../use-config', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockUseConfig(...args),+}))++const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType => ({+ title: 'Google Search',+ desc: '',+ type: BlockEnum.Tool,+ provider_id: 'google_search',+ provider_type: CollectionType.builtIn,+ provider_name: 'Google Search',+ tool_name: 'google_search',+ tool_label: 'Google Search',+ tool_parameters: {},+ tool_configurations: {},+ ...overrides,+})++describe('useGetDataForCheckMore', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ })++ it('should expose the config hook validator as getData', () => {+ const getMoreDataForCheckValid = vi.fn(() => ({ provider: 'google' }))+ const payload = createNodeData()+ mockUseConfig.mockReturnValue({+ getMoreDataForCheckValid,+ })++ const { result } = renderHook(() => useGetDataForCheckMore({+ id: 'tool-node-1',+ payload,+ }))++ expect(mockUseConfig).toHaveBeenCalledWith('tool-node-1', payload)+ expect(result.current.getData).toBe(getMoreDataForCheckValid)+ expect(result.current.getData()).toEqual({ provider: 'google' })+ })+})diff --git a/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.ts b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.tsnew file mode 100644index 00000000000..2e0dc13cb34--- /dev/null+++ b/web/app/components/workflow/nodes/tool/hooks/__tests__/use-single-run-form-params.spec.ts@@ -0,0 +1,206 @@+import type { ToolNodeType, VarType } from '../../types'+import type { InputVar } from '@/app/components/workflow/types'+import type { NodeTracing } from '@/types/workflow'+import { act, renderHook } from '@testing-library/react'+import { CollectionType } from '@/app/components/tools/types'+import { BlockEnum, InputVarType } from '@/app/components/workflow/types'+import useSingleRunFormParams from '../use-single-run-form-params'++const mockUseToolIcon = vi.hoisted(() => vi.fn())+const mockUseNodeCrud = vi.hoisted(() => vi.fn())+const mockFormatToTracingNodeList = vi.hoisted(() => vi.fn())++vi.mock('@/app/components/workflow/hooks', () => ({+ useToolIcon: (...args: unknown[]) => mockUseToolIcon(...args),+}))++vi.mock('@/app/components/workflow/nodes/_base/hooks/use-node-crud', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockUseNodeCrud(...args),+}))++vi.mock('@/app/components/workflow/run/utils/format-log', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockFormatToTracingNodeList(...args),+}))++const createNodeData = (overrides: Partial<ToolNodeType> = {}): ToolNodeType => ({+ title: 'Google Search',+ desc: '',+ type: BlockEnum.Tool,+ provider_id: 'google_search',+ provider_type: CollectionType.builtIn,+ provider_name: 'Google Search',+ tool_name: 'google_search',+ tool_label: 'Google Search',+ tool_parameters: {},+ tool_configurations: {},+ ...overrides,+})++const createInputVar = (variable: InputVar['variable']): InputVar => ({+ type: InputVarType.textInput,+ label: typeof variable === 'string' ? variable : 'invalid',+ variable,+ required: false,+})++const createRunResult = (): NodeTracing => ({+ id: 'trace-1',+ index: 0,+ predecessor_node_id: '',+ node_id: 'tool-node-1',+ node_type: BlockEnum.Tool,+ title: 'Google Search',+ inputs: {},+ inputs_truncated: false,+ process_data: {},+ process_data_truncated: false,+ outputs_truncated: false,+ status: 'succeeded',+ elapsed_time: 1,+ metadata: {+ iterator_length: 0,+ iterator_index: 0,+ loop_length: 0,+ loop_index: 0,+ },+ created_at: 0,+ created_by: {+ id: 'user-1',+ name: 'User',+ email: '[email protected]',+ },+ finished_at: 1,+})++describe('useSingleRunFormParams', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ mockUseToolIcon.mockReturnValue('tool-icon')+ mockFormatToTracingNodeList.mockReturnValue([{ id: 'formatted-node' }])+ mockUseNodeCrud.mockImplementation((_id: string, payload: ToolNodeType) => ({+ inputs: payload,+ }))+ })++ describe('Variable Extraction', () => {+ it('should build form inputs from variable params and settings and expose dependent vars', () => {+ const payload = createNodeData({+ tool_parameters: {+ query: { type: 'variable' as VarType, value: ['start', 'query'] },+ legacy_query: { type: 'variable' as VarType, value: 'legacy.answer' },+ constant_query: { type: 'constant' as VarType, value: 'fixed' },+ },+ tool_configurations: {+ prompt: { type: 'mixed' as VarType, value: 'prefix {{#tool.result#}}' },+ api_key: { type: 'constant' as VarType, value: 'secret' },+ plainText: 'ignored',+ },+ })+ const getInputVars = vi.fn(() => [+ createInputVar('#start.query#'),+ createInputVar(undefined as unknown as string),+ createInputVar('#legacy.answer#'),+ ])++ const { result } = renderHook(() => useSingleRunFormParams({+ id: 'tool-node-1',+ payload,+ runInputData: {},+ runInputDataRef: { current: {} },+ getInputVars,+ setRunInputData: vi.fn(),+ toVarInputs: vi.fn(),+ runResult: null as unknown as NodeTracing,+ }))++ expect(getInputVars).toHaveBeenCalledWith([+ '{{#start.query#}}',+ '{{#legacy.answer#}}',+ 'prefix {{#tool.result#}}',+ ])+ expect(result.current.forms).toHaveLength(1)+ expect(result.current.forms[0].inputs).toEqual([+ createInputVar('#start.query#'),+ createInputVar(undefined as unknown as string),+ createInputVar('#legacy.answer#'),+ ])+ expect(result.current.forms[0].values).toEqual({})+ expect(result.current.toolIcon).toBe('tool-icon')+ expect(result.current.getDependentVars()).toEqual([+ ['start', 'query'],+ ['legacy', 'answer'],+ ])+ expect(result.current.nodeInfo).toBeNull()+ })+ })++ describe('Form Updates', () => {+ it('should update form values and forward run input data on change', () => {+ const payload = createNodeData({+ tool_parameters: {+ nullable_constant: { type: 'constant' as VarType, value: null },+ query: { type: 'variable' as VarType, value: ['start', 'query'] },+ },+ })+ const getInputVars = vi.fn(() => [createInputVar('#start.query#')])+ const setRunInputData = vi.fn()++ const { result } = renderHook(() => useSingleRunFormParams({+ id: 'tool-node-1',+ payload,+ runInputData: {},+ runInputDataRef: { current: {} },+ getInputVars,+ setRunInputData,+ toVarInputs: vi.fn(),+ runResult: null as unknown as NodeTracing,+ }))++ act(() => {+ result.current.forms[0].onChange({+ query: 'weather',+ tool_parameters: {+ nullable_constant: 'temp-value',+ },+ })+ })++ expect(setRunInputData).toHaveBeenCalledWith({+ query: 'weather',+ tool_parameters: {+ nullable_constant: 'temp-value',+ },+ })+ expect(result.current.forms[0].values).toEqual({+ query: 'weather',+ tool_parameters: {+ nullable_constant: 'temp-value',+ },+ nullable_constant: null,+ })+ })+ })++ describe('Tracing Data', () => {+ it('should format the latest run result into node info when a run result exists', () => {+ const payload = createNodeData()+ const runResult = createRunResult()++ const { result } = renderHook(() => useSingleRunFormParams({+ id: 'tool-node-1',+ payload,+ runInputData: {},+ runInputDataRef: { current: {} },+ getInputVars: vi.fn(() => []),+ setRunInputData: vi.fn(),+ toVarInputs: vi.fn(),+ runResult,+ }))++ expect(mockFormatToTracingNodeList).toHaveBeenCalledWith([runResult], expect.any(Function))+ expect(result.current.nodeInfo).toEqual({ id: 'formatted-node' })+ })+ })+})diff --git a/web/app/components/workflow/nodes/tool/use-config.ts b/web/app/components/workflow/nodes/tool/hooks/use-config.tssimilarity index 83%rename from web/app/components/workflow/nodes/tool/use-config.tsrename to web/app/components/workflow/nodes/tool/hooks/use-config.tsindex 87e91860080..6ebe7bea264 100644--- a/web/app/components/workflow/nodes/tool/use-config.ts+++ b/web/app/components/workflow/nodes/tool/hooks/use-config.ts@@ -1,4 +1,4 @@-import type { ToolNodeType, ToolVarInputs } from './types'+import type { ToolNodeType, ToolVarInputs } from '../types'import type { InputVar } from '@/app/components/workflow/types'import { useBoolean } from 'ahooks'import { capitalize } from 'es-toolkit/string'@@ -16,17 +16,14 @@ import {useNodesReadOnly,} from '@/app/components/workflow/hooks'import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'+import { useWorkflowStore } from '@/app/components/workflow/store'import { updateBuiltInToolCredential } from '@/service/tools'import {- useAllBuiltInTools,- useAllCustomTools,- useAllMCPTools,- useAllWorkflowTools,useInvalidToolsByType,} from '@/service/use-tools'-import { canFindTool } from '@/utils'-import { useWorkflowStore } from '../../store'-import { normalizeJsonSchemaType } from './output-schema-utils'+import { isToolAuthorizationRequired } from '../auth'+import { normalizeJsonSchemaType } from '../output-schema-utils'+import useCurrentToolCollection from './use-current-tool-collection'const formatDisplayType = (output: Record<string, unknown>): string => {const normalizedType = normalizeJsonSchemaType(output) || 'Unknown'@@ -55,33 +52,10 @@ const useConfig = (id: string, payload: ToolNodeType) => {tool_parameters,} = inputsconst isBuiltIn = provider_type === CollectionType.builtIn- const { data: buildInTools } = useAllBuiltInTools()- const { data: customTools } = useAllCustomTools()- const { data: workflowTools } = useAllWorkflowTools()- const { data: mcpTools } = useAllMCPTools()-- const currentTools = useMemo(() => {- switch (provider_type) {- case CollectionType.builtIn:- return buildInTools || []- case CollectionType.custom:- return customTools || []- case CollectionType.workflow:- return workflowTools || []- case CollectionType.mcp:- return mcpTools || []- default:- return []- }- }, [buildInTools, customTools, mcpTools, provider_type, workflowTools])- const currCollection = useMemo(() => {- return currentTools.find(item => canFindTool(item.id, provider_id))- }, [currentTools, provider_id])+ const { currCollection } = useCurrentToolCollection(provider_type, provider_id)// Auth- const needAuth = !!currCollection?.allow_delete- const isAuthed = !!currCollection?.is_team_authorization- const isShowAuthBtn = isBuiltIn && needAuth && !isAuthed+ const isShowAuthBtn = isToolAuthorizationRequired(provider_type, currCollection)const [showSetAuth,{ setTrue: showSetAuthModal, setFalse: hideSetAuthModal },@@ -104,7 +78,6 @@ const useConfig = (id: string, payload: ToolNodeType) => {hideSetAuthModal,t,invalidToolsByType,- provider_type,],)@@ -172,38 +145,49 @@ const useConfig = (id: string, payload: ToolNodeType) => {[inputs, setInputs],)- const formattingParameters = () => {+ const formattingParameters = useCallback(() => {const inputsWithDefaultValue = produce(inputs, (draft) => {if (!draft.tool_configurations|| Object.keys(draft.tool_configurations).length === 0) {- draft.tool_configurations = getConfiguredValue(+ const configuredToolSettings = getConfiguredValue(tool_configurations,toolSettingSchema,) as ToolVarInputs+ if (Object.keys(configuredToolSettings).length > 0)+ draft.tool_configurations = configuredToolSettings}if (!draft.tool_parameters|| Object.keys(draft.tool_parameters).length === 0) {- draft.tool_parameters = getConfiguredValue(+ const configuredToolParameters = getConfiguredValue(tool_parameters,toolInputVarSchema,) as ToolVarInputs+ if (Object.keys(configuredToolParameters).length > 0)+ draft.tool_parameters = configuredToolParameters}})return inputsWithDefaultValue- }+ }, [inputs, toolInputVarSchema, toolSettingSchema, tool_configurations, tool_parameters])useEffect(() => {if (!currTool)returnconst inputsWithDefaultValue = formattingParameters()+ if (inputsWithDefaultValue === inputs)+ return+const { setControlPromptEditorRerenderKey } = workflowStore.getState()setInputs(inputsWithDefaultValue)- setTimeout(() => setControlPromptEditorRerenderKey(Date.now()))- }, [currTool])+ const rerenderTimeout = setTimeout(() => setControlPromptEditorRerenderKey(Date.now()))++ return () => {+ clearTimeout(rerenderTimeout)+ }+ }, [currTool, formattingParameters, inputs, setInputs, workflowStore])// setting when callconst setInputVar = useCallback(diff --git a/web/app/components/workflow/nodes/tool/hooks/use-current-tool-collection.ts b/web/app/components/workflow/nodes/tool/hooks/use-current-tool-collection.tsnew file mode 100644index 00000000000..8a1d0440d2c--- /dev/null+++ b/web/app/components/workflow/nodes/tool/hooks/use-current-tool-collection.ts@@ -0,0 +1,47 @@+import type { ToolNodeType } from '../types'+import type { ToolWithProvider } from '@/app/components/workflow/types'+import { useMemo } from 'react'+import { CollectionType } from '@/app/components/tools/types'+import {+ useAllBuiltInTools,+ useAllCustomTools,+ useAllMCPTools,+ useAllWorkflowTools,+} from '@/service/use-tools'+import { canFindTool } from '@/utils'++const useCurrentToolCollection = (+ providerType: ToolNodeType['provider_type'],+ providerId: string,+) => {+ const { data: buildInTools } = useAllBuiltInTools()+ const { data: customTools } = useAllCustomTools()+ const { data: workflowTools } = useAllWorkflowTools()+ const { data: mcpTools } = useAllMCPTools()++ const currentTools = useMemo<ToolWithProvider[]>(() => {+ switch (providerType) {+ case CollectionType.builtIn:+ return buildInTools || []+ case CollectionType.custom:+ return customTools || []+ case CollectionType.workflow:+ return workflowTools || []+ case CollectionType.mcp:+ return mcpTools || []+ default:+ return []+ }+ }, [buildInTools, customTools, mcpTools, providerType, workflowTools])++ const currCollection = useMemo(() => {+ return currentTools.find(item => canFindTool(item.id, providerId))+ }, [currentTools, providerId])++ return {+ currentTools,+ currCollection,+ }+}++export default useCurrentToolCollectiondiff --git a/web/app/components/workflow/nodes/tool/use-get-data-for-check-more.ts b/web/app/components/workflow/nodes/tool/hooks/use-get-data-for-check-more.tssimilarity index 87%rename from web/app/components/workflow/nodes/tool/use-get-data-for-check-more.tsrename to web/app/components/workflow/nodes/tool/hooks/use-get-data-for-check-more.tsindex 78ebab7bff1..d814f14728e 100644--- a/web/app/components/workflow/nodes/tool/use-get-data-for-check-more.ts+++ b/web/app/components/workflow/nodes/tool/hooks/use-get-data-for-check-more.ts@@ -1,4 +1,4 @@-import type { ToolNodeType } from './types'+import type { ToolNodeType } from '../types'import useConfig from './use-config'type Params = {diff --git a/web/app/components/workflow/nodes/tool/use-single-run-form-params.ts b/web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.tssimilarity index 85%rename from web/app/components/workflow/nodes/tool/use-single-run-form-params.tsrename to web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.tsindex ca1e61be37a..fcef11d5781 100644--- a/web/app/components/workflow/nodes/tool/use-single-run-form-params.ts+++ b/web/app/components/workflow/nodes/tool/hooks/use-single-run-form-params.ts@@ -1,15 +1,15 @@import type { RefObject } from 'react'-import type { ToolNodeType } from './types'+import type { ToolNodeType } from '../types'import type { Props as FormProps } from '@/app/components/workflow/nodes/_base/components/before-run-form/form'import type { InputVar, ValueSelector, Variable } from '@/app/components/workflow/types'import type { NodeTracing } from '@/types/workflow'import { produce } from 'immer'import { useCallback, useMemo, useState } from 'react'import { useTranslation } from 'react-i18next'+import { useToolIcon } from '@/app/components/workflow/hooks'+import useNodeCrud from '@/app/components/workflow/nodes/_base/hooks/use-node-crud'import formatToTracingNodeList from '@/app/components/workflow/run/utils/format-log'-import { useToolIcon } from '../../hooks'-import useNodeCrud from '../_base/hooks/use-node-crud'-import { VarType } from './types'+import { VarType } from '../types'type Params = {id: string@@ -50,9 +50,9 @@ const useSingleRunFormParams = ({return p.value as string}))- const [inputVarValues, doSetInputVarValues] = useState<Record<string, any>>({})- const setInputVarValues = useCallback((value: Record<string, any>) => {- doSetInputVarValues(value)+ const [inputVarValues, setInputVarValues] = useState<Record<string, any>>({})+ const handleInputVarValuesChange = useCallback((value: Record<string, any>) => {+ setInputVarValues(value)setRunInputData(value)}, [setRunInputData])@@ -74,10 +74,10 @@ const useSingleRunFormParams = ({const forms: FormProps[] = [{inputs: varInputs,values: inputVarValuesWithConstantValue(),- onChange: setInputVarValues,+ onChange: handleInputVarValuesChange,}]return forms- }, [inputVarValuesWithConstantValue, setInputVarValues, varInputs])+ }, [handleInputVarValuesChange, inputVarValuesWithConstantValue, varInputs])const nodeInfo = useMemo(() => {if (!runResult)diff --git a/web/app/components/workflow/nodes/tool/node.tsx b/web/app/components/workflow/nodes/tool/node.tsxindex 0cf4f0ff58b..f44b3b7327e 100644--- a/web/app/components/workflow/nodes/tool/node.tsx+++ b/web/app/components/workflow/nodes/tool/node.tsx@@ -2,16 +2,17 @@ import type { FC } from 'react'import type { ToolNodeType } from './types'import type { NodeProps } from '@/app/components/workflow/types'import * as React from 'react'-import { useEffect } from 'react'+import { useTranslation } from 'react-i18next'import { FormTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'-import { useNodeDataUpdate } from '@/app/components/workflow/hooks/use-node-data-update'import { useNodePluginInstallation } from '@/app/components/workflow/hooks/use-node-plugin-installation'import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'+import { isToolAuthorizationRequired } from './auth'+import useCurrentToolCollection from './hooks/use-current-tool-collection'const Node: FC<NodeProps<ToolNodeType>> = ({- id,data,}) => {+ const { t } = useTranslation()const { tool_configurations, paramSchemas } = dataconst toolConfigs = Object.keys(tool_configurations || {})const {@@ -22,25 +23,13 @@ const Node: FC<NodeProps<ToolNodeType>> = ({onInstallSuccess,shouldDim,} = useNodePluginInstallation(data)+ const { currCollection } = useCurrentToolCollection(data.provider_type, data.provider_id)const showInstallButton = !isChecking && isMissing && canInstall && uniqueIdentifier- const { handleNodeDataUpdate } = useNodeDataUpdate()- const shouldLock = !isChecking && isMissing && canInstall && Boolean(uniqueIdentifier)-- useEffect(() => {- if (data._pluginInstallLocked === shouldLock && data._dimmed === shouldDim)- return- handleNodeDataUpdate({- id,- data: {- _pluginInstallLocked: shouldLock,- _dimmed: shouldDim,- },- })- }, [data._pluginInstallLocked, data._dimmed, handleNodeDataUpdate, id, shouldDim, shouldLock])+ const showAuthorizationWarning = isToolAuthorizationRequired(data.provider_type, currCollection)const hasConfigs = toolConfigs.length > 0- if (!showInstallButton && !hasConfigs)+ if (!showInstallButton && !hasConfigs && !showAuthorizationWarning)return nullreturn (@@ -60,10 +49,10 @@ const Node: FC<NodeProps<ToolNodeType>> = ({/></div>)}- {hasConfigs && (+ {(hasConfigs || showAuthorizationWarning) && (<div className="space-y-0.5" aria-disabled={shouldDim}>- {toolConfigs.map((key, index) => (- <div key={index} className="flex h-6 items-center justify-between space-x-1 rounded-md bg-workflow-block-parma-bg px-1 text-xs font-normal text-text-secondary">+ {hasConfigs && toolConfigs.map(key => (+ <div key={key} className="flex h-6 items-center justify-between space-x-1 rounded-md bg-workflow-block-parma-bg px-1 text-xs font-normal text-text-secondary"><div title={key} className="max-w-[100px] shrink-0 truncate text-xs font-medium uppercase text-text-tertiary">{key}</div>@@ -84,6 +73,14 @@ const Node: FC<NodeProps<ToolNodeType>> = ({)}</div>))}+ {showAuthorizationWarning && (+ <div className="flex h-6 items-center rounded-md border-[0.5px] border-state-warning-active bg-state-warning-hover px-1.5">+ <span className="mr-1 size-[4px] shrink-0 rounded-[2px] bg-text-warning-secondary" />+ <div className="grow truncate text-text-warning system-xs-medium" title={t('nodes.tool.authorizationRequired', { ns: 'workflow' })}>+ {t('nodes.tool.authorizationRequired', { ns: 'workflow' })}+ </div>+ </div>+ )}</div>)}</div>diff --git a/web/app/components/workflow/nodes/tool/panel.tsx b/web/app/components/workflow/nodes/tool/panel.tsxindex 899a26ff4fb..a378c01196c 100644--- a/web/app/components/workflow/nodes/tool/panel.tsx+++ b/web/app/components/workflow/nodes/tool/panel.tsx@@ -12,7 +12,7 @@ import { wrapStructuredVarItem } from '@/app/components/workflow/utils/tool'import Split from '../_base/components/split'import useMatchSchemaType, { getMatchedSchemaType } from '../_base/components/variable/use-match-schema-type'import ToolForm from './components/tool-form'-import useConfig from './use-config'+import useConfig from './hooks/use-config'const i18nPrefix = 'nodes.tool'diff --git a/web/app/components/workflow/nodes/trigger-plugin/node.tsx b/web/app/components/workflow/nodes/trigger-plugin/node.tsxindex b7a890223e6..a959d28b040 100644--- a/web/app/components/workflow/nodes/trigger-plugin/node.tsx+++ b/web/app/components/workflow/nodes/trigger-plugin/node.tsx@@ -2,10 +2,9 @@ import type { FC } from 'react'import type { PluginTriggerNodeType } from './types'import type { NodeProps } from '@/app/components/workflow/types'import * as React from 'react'-import { useEffect, useMemo } from 'react'+import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import NodeStatus, { NodeStatusEnum } from '@/app/components/base/node-status'-import { useNodeDataUpdate } from '@/app/components/workflow/hooks/use-node-data-update'import { useNodePluginInstallation } from '@/app/components/workflow/hooks/use-node-plugin-installation'import { InstallPluginButton } from '@/app/components/workflow/nodes/_base/components/install-plugin-button'import useConfig from './use-config'@@ -54,21 +53,7 @@ const Node: FC<NodeProps<PluginTriggerNodeType>> = ({onInstallSuccess,shouldDim,} = useNodePluginInstallation(data)- const { handleNodeDataUpdate } = useNodeDataUpdate()const showInstallButton = !isChecking && isMissing && canInstall && uniqueIdentifier- const shouldLock = !isChecking && isMissing && canInstall && Boolean(uniqueIdentifier)-- useEffect(() => {- if (data._pluginInstallLocked === shouldLock && data._dimmed === shouldDim)- return- handleNodeDataUpdate({- id,- data: {- _pluginInstallLocked: shouldLock,- _dimmed: shouldDim,- },- })- }, [data._pluginInstallLocked, data._dimmed, handleNodeDataUpdate, id, shouldDim, shouldLock])const { t } = useTranslation()diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/object-value-item.tsx b/web/app/components/workflow/panel/chat-variable-panel/components/object-value-item.tsxindex 74765c2b9e8..b573762d7b8 100644--- a/web/app/components/workflow/panel/chat-variable-panel/components/object-value-item.tsx+++ b/web/app/components/workflow/panel/chat-variable-panel/components/object-value-item.tsx@@ -96,7 +96,7 @@ const ObjectValueItem: FC<Props> = ({{/* Key */}<div className="w-[120px] border-r border-gray-200"><input- className="system-xs-regular placeholder:system-xs-regular block h-7 w-full appearance-none px-2 text-text-secondary caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:bg-state-base-hover focus:bg-components-input-bg-active"+ className="block h-7 w-full appearance-none px-2 text-text-secondary caret-primary-600 outline-none system-xs-regular placeholder:text-components-input-text-placeholder placeholder:system-xs-regular hover:bg-state-base-hover focus:bg-components-input-bg-active"placeholder={t('chatVariable.modal.objectKey', { ns: 'workflow' }) || ''}value={list[index].key}onChange={handleKeyChange(index)}@@ -115,7 +115,7 @@ const ObjectValueItem: FC<Props> = ({{/* Value */}<div className="relative w-[230px]"><input- className="system-xs-regular placeholder:system-xs-regular block h-7 w-full appearance-none px-2 text-text-secondary caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:bg-state-base-hover focus:bg-components-input-bg-active"+ className="block h-7 w-full appearance-none px-2 text-text-secondary caret-primary-600 outline-none system-xs-regular placeholder:text-components-input-text-placeholder placeholder:system-xs-regular hover:bg-state-base-hover focus:bg-components-input-bg-active"placeholder={t('chatVariable.modal.objectValue', { ns: 'workflow' }) || ''}value={list[index].value}onChange={handleValueChange(index)}diff --git a/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx b/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsxindex dd14bcf75a5..417e3543142 100644--- a/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx+++ b/web/app/components/workflow/panel/chat-variable-panel/components/variable-modal.tsx@@ -273,7 +273,7 @@ const ChatVariableModal = ({<divclassName={cn('flex h-full w-[360px] flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl', type === ChatVarType.Object && 'w-[480px]')}>- <div className="system-xl-semibold mb-3 flex shrink-0 items-center justify-between p-4 pb-0 text-text-primary">+ <div className="mb-3 flex shrink-0 items-center justify-between p-4 pb-0 text-text-primary system-xl-semibold">{!chatVar ? t('chatVariable.modal.title', { ns: 'workflow' }) : t('chatVariable.modal.editTitle', { ns: 'workflow' })}<div className="flex items-center"><div@@ -287,7 +287,7 @@ const ChatVariableModal = ({<div className="max-h-[480px] overflow-y-auto px-4 py-2">{/* name */}<div className="mb-4">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('chatVariable.modal.name', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('chatVariable.modal.name', { ns: 'workflow' })}</div><div className="flex"><Inputplaceholder={t('chatVariable.modal.namePlaceholder', { ns: 'workflow' }) || ''}@@ -300,7 +300,7 @@ const ChatVariableModal = ({</div>{/* type */}<div className="mb-4">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('chatVariable.modal.type', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('chatVariable.modal.type', { ns: 'workflow' })}</div><div className="flex"><VariableTypeSelectorvalue={type}@@ -312,7 +312,7 @@ const ChatVariableModal = ({</div>{/* default value */}<div className="mb-4">- <div className="system-sm-semibold mb-1 flex h-6 items-center justify-between text-text-secondary">+ <div className="mb-1 flex h-6 items-center justify-between text-text-secondary system-sm-semibold"><div>{t('chatVariable.modal.value', { ns: 'workflow' })}</div>{(type === ChatVarType.ArrayString || type === ChatVarType.ArrayNumber || type === ChatVarType.ArrayBoolean) && (<Button@@ -341,7 +341,7 @@ const ChatVariableModal = ({{type === ChatVarType.String && (// Input will remove \n\r, so use Textarea just like description area<textarea- className="system-sm-regular placeholder:system-sm-regular block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"+ className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none system-sm-regular placeholder:text-components-input-text-placeholder placeholder:system-sm-regular hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"value={value}placeholder={t('chatVariable.modal.valuePlaceholder', { ns: 'workflow' }) || ''}onChange={e => setValue(e.target.value)}@@ -404,10 +404,10 @@ const ChatVariableModal = ({</div>{/* description */}<div className="">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('chatVariable.modal.description', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('chatVariable.modal.description', { ns: 'workflow' })}</div><div className="flex"><textarea- className="system-sm-regular placeholder:system-sm-regular block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"+ className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none system-sm-regular placeholder:text-components-input-text-placeholder placeholder:system-sm-regular hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"value={description}placeholder={t('chatVariable.modal.descriptionPlaceholder', { ns: 'workflow' }) || ''}onChange={e => setDescription(e.target.value)}diff --git a/web/app/components/workflow/panel/env-panel/variable-modal.tsx b/web/app/components/workflow/panel/env-panel/variable-modal.tsxindex 493a73405ab..2aa600ecd33 100644--- a/web/app/components/workflow/panel/env-panel/variable-modal.tsx+++ b/web/app/components/workflow/panel/env-panel/variable-modal.tsx@@ -88,7 +88,7 @@ const VariableModal = ({<divclassName={cn('flex h-full w-[360px] flex-col rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg shadow-2xl')}>- <div className="system-xl-semibold mb-3 flex shrink-0 items-center justify-between p-4 pb-0 text-text-primary">+ <div className="mb-3 flex shrink-0 items-center justify-between p-4 pb-0 text-text-primary system-xl-semibold">{!env ? t('env.modal.title', { ns: 'workflow' }) : t('env.modal.editTitle', { ns: 'workflow' })}<div className="flex items-center"><div@@ -102,12 +102,12 @@ const VariableModal = ({<div className="px-4 py-2">{/* type */}<div className="mb-4">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('env.modal.type', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('env.modal.type', { ns: 'workflow' })}</div><div className="flex gap-2"><divclassName={cn(- 'radius-md system-sm-regular flex w-[106px] cursor-pointer items-center justify-center border border-components-option-card-option-border bg-components-option-card-option-bg p-2 text-text-secondary hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',- type === 'string' && 'system-sm-medium border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary shadow-xs hover:border-components-option-card-option-selected-border',+ 'flex w-[106px] cursor-pointer items-center justify-center border border-components-option-card-option-border bg-components-option-card-option-bg p-2 text-text-secondary system-sm-regular radius-md hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',+ type === 'string' && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary shadow-xs system-sm-medium hover:border-components-option-card-option-selected-border',)}onClick={() => setType('string')}>@@ -115,7 +115,7 @@ const VariableModal = ({</div><divclassName={cn(- 'radius-md system-sm-regular flex w-[106px] cursor-pointer items-center justify-center border border-components-option-card-option-border bg-components-option-card-option-bg p-2 text-text-secondary hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',+ 'flex w-[106px] cursor-pointer items-center justify-center border border-components-option-card-option-border bg-components-option-card-option-bg p-2 text-text-secondary system-sm-regular radius-md hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',type === 'number' && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg font-medium text-text-primary shadow-xs hover:border-components-option-card-option-selected-border',)}onClick={() => {@@ -128,7 +128,7 @@ const VariableModal = ({</div><divclassName={cn(- 'radius-md system-sm-regular flex w-[106px] cursor-pointer items-center justify-center border border-components-option-card-option-border bg-components-option-card-option-bg p-2 text-text-secondary hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',+ 'flex w-[106px] cursor-pointer items-center justify-center border border-components-option-card-option-border bg-components-option-card-option-bg p-2 text-text-secondary system-sm-regular radius-md hover:border-components-option-card-option-border-hover hover:bg-components-option-card-option-bg-hover hover:shadow-xs',type === 'secret' && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg font-medium text-text-primary shadow-xs hover:border-components-option-card-option-selected-border',)}onClick={() => setType('secret')}@@ -147,7 +147,7 @@ const VariableModal = ({</div>{/* name */}<div className="mb-4">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('env.modal.name', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('env.modal.name', { ns: 'workflow' })}</div><div className="flex"><Inputplaceholder={t('env.modal.namePlaceholder', { ns: 'workflow' }) || ''}@@ -160,13 +160,13 @@ const VariableModal = ({</div>{/* value */}<div className="mb-4">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('env.modal.value', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('env.modal.value', { ns: 'workflow' })}</div><div className="flex">{type !== 'number'? (<textarea- className="system-sm-regular placeholder:system-sm-regular block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"+ className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none system-sm-regular placeholder:text-components-input-text-placeholder placeholder:system-sm-regular hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"value={value}placeholder={t('env.modal.valuePlaceholder', { ns: 'workflow' }) || ''}onChange={e => setValue(e.target.value)}@@ -185,10 +185,10 @@ const VariableModal = ({</div>{/* description */}<div className="">- <div className="system-sm-semibold mb-1 flex h-6 items-center text-text-secondary">{t('env.modal.description', { ns: 'workflow' })}</div>+ <div className="mb-1 flex h-6 items-center text-text-secondary system-sm-semibold">{t('env.modal.description', { ns: 'workflow' })}</div><div className="flex"><textarea- className="system-sm-regular placeholder:system-sm-regular block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none placeholder:text-components-input-text-placeholder hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"+ className="block h-20 w-full resize-none appearance-none rounded-lg border border-transparent bg-components-input-bg-normal p-2 text-components-input-text-filled caret-primary-600 outline-none system-sm-regular placeholder:text-components-input-text-placeholder placeholder:system-sm-regular hover:border-components-input-border-hover hover:bg-components-input-bg-hover focus:border-components-input-border-active focus:bg-components-input-bg-active focus:shadow-xs"value={description}placeholder={t('env.modal.descriptionPlaceholder', { ns: 'workflow' }) || ''}onChange={e => setDescription(e.target.value)}diff --git a/web/app/components/workflow/run/index.tsx b/web/app/components/workflow/run/index.tsxindex 96acb1a0269..b96037c7652 100644--- a/web/app/components/workflow/run/index.tsx+++ b/web/app/components/workflow/run/index.tsx@@ -124,7 +124,7 @@ const RunPanel: FC<RunProps> = ({{!hideResult && (<divclassName={cn(- 'system-sm-semibold-uppercase mr-6 cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary',+ 'mr-6 cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary system-sm-semibold-uppercase',currentTab === 'RESULT' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',)}onClick={() => switchTab('RESULT')}@@ -134,7 +134,7 @@ const RunPanel: FC<RunProps> = ({)}<divclassName={cn(- 'system-sm-semibold-uppercase mr-6 cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary',+ 'mr-6 cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary system-sm-semibold-uppercase',currentTab === 'DETAIL' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',)}onClick={() => switchTab('DETAIL')}@@ -143,7 +143,7 @@ const RunPanel: FC<RunProps> = ({</div><divclassName={cn(- 'system-sm-semibold-uppercase mr-6 cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary',+ 'mr-6 cursor-pointer border-b-2 border-transparent py-3 text-text-tertiary system-sm-semibold-uppercase',currentTab === 'TRACING' && '!border-util-colors-blue-brand-blue-brand-600 text-text-primary',)}onClick={() => switchTab('TRACING')}diff --git a/web/app/components/workflow/store/workflow/node-slice.ts b/web/app/components/workflow/store/workflow/node-slice.tsindex b90f23e925e..eb16388ef42 100644--- a/web/app/components/workflow/store/workflow/node-slice.ts+++ b/web/app/components/workflow/store/workflow/node-slice.ts@@ -1,4 +1,5 @@import type { StateCreator } from 'zustand'+import type { ChecklistItem } from '@/app/components/workflow/hooks/use-checklist'import type {VariableAssignerNodeType,} from '@/app/components/workflow/nodes/variable-assigner/types'@@ -10,6 +11,7 @@ import type {} from '@/types/workflow'export type NodeSliceShape = {+ checklistItems: ChecklistItem[]showSingleRunPanel: booleansetShowSingleRunPanel: (showSingleRunPanel: boolean) => voidnodeAnimation: boolean@@ -56,6 +58,7 @@ export type NodeSliceShape = {}export const createNodeSlice: StateCreator<NodeSliceShape> = set => ({+ checklistItems: [],showSingleRunPanel: false,setShowSingleRunPanel: showSingleRunPanel => set(() => ({ showSingleRunPanel })),nodeAnimation: false,diff --git a/web/app/components/workflow/types.ts b/web/app/components/workflow/types.tsindex 871ca301277..b66f7d77cc8 100644--- a/web/app/components/workflow/types.ts+++ b/web/app/components/workflow/types.ts@@ -112,7 +112,6 @@ export type CommonNodeType<T = {}> = {subscription_id?: stringprovider_id?: string_dimmed?: boolean- _pluginInstallLocked?: boolean} & T & Partial<PluginDefaultValue>export type CommonEdgeType = {diff --git a/web/app/components/workflow/update-dsl-modal.tsx b/web/app/components/workflow/update-dsl-modal.tsxindex 08107a0c241..f7a635fc2da 100644--- a/web/app/components/workflow/update-dsl-modal.tsx+++ b/web/app/components/workflow/update-dsl-modal.tsx@@ -262,7 +262,7 @@ const UpdateDSLModal = ({onClose={onCancel}><div className="mb-3 flex items-center justify-between">- <div className="title-2xl-semi-bold text-text-primary">{t('common.importDSL', { ns: 'workflow' })}</div>+ <div className="text-text-primary title-2xl-semi-bold">{t('common.importDSL', { ns: 'workflow' })}</div><div className="flex h-[22px] w-[22px] cursor-pointer items-center justify-center" onClick={onCancel}><RiCloseLine className="h-[18px] w-[18px] text-text-tertiary" /></div>@@ -273,7 +273,7 @@ const UpdateDSLModal = ({<RiAlertFill className="h-4 w-4 shrink-0 text-text-warning-secondary" /></div><div className="flex grow flex-col items-start gap-0.5 py-1">- <div className="system-xs-medium whitespace-pre-line text-text-primary">{t('common.importDSLTip', { ns: 'workflow' })}</div>+ <div className="whitespace-pre-line text-text-primary system-xs-medium">{t('common.importDSLTip', { ns: 'workflow' })}</div><div className="flex items-start gap-1 self-stretch pb-0.5 pt-1"><Buttonsize="small"@@ -290,7 +290,7 @@ const UpdateDSLModal = ({</div></div><div>- <div className="system-md-semibold pt-2 text-text-primary">+ <div className="pt-2 text-text-primary system-md-semibold">{t('common.chooseDSL', { ns: 'workflow' })}</div><div className="flex w-full flex-col items-start justify-center gap-4 self-stretch py-4">@@ -319,8 +319,8 @@ const UpdateDSLModal = ({className="w-[480px]"><div className="flex flex-col items-start gap-2 self-stretch pb-4">- <div className="title-2xl-semi-bold text-text-primary">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>- <div className="system-md-regular flex grow flex-col text-text-secondary">+ <div className="text-text-primary title-2xl-semi-bold">{t('newApp.appCreateDSLErrorTitle', { ns: 'app' })}</div>+ <div className="flex grow flex-col text-text-secondary system-md-regular"><div>{t('newApp.appCreateDSLErrorPart1', { ns: 'app' })}</div><div>{t('newApp.appCreateDSLErrorPart2', { ns: 'app' })}</div><br />diff --git a/web/app/components/workflow/utils/plugin-install-check.spec.ts b/web/app/components/workflow/utils/plugin-install-check.spec.tsnew file mode 100644index 00000000000..e37315328e0--- /dev/null+++ b/web/app/components/workflow/utils/plugin-install-check.spec.ts@@ -0,0 +1,195 @@+import type { TriggerWithProvider } from '../block-selector/types'+import type { CommonNodeType, ToolWithProvider } from '../types'+import { CollectionType } from '@/app/components/tools/types'+import { BlockEnum } from '../types'+import {+ isNodePluginMissing,+ isPluginDependentNode,+ matchDataSource,+ matchToolInCollection,+ matchTriggerProvider,+} from './plugin-install-check'++const createTool = (overrides: Partial<ToolWithProvider> = {}): ToolWithProvider => ({+ id: 'langgenius/search/search',+ name: 'search',+ plugin_id: 'plugin-search',+ provider: 'search-provider',+ plugin_unique_identifier: '[email protected]',+ ...overrides,+} as ToolWithProvider)++const createTriggerProvider = (overrides: Partial<TriggerWithProvider> = {}): TriggerWithProvider => ({+ id: 'trigger-provider-id',+ name: 'trigger-provider',+ plugin_id: 'trigger-plugin',+ ...overrides,+} as TriggerWithProvider)++describe('plugin install check', () => {+ describe('isPluginDependentNode', () => {+ it('should return true for plugin dependent node types', () => {+ expect(isPluginDependentNode(BlockEnum.Tool)).toBe(true)+ expect(isPluginDependentNode(BlockEnum.DataSource)).toBe(true)+ expect(isPluginDependentNode(BlockEnum.TriggerPlugin)).toBe(true)+ })++ it('should return false for non-plugin node types', () => {+ expect(isPluginDependentNode(BlockEnum.LLM)).toBe(false)+ })+ })++ describe('matchToolInCollection', () => {+ const collection = [createTool()]++ it('should match a tool by plugin id', () => {+ expect(matchToolInCollection(collection, { plugin_id: 'plugin-search' })).toEqual(collection[0])+ })++ it('should match a tool by legacy provider id', () => {+ expect(matchToolInCollection(collection, { provider_id: 'search' })).toEqual(collection[0])+ })++ it('should match a tool by provider name', () => {+ expect(matchToolInCollection(collection, { provider_name: 'search' })).toEqual(collection[0])+ })++ it('should return undefined when no tool matches', () => {+ expect(matchToolInCollection(collection, { plugin_id: 'missing-plugin' })).toBeUndefined()+ })+ })++ describe('matchTriggerProvider', () => {+ const providers = [createTriggerProvider()]++ it('should match a trigger provider by name', () => {+ expect(matchTriggerProvider(providers, { provider_name: 'trigger-provider' })).toEqual(providers[0])+ })++ it('should match a trigger provider by id', () => {+ expect(matchTriggerProvider(providers, { provider_id: 'trigger-provider-id' })).toEqual(providers[0])+ })++ it('should match a trigger provider by plugin id', () => {+ expect(matchTriggerProvider(providers, { plugin_id: 'trigger-plugin' })).toEqual(providers[0])+ })+ })++ describe('matchDataSource', () => {+ const dataSources = [createTool({+ provider: 'knowledge-provider',+ plugin_id: 'knowledge-plugin',+ plugin_unique_identifier: '[email protected]',+ })]++ it('should match a data source by unique identifier', () => {+ expect(matchDataSource(dataSources, { plugin_unique_identifier: '[email protected]' })).toEqual(dataSources[0])+ })++ it('should match a data source by plugin id', () => {+ expect(matchDataSource(dataSources, { plugin_id: 'knowledge-plugin' })).toEqual(dataSources[0])+ })++ it('should match a data source by provider name', () => {+ expect(matchDataSource(dataSources, { provider_name: 'knowledge-provider' })).toEqual(dataSources[0])+ })+ })++ describe('isNodePluginMissing', () => {+ it('should report missing tool plugins when the collection is loaded but unmatched', () => {+ const node = {+ type: BlockEnum.Tool,+ title: 'Tool',+ desc: '',+ provider_type: CollectionType.builtIn,+ provider_id: 'missing-provider',+ plugin_unique_identifier: '[email protected]',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { builtInTools: [createTool()] })).toBe(true)+ })++ it('should keep tool nodes installable when the collection has not loaded yet', () => {+ const node = {+ type: BlockEnum.Tool,+ title: 'Tool',+ desc: '',+ provider_type: CollectionType.builtIn,+ provider_id: 'missing-provider',+ plugin_unique_identifier: '[email protected]',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { builtInTools: undefined })).toBe(false)+ })++ it('should ignore unmatched tool nodes without plugin identifiers', () => {+ const node = {+ type: BlockEnum.Tool,+ title: 'Tool',+ desc: '',+ provider_type: CollectionType.builtIn,+ provider_id: 'missing-provider',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { builtInTools: [createTool()] })).toBe(false)+ })++ it('should report missing trigger plugins when no provider matches', () => {+ const node = {+ type: BlockEnum.TriggerPlugin,+ title: 'Trigger',+ desc: '',+ provider_id: 'missing-trigger',+ plugin_unique_identifier: '[email protected]',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { triggerPlugins: [createTriggerProvider()] })).toBe(true)+ })++ it('should keep trigger plugin nodes installable when the provider list has not loaded yet', () => {+ const node = {+ type: BlockEnum.TriggerPlugin,+ title: 'Trigger',+ desc: '',+ provider_id: 'missing-trigger',+ plugin_unique_identifier: '[email protected]',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { triggerPlugins: undefined })).toBe(false)+ })++ it('should report missing data source plugins when the list is loaded but unmatched', () => {+ const node = {+ type: BlockEnum.DataSource,+ title: 'Data Source',+ desc: '',+ provider_name: 'missing-provider',+ plugin_unique_identifier: '[email protected]',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { dataSourceList: [createTool()] })).toBe(true)+ })++ it('should keep data source nodes installable when the list has not loaded yet', () => {+ const node = {+ type: BlockEnum.DataSource,+ title: 'Data Source',+ desc: '',+ provider_name: 'missing-provider',+ plugin_unique_identifier: '[email protected]',+ } as CommonNodeType++ expect(isNodePluginMissing(node, { dataSourceList: undefined })).toBe(false)+ })++ it('should return false for unsupported node types', () => {+ const node = {+ type: BlockEnum.LLM,+ title: 'LLM',+ desc: '',+ } as CommonNodeType++ expect(isNodePluginMissing(node, {})).toBe(false)+ })+ })+})diff --git a/web/app/components/workflow/utils/plugin-install-check.ts b/web/app/components/workflow/utils/plugin-install-check.tsnew file mode 100644index 00000000000..b4d36406191--- /dev/null+++ b/web/app/components/workflow/utils/plugin-install-check.ts@@ -0,0 +1,95 @@+import type { TriggerWithProvider } from '../block-selector/types'+import type { DataSourceNodeType } from '../nodes/data-source/types'+import type { ToolNodeType } from '../nodes/tool/types'+import type { PluginTriggerNodeType } from '../nodes/trigger-plugin/types'+import type { CommonNodeType, ToolWithProvider } from '../types'+import { CollectionType } from '@/app/components/tools/types'+import { canFindTool } from '@/utils'+import { BlockEnum } from '../types'++export const PLUGIN_DEPENDENT_TYPES: BlockEnum[] = [+ BlockEnum.Tool,+ BlockEnum.DataSource,+ BlockEnum.TriggerPlugin,+]++export function isPluginDependentNode(type: string): boolean {+ return PLUGIN_DEPENDENT_TYPES.includes(type as BlockEnum)+}++export function matchToolInCollection(+ collection: ToolWithProvider[],+ data: { plugin_id?: string, provider_id?: string, provider_name?: string },+): ToolWithProvider | undefined {+ return collection.find(tool =>+ (data.plugin_id && tool.plugin_id === data.plugin_id)+ || canFindTool(tool.id, data.provider_id)+ || tool.name === data.provider_name,+ )+}++export function matchTriggerProvider(+ providers: TriggerWithProvider[],+ data: { provider_name?: string, provider_id?: string, plugin_id?: string },+): TriggerWithProvider | undefined {+ return providers.find(provider =>+ provider.name === data.provider_name+ || provider.id === data.provider_id+ || (data.plugin_id && provider.plugin_id === data.plugin_id),+ )+}++export function matchDataSource(+ list: ToolWithProvider[],+ data: { plugin_unique_identifier?: string, plugin_id?: string, provider_name?: string },+): ToolWithProvider | undefined {+ return list.find(item =>+ (data.plugin_unique_identifier && item.plugin_unique_identifier === data.plugin_unique_identifier)+ || (data.plugin_id && item.plugin_id === data.plugin_id)+ || (data.provider_name && item.provider === data.provider_name),+ )+}++export type PluginInstallCheckContext = {+ builtInTools?: ToolWithProvider[]+ customTools?: ToolWithProvider[]+ workflowTools?: ToolWithProvider[]+ mcpTools?: ToolWithProvider[]+ triggerPlugins?: TriggerWithProvider[]+ dataSourceList?: ToolWithProvider[]+}++export function isNodePluginMissing(+ data: CommonNodeType,+ context: PluginInstallCheckContext,+): boolean {+ switch (data.type as BlockEnum) {+ case BlockEnum.Tool: {+ const toolData = data as ToolNodeType+ const collectionMap: Partial<Record<CollectionType, ToolWithProvider[] | undefined>> = {+ [CollectionType.builtIn]: context.builtInTools,+ [CollectionType.custom]: context.customTools,+ [CollectionType.workflow]: context.workflowTools,+ [CollectionType.mcp]: context.mcpTools,+ }+ const collection = collectionMap[toolData.provider_type]+ if (!collection)+ return false+ return !matchToolInCollection(collection, toolData) && Boolean(toolData.plugin_unique_identifier)+ }+ case BlockEnum.TriggerPlugin: {+ const triggerData = data as PluginTriggerNodeType+ if (!context.triggerPlugins)+ return false+ return !matchTriggerProvider(context.triggerPlugins, triggerData) && Boolean(triggerData.plugin_unique_identifier)+ }+ case BlockEnum.DataSource: {+ const dataSourceData = data as DataSourceNodeType+ if (!context.dataSourceList)+ return false+ return !matchDataSource(context.dataSourceList, dataSourceData) && Boolean(dataSourceData.plugin_unique_identifier)+ }+ default:+ return false+ }+}diff --git a/web/app/components/workflow/utils/plugin.ts b/web/app/components/workflow/utils/plugin.tsnew file mode 100644index 00000000000..6ebb088181a--- /dev/null+++ b/web/app/components/workflow/utils/plugin.ts@@ -0,0 +1,4 @@+export function extractPluginId(provider: string): string {+ const parts = provider.split('/')+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : provider+}diff --git a/web/app/components/workflow/utils/tool.ts b/web/app/components/workflow/utils/tool.tsindex 6740cf9be49..3dc41641e2d 100644--- a/web/app/components/workflow/utils/tool.ts+++ b/web/app/components/workflow/utils/tool.ts@@ -7,6 +7,7 @@ import type { StructuredOutput } from '@/app/components/workflow/nodes/llm/typesimport { CollectionType } from '@/app/components/tools/types'import { toolParametersToFormSchemas } from '@/app/components/tools/utils/to-form-schema'import { Type } from '@/app/components/workflow/nodes/llm/types'+import { isToolAuthorizationRequired } from '@/app/components/workflow/nodes/tool/auth'import { canFindTool } from '@/utils'export const getToolCheckParams = (@@ -17,7 +18,6 @@ export const getToolCheckParams = (language: string,) => {const { provider_id, provider_type, tool_name } = toolData- const isBuiltIn = provider_type === CollectionType.builtInconst currentTools = provider_type === CollectionType.builtIn ? buildInTools : provider_type === CollectionType.custom ? customTools : workflowToolsconst currCollection = currentTools.find(item => canFindTool(item.id, provider_id))const currTool = currCollection?.tools.find(tool => tool.name === tool_name)@@ -38,7 +38,7 @@ export const getToolCheckParams = (})return formInputs})(),- notAuthed: isBuiltIn && !!currCollection?.allow_delete && !currCollection?.is_team_authorization,+ notAuthed: isToolAuthorizationRequired(provider_type, currCollection),toolSettingSchema,language,}diff --git a/web/app/education-apply/education-apply-page.tsx b/web/app/education-apply/education-apply-page.tsxindex 636a471d3de..d457409d29f 100644--- a/web/app/education-apply/education-apply-page.tsx+++ b/web/app/education-apply/education-apply-page.tsx@@ -90,11 +90,11 @@ const EducationApplyAge = () => {</div><div className="mx-auto max-w-[720px] px-8 pb-[180px]"><div className="mb-2 flex h-[192px] flex-col justify-end pb-4 pt-3 text-text-primary-on-surface">- <div className="title-5xl-bold mb-2 shadow-xs">{t('toVerified', { ns: 'education' })}</div>- <div className="system-md-medium shadow-xs">+ <div className="mb-2 shadow-xs title-5xl-bold">{t('toVerified', { ns: 'education' })}</div>+ <div className="shadow-xs system-md-medium">{t('toVerifiedTip.front', { ns: 'education' })} - <span className="system-md-semibold underline">{t('toVerifiedTip.coupon', { ns: 'education' })}</span>+ <span className="underline system-md-semibold">{t('toVerifiedTip.coupon', { ns: 'education' })}</span> {t('toVerifiedTip.end', { ns: 'education' })}</div>@@ -103,7 +103,7 @@ const EducationApplyAge = () => {<UserInfo /></div><div className="mb-7">- <div className="system-md-semibold mb-1 flex h-6 items-center text-text-secondary">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-md-semibold">{t('form.schoolName.title', { ns: 'education' })}</div><SearchInput@@ -112,7 +112,7 @@ const EducationApplyAge = () => {/></div><div className="mb-7">- <div className="system-md-semibold mb-1 flex h-6 items-center text-text-secondary">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-md-semibold">{t('form.schoolRole.title', { ns: 'education' })}</div><RoleSelector@@ -121,10 +121,10 @@ const EducationApplyAge = () => {/></div><div className="mb-7">- <div className="system-md-semibold mb-1 flex h-6 items-center text-text-secondary">+ <div className="mb-1 flex h-6 items-center text-text-secondary system-md-semibold">{t('form.terms.title', { ns: 'education' })}</div>- <div className="system-md-regular mb-1 text-text-tertiary">+ <div className="mb-1 text-text-tertiary system-md-regular">{t('form.terms.desc.front', { ns: 'education' })} <a href="https://dify.ai/terms" target="_blank" className="text-text-secondary hover:underline">{t('form.terms.desc.termsOfService', { ns: 'education' })}</a>@@ -134,7 +134,7 @@ const EducationApplyAge = () => {<a href="https://dify.ai/privacy" target="_blank" className="text-text-secondary hover:underline">{t('form.terms.desc.privacyPolicy', { ns: 'education' })}</a>{t('form.terms.desc.end', { ns: 'education' })}</div>- <div className="system-md-regular py-2 text-text-primary">+ <div className="py-2 text-text-primary system-md-regular"><div className="mb-2 flex"><CheckboxclassName="mr-2 shrink-0"@@ -162,7 +162,7 @@ const EducationApplyAge = () => {</Button><div className="mb-4 mt-5 h-px bg-gradient-to-r from-[rgba(16,24,40,0.08)]"></div><a- className="system-xs-regular flex items-center text-text-accent"+ className="flex items-center text-text-accent system-xs-regular"href={docLink('/use-dify/workspace/subscription-management#dify-for-education')}target="_blank">diff --git a/web/context/modal-context-provider.tsx b/web/context/modal-context-provider.tsxindex 8c64642f433..9c86253d6f4 100644--- a/web/context/modal-context-provider.tsx+++ b/web/context/modal-context-provider.tsx@@ -266,8 +266,8 @@ export const ModalContextProvider = ({accountSettingTab && (<AccountSettingactiveTab={accountSettingTab}- onCancel={handleCancelAccountSettingModal}- onTabChange={handleAccountSettingTabChange}+ onCancelAction={handleCancelAccountSettingModal}+ onTabChangeAction={handleAccountSettingTabChange}/>)}diff --git a/web/contract/console/model-providers.ts b/web/contract/console/model-providers.tsnew file mode 100644index 00000000000..2feab369abb--- /dev/null+++ b/web/contract/console/model-providers.ts@@ -0,0 +1,33 @@+import type { ModelItem, PreferredProviderTypeEnum } from '@/app/components/header/account-setting/model-provider-page/declarations'+import type { CommonResponse } from '@/models/common'+import { type } from '@orpc/contract'+import { base } from '../base'++export const modelProvidersModelsContract = base+ .route({+ path: '/workspaces/current/model-providers/{provider}/models',+ method: 'GET',+ })+ .input(type<{+ params: {+ provider: string+ }+ }>())+ .output(type<{+ data: ModelItem[]+ }>())++export const changePreferredProviderTypeContract = base+ .route({+ path: '/workspaces/current/model-providers/{provider}/preferred-provider-type',+ method: 'POST',+ })+ .input(type<{+ params: {+ provider: string+ }+ body: {+ preferred_provider_type: PreferredProviderTypeEnum+ }+ }>())+ .output(type<CommonResponse>())diff --git a/web/contract/console/plugins.ts b/web/contract/console/plugins.tsnew file mode 100644index 00000000000..1b1bc70ffa6--- /dev/null+++ b/web/contract/console/plugins.ts@@ -0,0 +1,27 @@+import type { InstalledLatestVersionResponse, PluginDetail } from '@/app/components/plugins/types'+import { type } from '@orpc/contract'+import { base } from '../base'++export const pluginCheckInstalledContract = base+ .route({+ path: '/workspaces/current/plugin/list/installations/ids',+ method: 'POST',+ })+ .input(type<{+ body: {+ plugin_ids: string[]+ }+ }>())+ .output(type<{ plugins: PluginDetail[] }>())++export const pluginLatestVersionsContract = base+ .route({+ path: '/workspaces/current/plugin/list/latest-versions',+ method: 'POST',+ })+ .input(type<{+ body: {+ plugin_ids: string[]+ }+ }>())+ .output(type<InstalledLatestVersionResponse>())diff --git a/web/contract/router.ts b/web/contract/router.tsindex 0518378aa09..d325cac6601 100644--- a/web/contract/router.ts+++ b/web/contract/router.ts@@ -12,7 +12,9 @@ import {exploreInstalledAppsContract,exploreInstalledAppUninstallContract,} from './console/explore'+import { changePreferredProviderTypeContract, modelProvidersModelsContract } from './console/model-providers'import { notificationContract, notificationDismissContract } from './console/notification'+import { pluginCheckInstalledContract, pluginLatestVersionsContract } from './console/plugins'import { systemFeaturesContract } from './console/system'import {triggerOAuthConfigContract,@@ -64,6 +66,14 @@ export const consoleRouterContract = {parameters: trialAppParametersContract,workflows: trialAppWorkflowsContract,},+ modelProviders: {+ models: modelProvidersModelsContract,+ changePreferredProviderType: changePreferredProviderTypeContract,+ },+ plugins: {+ checkInstalled: pluginCheckInstalledContract,+ latestVersions: pluginLatestVersionsContract,+ },billing: {invoices: invoicesContract,bindPartnerStack: bindPartnerStackContract,diff --git a/web/eslint-suppressions.json b/web/eslint-suppressions.jsonindex 29c2a48253b..6671296efac 100644--- a/web/eslint-suppressions.json+++ b/web/eslint-suppressions.json@@ -275,18 +275,12 @@"app/account/(commonLayout)/account-page/AvatarWithEdit.tsx": {"no-restricted-imports": {"count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1}},"app/account/(commonLayout)/account-page/email-change-modal.tsx": {"no-restricted-imports": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 21- },"ts/no-explicit-any": {"count": 5}@@ -295,12 +289,6 @@"no-restricted-imports": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 14- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 2- },"ts/no-explicit-any": {"count": 1}@@ -434,9 +422,6 @@"app/components/app/annotation/batch-add-annotation-modal/csv-uploader.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1}},"app/components/app/annotation/batch-add-annotation-modal/index.tsx": {@@ -662,9 +647,6 @@"no-restricted-imports": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 1- },"ts/no-explicit-any": {"count": 3}@@ -815,9 +797,6 @@"app/components/app/configuration/config/agent/prompt-editor.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 1}},"app/components/app/configuration/config/assistant-type-picker/index.tsx": {@@ -894,12 +873,6 @@"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 4},- "tailwindcss/enforce-consistent-class-order": {- "count": 1- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 1- },"ts/no-explicit-any": {"count": 2}@@ -1006,9 +979,6 @@"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 5- },"ts/no-explicit-any": {"count": 3}@@ -1084,9 +1054,6 @@"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 2- },"ts/no-explicit-any": {"count": 11}@@ -1106,12 +1073,6 @@"style/multiline-ternary": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 2- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 2- },"ts/no-explicit-any": {"count": 24}@@ -1138,9 +1099,6 @@"no-restricted-imports": {"count": 3},- "tailwindcss/no-unnecessary-whitespace": {- "count": 1- },"ts/no-explicit-any": {"count": 2}@@ -1212,17 +1170,11 @@},"react-refresh/only-export-components": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 5}},"app/components/app/create-from-dsl-modal/uploader.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 1}},"app/components/app/duplicate-modal/index.tsx": {@@ -1261,9 +1213,6 @@"style/multiline-ternary": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 12- },"ts/no-explicit-any": {"count": 14}@@ -2694,11 +2643,6 @@"count": 2}},- "app/components/base/prompt-editor/plugins/workflow-variable-block/component.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/base/prompt-editor/plugins/workflow-variable-block/index.tsx": {"react-refresh/only-export-components": {"count": 4@@ -2965,11 +2909,6 @@"count": 2}},- "app/components/billing/pricing/index.tsx": {- "react-refresh/only-export-components": {- "count": 1- }- },"app/components/billing/pricing/plan-switcher/plan-range-switcher.tsx": {"react-refresh/only-export-components": {"count": 1@@ -3725,9 +3664,6 @@"app/components/datasets/documents/detail/batch-modal/csv-uploader.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 1}},"app/components/datasets/documents/detail/batch-modal/index.tsx": {@@ -3854,9 +3790,6 @@"no-restricted-imports": {"count": 1},- "tailwindcss/enforce-consistent-class-order": {- "count": 3- },"ts/no-explicit-any": {"count": 1}@@ -3933,9 +3866,6 @@"no-restricted-imports": {"count": 1},- "tailwindcss/enforce-consistent-class-order": {- "count": 3- },"ts/no-explicit-any": {"count": 1}@@ -3985,9 +3915,6 @@},"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 5}},"app/components/datasets/external-api/external-api-panel/index.tsx": {@@ -4372,9 +4299,6 @@"app/components/datasets/settings/summary-index-setting.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 11}},"app/components/develop/code.tsx": {@@ -4553,12 +4477,6 @@"app/components/header/account-dropdown/workplace-selector/index.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 3- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 2}},"app/components/header/account-setting/api-based-extension-page/empty.tsx": {@@ -4692,11 +4610,6 @@"count": 3}},- "app/components/header/account-setting/index.tsx": {- "react-hooks-extra/no-direct-set-state-in-use-effect": {- "count": 1- }- },"app/components/header/account-setting/key-validator/declarations.ts": {"ts/no-explicit-any": {"count": 1@@ -4708,11 +4621,6 @@}},"app/components/header/account-setting/members-page/edit-workspace-modal/index.tsx": {- "no-restricted-imports": {- "count": 2- }- },- "app/components/header/account-setting/members-page/index.tsx": {"no-restricted-imports": {"count": 1}@@ -4743,9 +4651,6 @@"app/components/header/account-setting/members-page/operation/index.tsx": {"no-restricted-imports": {"count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 5}},"app/components/header/account-setting/members-page/operation/transfer-ownership.tsx": {@@ -4775,16 +4680,8 @@}},"app/components/header/account-setting/model-provider-page/hooks.ts": {- "react-hooks-extra/no-direct-set-state-in-use-effect": {- "count": 1- },"ts/no-explicit-any": {- "count": 3- }- },- "app/components/header/account-setting/model-provider-page/install-from-marketplace.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 3+ "count": 2}},"app/components/header/account-setting/model-provider-page/model-auth/add-credential-in-load-balancing.tsx": {@@ -4808,14 +4705,6 @@"count": 1}},- "app/components/header/account-setting/model-provider-page/model-auth/authorized/credential-item.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/model-auth/authorized/index.tsx": {"no-restricted-imports": {"count": 3@@ -4866,11 +4755,6 @@"count": 3}},- "app/components/header/account-setting/model-provider-page/model-badge/index.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/model-modal/Form.tsx": {"no-restricted-imports": {"count": 2@@ -4885,24 +4769,10 @@}},"app/components/header/account-setting/model-provider-page/model-modal/index.tsx": {- "no-restricted-imports": {- "count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 6- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 1- },"ts/no-explicit-any": {"count": 5}},- "app/components/header/account-setting/model-provider-page/model-name/index.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/model-parameter-modal/agent-model-trigger.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -4913,14 +4783,6 @@"count": 2}},- "app/components/header/account-setting/model-provider-page/model-parameter-modal/index.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 3- }- },"app/components/header/account-setting/model-provider-page/model-parameter-modal/model-display.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -4929,19 +4791,6 @@"count": 1}},- "app/components/header/account-setting/model-provider-page/model-parameter-modal/parameter-item.tsx": {- "no-restricted-imports": {- "count": 2- }- },- "app/components/header/account-setting/model-provider-page/model-parameter-modal/presets-parameter.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/model-parameter-modal/status-indicators.tsx": {"no-restricted-imports": {"count": 1@@ -4953,55 +4802,11 @@"count": 2}},- "app/components/header/account-setting/model-provider-page/model-parameter-modal/trigger.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 2- }- },- "app/components/header/account-setting/model-provider-page/model-selector/deprecated-model-trigger.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/model-selector/feature-icon.tsx": {"no-restricted-imports": {"count": 1}},- "app/components/header/account-setting/model-provider-page/model-selector/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "app/components/header/account-setting/model-provider-page/model-selector/model-trigger.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "app/components/header/account-setting/model-provider-page/model-selector/popup-item.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 3- }- },- "app/components/header/account-setting/model-provider-page/model-selector/popup.tsx": {- "no-restricted-imports": {- "count": 1- }- },- "app/components/header/account-setting/model-provider-page/provider-added-card/add-model-button.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/header/account-setting/model-provider-page/provider-added-card/cooldown-timer.tsx": {"no-restricted-imports": {"count": 1@@ -5010,28 +4815,14 @@"count": 2}},- "app/components/header/account-setting/model-provider-page/provider-added-card/credential-panel.tsx": {+ "app/components/header/account-setting/model-provider-page/provider-added-card/model-auth-dropdown/use-activate-credential.ts": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1- },- "ts/no-explicit-any": {- "count": 1- }- },- "app/components/header/account-setting/model-provider-page/provider-added-card/index.tsx": {- "ts/no-explicit-any": {- "count": 1}},"app/components/header/account-setting/model-provider-page/provider-added-card/model-list-item.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1}},"app/components/header/account-setting/model-provider-page/provider-added-card/model-list.tsx": {@@ -5063,22 +4854,14 @@"count": 1}},- "app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx": {+ "app/components/header/account-setting/model-provider-page/provider-added-card/use-change-provider-priority.ts": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 2- }- },- "app/components/header/account-setting/model-provider-page/provider-icon/index.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 1}},"app/components/header/account-setting/model-provider-page/system-model-selector/index.tsx": {"no-restricted-imports": {- "count": 3+ "count": 1}},"app/components/header/account-setting/plugin-page/SerpapiPlugin.tsx": {@@ -5104,11 +4887,6 @@"count": 1}},- "app/components/header/index.tsx": {- "tailwindcss/no-unnecessary-whitespace": {- "count": 1- }- },"app/components/header/license-env/index.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 3@@ -5173,11 +4951,6 @@"count": 2}},- "app/components/plugins/card/index.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/plugins/install-plugin/base/installed.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -5385,9 +5158,6 @@"no-restricted-imports": {"count": 4},- "tailwindcss/enforce-consistent-class-order": {- "count": 2- },"ts/no-explicit-any": {"count": 2}@@ -5489,11 +5259,6 @@"count": 1}},- "app/components/plugins/plugin-detail-panel/detail-header/components/header-modals.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/plugins/plugin-detail-panel/detail-header/components/plugin-source-badge.tsx": {"no-restricted-imports": {"count": 1@@ -5507,11 +5272,6 @@"count": 1}},- "app/components/plugins/plugin-detail-panel/detail-header/index.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/plugins/plugin-detail-panel/endpoint-card.tsx": {"no-restricted-imports": {"count": 3@@ -5555,9 +5315,6 @@},"app/components/plugins/plugin-detail-panel/model-selector/index.tsx": {"no-restricted-imports": {- "count": 2- },- "tailwindcss/enforce-consistent-class-order": {"count": 1},"ts/no-explicit-any": {@@ -5591,14 +5348,6 @@"count": 1}},- "app/components/plugins/plugin-detail-panel/operation-dropdown.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 4- }- },"app/components/plugins/plugin-detail-panel/strategy-detail.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 11@@ -5866,11 +5615,6 @@"count": 1}},- "app/components/plugins/plugin-page/plugin-tasks/components/plugin-task-list.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 2- }- },"app/components/plugins/plugin-page/plugin-tasks/components/task-status-indicator.tsx": {"no-restricted-imports": {"count": 1@@ -5955,25 +5699,9 @@"count": 30}},- "app/components/plugins/update-plugin/downgrade-warning.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 2- }- },"app/components/plugins/update-plugin/from-market-place.tsx": {- "no-restricted-imports": {- "count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },- "app/components/plugins/update-plugin/plugin-version-picker.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 3}},"app/components/rag-pipeline/components/chunk-card-list/chunk-card.tsx": {@@ -6163,9 +5891,6 @@"app/components/rag-pipeline/components/rag-pipeline-header/publisher/popup.tsx": {"no-restricted-imports": {"count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 8}},"app/components/rag-pipeline/components/rag-pipeline-header/run-mode.tsx": {@@ -6848,11 +6573,6 @@"count": 6}},- "app/components/workflow/header/checklist.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/workflow/header/editing-title.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -6878,9 +6598,6 @@"no-restricted-imports": {"count": 1},- "tailwindcss/enforce-consistent-class-order": {- "count": 2- },"ts/no-explicit-any": {"count": 1}@@ -6942,7 +6659,7 @@"count": 1},"ts/no-empty-object-type": {- "count": 2+ "count": 1},"ts/no-explicit-any": {"count": 4@@ -7151,9 +6868,6 @@"app/components/workflow/nodes/_base/components/field.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 2}},"app/components/workflow/nodes/_base/components/file-type-item.tsx": {@@ -7215,14 +6929,6 @@"count": 1}},- "app/components/workflow/nodes/_base/components/layout/field-title.tsx": {- "no-restricted-imports": {- "count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 1- }- },"app/components/workflow/nodes/_base/components/layout/index.tsx": {"react-refresh/only-export-components": {"count": 7@@ -7320,9 +7026,6 @@"no-restricted-imports": {"count": 1},- "tailwindcss/no-unnecessary-whitespace": {- "count": 2- },"ts/no-explicit-any": {"count": 4}@@ -7468,11 +7171,6 @@"count": 1}},- "app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-label.tsx": {- "no-restricted-imports": {- "count": 1- }- },"app/components/workflow/nodes/_base/components/variable/variable-label/base/variable-name.tsx": {"tailwindcss/enforce-consistent-class-order": {"count": 1@@ -8128,11 +7826,6 @@"count": 2}},- "app/components/workflow/nodes/knowledge-base/node.tsx": {- "tailwindcss/enforce-consistent-class-order": {- "count": 4- }- },"app/components/workflow/nodes/knowledge-base/use-single-run-form-params.ts": {"ts/no-explicit-any": {"count": 3@@ -8439,9 +8132,6 @@"app/components/workflow/nodes/llm/panel.tsx": {"no-restricted-imports": {"count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 3}},"app/components/workflow/nodes/llm/use-config.ts": {@@ -8746,9 +8436,17 @@"count": 7}},- "app/components/workflow/nodes/tool/node.tsx": {- "tailwindcss/no-unnecessary-whitespace": {+ "app/components/workflow/nodes/tool/hooks/use-config.ts": {+ "no-restricted-imports": {"count": 1+ },+ "ts/no-explicit-any": {+ "count": 6+ }+ },+ "app/components/workflow/nodes/tool/hooks/use-single-run-form-params.ts": {+ "ts/no-explicit-any": {+ "count": 6}},"app/components/workflow/nodes/tool/output-schema-utils.ts": {@@ -8766,19 +8464,6 @@"count": 3}},- "app/components/workflow/nodes/tool/use-config.ts": {- "no-restricted-imports": {- "count": 1- },- "ts/no-explicit-any": {- "count": 6- }- },- "app/components/workflow/nodes/tool/use-single-run-form-params.ts": {- "ts/no-explicit-any": {- "count": 6- }- },"app/components/workflow/nodes/trigger-plugin/components/trigger-form/index.tsx": {"ts/no-explicit-any": {"count": 1@@ -9009,12 +8694,6 @@"react-refresh/only-export-components": {"count": 1},- "tailwindcss/enforce-consistent-class-order": {- "count": 2- },- "tailwindcss/no-unnecessary-whitespace": {- "count": 2- },"ts/no-explicit-any": {"count": 5},@@ -9047,9 +8726,6 @@"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 8},- "tailwindcss/enforce-consistent-class-order": {- "count": 7- },"ts/no-explicit-any": {"count": 3}@@ -9119,9 +8795,6 @@"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 4},- "tailwindcss/enforce-consistent-class-order": {- "count": 11- },"ts/no-explicit-any": {"count": 1}@@ -9284,9 +8957,6 @@},"react-hooks-extra/no-direct-set-state-in-use-effect": {"count": 2- },- "tailwindcss/enforce-consistent-class-order": {- "count": 3}},"app/components/workflow/run/iteration-log/iteration-log-trigger.tsx": {@@ -9476,9 +9146,6 @@"no-restricted-imports": {"count": 2},- "tailwindcss/enforce-consistent-class-order": {- "count": 5- },"ts/no-explicit-any": {"count": 2}@@ -9662,9 +9329,6 @@"app/education-apply/education-apply-page.tsx": {"no-restricted-imports": {"count": 1- },- "tailwindcss/enforce-consistent-class-order": {- "count": 9}},"app/education-apply/expire-notice-modal.tsx": {diff --git a/web/i18n/ar-TN/common.json b/web/i18n/ar-TN/common.jsonindex 2cdbabc1b85..74fe80bcffb 100644--- a/web/i18n/ar-TN/common.json+++ b/web/i18n/ar-TN/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "تمت إزالة هذا النموذج. يرجى إضافة نموذج أو تحديد نموذج آخر.","modelProvider.setupModelFirst": "يرجى إعداد نموذجك أولاً","modelProvider.showModels": "عرض النماذج",- "modelProvider.showModelsNum": "عرض {{num}} نماذج","modelProvider.showMoreModelProvider": "عرض المزيد من مزودي النماذج","modelProvider.speechToTextModel.key": "نموذج تحويل الكلام إلى نص","modelProvider.speechToTextModel.tip": "تعيين النموذج الافتراضي لإدخال تحويل الكلام إلى نص في المحادثة.","modelProvider.systemModelSettings": "إعدادات نموذج النظام",- "modelProvider.systemModelSettingsLink": "لماذا من الضروري إعداد نموذج النظام؟","modelProvider.systemReasoningModel.key": "نموذج التفكير النظامي","modelProvider.systemReasoningModel.tip": "تعيين نموذج الاستنتاج الافتراضي لاستخدامه لإنشاء التطبيقات، بالإضافة إلى ميزات مثل إنشاء اسم الحوار واقتراح السؤال التالي ستستخدم أيضًا نموذج الاستنتاج الافتراضي.","modelProvider.toBeConfigured": "ليتم تكوينه",diff --git a/web/i18n/de-DE/common.json b/web/i18n/de-DE/common.jsonindex 04fc0dbe9f3..a7aaf550862 100644--- a/web/i18n/de-DE/common.json+++ b/web/i18n/de-DE/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Dieses Modell wurde entfernt. Bitte fügen Sie ein Modell hinzu oder wählen Sie ein anderes Modell.","modelProvider.setupModelFirst": "Bitte richten Sie zuerst Ihr Modell ein","modelProvider.showModels": "Modelle anzeigen",- "modelProvider.showModelsNum": "Zeige {{num}} Modelle","modelProvider.showMoreModelProvider": "Zeige mehr Modellanbieter","modelProvider.speechToTextModel.key": "Sprach-zu-Text-Modell","modelProvider.speechToTextModel.tip": "Legen Sie das Standardmodell für die Spracheingabe in Konversationen fest.","modelProvider.systemModelSettings": "Systemmodell-Einstellungen",- "modelProvider.systemModelSettingsLink": "Warum ist es notwendig, ein Systemmodell einzurichten?","modelProvider.systemReasoningModel.key": "System-Reasoning-Modell","modelProvider.systemReasoningModel.tip": "Legen Sie das Standardinferenzmodell fest, das für die Erstellung von Anwendungen verwendet wird, sowie Funktionen wie die Generierung von Dialognamen und die Vorschlagserstellung für die nächste Frage, die auch das Standardinferenzmodell verwenden.","modelProvider.toBeConfigured": "Zu konfigurieren",diff --git a/web/i18n/en-US/app-debug.json b/web/i18n/en-US/app-debug.jsonindex cc538919129..9c64405ecc2 100644--- a/web/i18n/en-US/app-debug.json+++ b/web/i18n/en-US/app-debug.json@@ -235,11 +235,16 @@"inputs.run": "RUN","inputs.title": "Debug & Preview","inputs.userInputField": "User Input Field",+ "manageModels": "Manage models","modelConfig.modeType.chat": "Chat","modelConfig.modeType.completion": "Complete","modelConfig.model": "Model","modelConfig.setTone": "Set tone of responses","modelConfig.title": "Model and Parameters",+ "noModelProviderConfigured": "No model provider configured",+ "noModelProviderConfiguredTip": "Install or configure a model provider to get started.",+ "noModelSelected": "No model selected",+ "noModelSelectedTip": "configure a model above to continue.","noResult": "Output will be displayed here.","notSetAPIKey.description": "The LLM provider key has not been set, and it needs to be set before debugging.","notSetAPIKey.settingBtn": "Go to settings",diff --git a/web/i18n/en-US/common.json b/web/i18n/en-US/common.jsonindex 7ac3abedc85..36301ed72b8 100644--- a/web/i18n/en-US/common.json+++ b/web/i18n/en-US/common.json@@ -340,19 +340,38 @@"modelProvider.auth.unAuthorized": "Unauthorized","modelProvider.buyQuota": "Buy Quota","modelProvider.callTimes": "Call times",+ "modelProvider.card.aiCreditsInUse": "AI credits in use",+ "modelProvider.card.aiCreditsOption": "AI credits",+ "modelProvider.card.apiKeyOption": "API Key",+ "modelProvider.card.apiKeyRequired": "API key required",+ "modelProvider.card.apiKeyUnavailableFallback": "API Key unavailable, now using AI credits",+ "modelProvider.card.apiKeyUnavailableFallbackDescription": "Check your API key configuration to switch back","modelProvider.card.buyQuota": "Buy Quota","modelProvider.card.callTimes": "Call times",+ "modelProvider.card.creditsExhaustedDescription": "Please <upgradeLink>upgrade your plan</upgradeLink> or configure an API key",+ "modelProvider.card.creditsExhaustedFallback": "AI credits exhausted, now using API key",+ "modelProvider.card.creditsExhaustedFallbackDescription": "<upgradeLink>Upgrade your plan</upgradeLink> to resume AI credit priority.",+ "modelProvider.card.creditsExhaustedMessage": "AI credits have been exhausted","modelProvider.card.modelAPI": "{{modelName}} models are using the API Key.",- "modelProvider.card.modelNotSupported": "{{modelName}} models are not installed.",- "modelProvider.card.modelSupported": "{{modelName}} models are using this quota.",+ "modelProvider.card.modelNotSupported": "{{modelName}} not installed",+ "modelProvider.card.modelSupported": "{{modelName}} models are using these credits.",+ "modelProvider.card.noApiKeysDescription": "Add an API key to start using your own model credentials.",+ "modelProvider.card.noApiKeysFallback": "No API keys, using AI credits instead",+ "modelProvider.card.noApiKeysTitle": "No API keys configured yet",+ "modelProvider.card.noAvailableUsage": "No available usage","modelProvider.card.onTrial": "On Trial","modelProvider.card.paid": "Paid","modelProvider.card.priorityUse": "Priority use","modelProvider.card.quota": "QUOTA",- "modelProvider.card.quotaExhausted": "Quota exhausted",+ "modelProvider.card.quotaExhausted": "Credits exhausted","modelProvider.card.removeKey": "Remove API Key",- "modelProvider.card.tip": "Message Credits supports models from {{modelNames}}. Priority will be given to the paid quota. The free quota will be used after the paid quota is exhausted.",+ "modelProvider.card.tip": "AI Credits supports models from {{modelNames}}. Priority will be given to the paid quota. The Trial quota will be used after the paid quota is exhausted.","modelProvider.card.tokens": "Tokens",+ "modelProvider.card.unavailable": "Unavailable",+ "modelProvider.card.upgradePlan": "upgrade your plan",+ "modelProvider.card.usageLabel": "Usage",+ "modelProvider.card.usagePriority": "Usage Priority",+ "modelProvider.card.usagePriorityTip": "Set which resource to use first when running models.","modelProvider.collapse": "Collapse","modelProvider.config": "Config","modelProvider.configLoadBalancing": "Config Load Balancing",@@ -387,34 +406,51 @@"modelProvider.model": "Model","modelProvider.modelAndParameters": "Model and Parameters","modelProvider.modelHasBeenDeprecated": "This model has been deprecated",+ "modelProvider.modelSettings": "Model Settings","modelProvider.models": "Models","modelProvider.modelsNum": "{{num}} Models","modelProvider.noModelFound": "No model found for {{model}}",+ "modelProvider.noneConfigured": "Configure a default system model to run applications","modelProvider.notConfigured": "The system model has not yet been fully configured","modelProvider.parameters": "PARAMETERS","modelProvider.parametersInvalidRemoved": "Some parameters are invalid and have been removed","modelProvider.priorityUsing": "Prioritize using","modelProvider.providerManaged": "Provider managed","modelProvider.providerManagedDescription": "Use the single set of credentials provided by the model provider.",- "modelProvider.quota": "Quota",+ "modelProvider.quota": "AI Credits","modelProvider.quotaTip": "Remaining available free tokens","modelProvider.rerankModel.key": "Rerank Model","modelProvider.rerankModel.tip": "Rerank model will reorder the candidate document list based on the semantic match with user query, improving the results of semantic ranking","modelProvider.resetDate": "Reset on {{date}}","modelProvider.searchModel": "Search model","modelProvider.selectModel": "Select your model",+ "modelProvider.selector.aiCredits": "AI credits",+ "modelProvider.selector.apiKeyUnavailable": "API Key unavailable",+ "modelProvider.selector.apiKeyUnavailableTip": "The API key has been removed. Please configure a new API key.",+ "modelProvider.selector.configure": "Configure",+ "modelProvider.selector.configureRequired": "Configure required",+ "modelProvider.selector.creditsExhausted": "Credits exhausted",+ "modelProvider.selector.creditsExhaustedTip": "Your AI credits have been exhausted. Please upgrade your plan or add an API key.",+ "modelProvider.selector.disabled": "Disabled",+ "modelProvider.selector.discoverMoreInMarketplace": "Discover more in Marketplace","modelProvider.selector.emptySetting": "Please go to settings to configure","modelProvider.selector.emptyTip": "No available models",+ "modelProvider.selector.fromMarketplace": "From Marketplace",+ "modelProvider.selector.incompatible": "Incompatible",+ "modelProvider.selector.incompatibleTip": "This model is not available in the current version. Please select another available model.",+ "modelProvider.selector.install": "Install",+ "modelProvider.selector.modelProviderSettings": "Model Provider Settings",+ "modelProvider.selector.noProviderConfigured": "No model provider configured",+ "modelProvider.selector.noProviderConfiguredDesc": "Browse Marketplace to install one, or configure providers in settings.",+ "modelProvider.selector.onlyCompatibleModelsShown": "Only compatible models are shown","modelProvider.selector.rerankTip": "Please set up the Rerank model","modelProvider.selector.tip": "This model has been removed. Please add a model or select another model.","modelProvider.setupModelFirst": "Please set up your model first","modelProvider.showModels": "Show Models",- "modelProvider.showModelsNum": "Show {{num}} Models","modelProvider.showMoreModelProvider": "Show more model provider","modelProvider.speechToTextModel.key": "Speech-to-Text Model","modelProvider.speechToTextModel.tip": "Set the default model for speech-to-text input in conversation.",- "modelProvider.systemModelSettings": "System Model Settings",- "modelProvider.systemModelSettingsLink": "Why is it necessary to set up a system model?",+ "modelProvider.systemModelSettings": "Default Model Settings","modelProvider.systemReasoningModel.key": "System Reasoning Model","modelProvider.systemReasoningModel.tip": "Set the default inference model to be used for creating applications, as well as features such as dialogue name generation and next question suggestion will also use the default inference model.","modelProvider.toBeConfigured": "To be configured",@@ -430,7 +466,7 @@"operation.change": "Change","operation.clear": "Clear","operation.close": "Close",- "operation.config": "Config",+ "operation.config": "Configure","operation.confirm": "Confirm","operation.confirmAction": "Please confirm your action.","operation.copied": "Copied",diff --git a/web/i18n/en-US/plugin.json b/web/i18n/en-US/plugin.jsonindex c7f091a442f..85f8b3bbbda 100644--- a/web/i18n/en-US/plugin.json+++ b/web/i18n/en-US/plugin.json@@ -3,6 +3,7 @@"action.delete": "Remove plugin","action.deleteContentLeft": "Would you like to remove ","action.deleteContentRight": " plugin?",+ "action.deleteSuccess": "Plugin removed successfully","action.pluginInfo": "Plugin info","action.usedInApps": "This plugin is being used in {{num}} apps.","allCategories": "All Categories",@@ -114,7 +115,8 @@"detailPanel.operation.install": "Install","detailPanel.operation.remove": "Remove","detailPanel.operation.update": "Update",- "detailPanel.operation.viewDetail": "View Detail",+ "detailPanel.operation.updateTooltip": "Update to access the latest models.",+ "detailPanel.operation.viewDetail": "View on Marketplace","detailPanel.serviceOk": "Service OK","detailPanel.strategyNum": "{{num}} {{strategy}} INCLUDED","detailPanel.switchVersion": "Switch Version",@@ -231,12 +233,18 @@"source.local": "Local Package File","source.marketplace": "Marketplace","task.clearAll": "Clear all",+ "task.errorMsg.github": "This plugin couldn't be installed automatically.\nPlease install it from GitHub.",+ "task.errorMsg.marketplace": "This plugin couldn't be installed automatically.\nPlease install it from the Marketplace.",+ "task.errorMsg.unknown": "This plugin couldn't be installed.\nThe plugin source couldn't be identified.","task.errorPlugins": "Failed to Install Plugins","task.installError": "{{errorLength}} plugins failed to install, click to view",+ "task.installFromGithub": "Install from GitHub",+ "task.installFromMarketplace": "Install from Marketplace","task.installSuccess": "{{successLength}} plugins installed successfully","task.installed": "Installed","task.installedError": "{{errorLength}} plugins failed to install","task.installing": "Installing plugins",+ "task.installingHint": "Installing... This may take a few minutes.","task.installingWithError": "Installing {{installingLength}} plugins, {{successLength}} success, {{errorLength}} failed","task.installingWithSuccess": "Installing {{installingLength}} plugins, {{successLength}} success.","task.runningPlugins": "Installing Plugins",diff --git a/web/i18n/en-US/workflow.json b/web/i18n/en-US/workflow.jsonindex 4d9f5adbacb..e5049069d6b 100644--- a/web/i18n/en-US/workflow.json+++ b/web/i18n/en-US/workflow.json@@ -299,6 +299,7 @@"error.operations.updatingWorkflow": "updating workflow","error.startNodeRequired": "Please add a start node first before {{operation}}","errorMsg.authRequired": "Authorization is required",+ "errorMsg.configureModel": "Configure a model","errorMsg.fieldRequired": "{{field}} is required","errorMsg.fields.code": "Code","errorMsg.fields.model": "Model",@@ -307,7 +308,8 @@"errorMsg.fields.variableValue": "Variable Value","errorMsg.fields.visionVariable": "Vision Variable","errorMsg.invalidJson": "{{field}} is invalid JSON",- "errorMsg.invalidVariable": "Invalid variable",+ "errorMsg.invalidVariable": "Invalid variable. Please select an existing variable.",+ "errorMsg.modelPluginNotInstalled": "Invalid variable. Configure a model to enable this variable.","errorMsg.noValidTool": "{{field}} no valid tool selected","errorMsg.rerankModelRequired": "A configured Rerank Model is required","errorMsg.startNodeRequired": "Please add a start node first before {{operation}}",@@ -438,6 +440,7 @@"nodes.common.memory.windowSize": "Window Size","nodes.common.outputVars": "Output Variables","nodes.common.pluginNotInstalled": "Plugin is not installed",+ "nodes.common.pluginsNotInstalled": "{{count}} plugins not installed","nodes.common.retry.maxRetries": "max retries","nodes.common.retry.ms": "ms","nodes.common.retry.retries": "{{num}} Retries",@@ -676,9 +679,14 @@"nodes.knowledgeBase.chunksInput": "Chunks","nodes.knowledgeBase.chunksInputTip": "The input variable of the knowledge base node is Chunks. The variable type is an object with a specific JSON Schema which must be consistent with the selected chunk structure.","nodes.knowledgeBase.chunksVariableIsRequired": "Chunks variable is required",+ "nodes.knowledgeBase.embeddingModelApiKeyUnavailable": "API key unavailable",+ "nodes.knowledgeBase.embeddingModelCreditsExhausted": "Credits exhausted",+ "nodes.knowledgeBase.embeddingModelIncompatible": "Incompatible","nodes.knowledgeBase.embeddingModelIsInvalid": "Embedding model is invalid","nodes.knowledgeBase.embeddingModelIsRequired": "Embedding model is required",+ "nodes.knowledgeBase.embeddingModelNotConfigured": "Embedding model not configured","nodes.knowledgeBase.indexMethodIsRequired": "Index method is required",+ "nodes.knowledgeBase.notConfigured": "Not configured","nodes.knowledgeBase.rerankingModelIsInvalid": "Reranking model is invalid","nodes.knowledgeBase.rerankingModelIsRequired": "Reranking model is required","nodes.knowledgeBase.retrievalSettingIsRequired": "Retrieval setting is required",@@ -861,6 +869,7 @@"nodes.templateTransform.codeSupportTip": "Only supports Jinja2","nodes.templateTransform.inputVars": "Input Variables","nodes.templateTransform.outputVars.output": "Transformed content",+ "nodes.tool.authorizationRequired": "Authorization required","nodes.tool.authorize": "Authorize","nodes.tool.inputVars": "Input Variables","nodes.tool.insertPlaceholder1": "Type or press",@@ -1051,10 +1060,12 @@"panel.change": "Change","panel.changeBlock": "Change Node","panel.checklist": "Checklist",+ "panel.checklistDescription": "Resolve the following issues before publishing","panel.checklistResolved": "All issues are resolved","panel.checklistTip": "Make sure all issues are resolved before publishing","panel.createdBy": "Created By ","panel.goTo": "Go to",+ "panel.goToFix": "Go to fix","panel.helpLink": "View Docs","panel.maximize": "Maximize Canvas","panel.minimize": "Exit Full Screen",diff --git a/web/i18n/es-ES/common.json b/web/i18n/es-ES/common.jsonindex 0fc2fe862cc..595124496b9 100644--- a/web/i18n/es-ES/common.json+++ b/web/i18n/es-ES/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Este modelo ha sido eliminado. Por favor agrega un modelo o selecciona otro modelo.","modelProvider.setupModelFirst": "Por favor configura tu modelo primero","modelProvider.showModels": "Mostrar Modelos",- "modelProvider.showModelsNum": "Mostrar {{num}} Modelos","modelProvider.showMoreModelProvider": "Mostrar más proveedores de modelos","modelProvider.speechToTextModel.key": "Modelo de Voz a Texto","modelProvider.speechToTextModel.tip": "Establece el modelo predeterminado para la entrada de voz a texto en la conversación.","modelProvider.systemModelSettings": "Configuraciones del Modelo del Sistema",- "modelProvider.systemModelSettingsLink": "¿Por qué es necesario configurar un modelo del sistema?","modelProvider.systemReasoningModel.key": "Modelo de Razonamiento del Sistema","modelProvider.systemReasoningModel.tip": "Establece el modelo de inferencia predeterminado para ser usado en la creación de aplicaciones, así como características como la generación de nombres de diálogo y sugerencias de la próxima pregunta también usarán el modelo de inferencia predeterminado.","modelProvider.toBeConfigured": "A configurar",diff --git a/web/i18n/fa-IR/common.json b/web/i18n/fa-IR/common.jsonindex 1628c050ee6..ec535138a4d 100644--- a/web/i18n/fa-IR/common.json+++ b/web/i18n/fa-IR/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "این مدل حذف شده است. لطفاً یک مدل اضافه کنید یا مدل دیگری را انتخاب کنید.","modelProvider.setupModelFirst": "لطفاً ابتدا مدل خود را تنظیم کنید","modelProvider.showModels": "نمایش مدلها",- "modelProvider.showModelsNum": "نمایش {{num}} مدل","modelProvider.showMoreModelProvider": "نمایش ارائهدهندگان مدل بیشتر","modelProvider.speechToTextModel.key": "مدل تبدیل گفتار به متن","modelProvider.speechToTextModel.tip": "مدل پیشفرض را برای ورودی گفتار به متن در مکالمه تنظیم کنید.","modelProvider.systemModelSettings": "تنظیمات مدل سیستم",- "modelProvider.systemModelSettingsLink": "چرا تنظیم مدل سیستم ضروری است؟","modelProvider.systemReasoningModel.key": "مدل استدلال سیستم","modelProvider.systemReasoningModel.tip": "مدل استنتاج پیشفرض را برای ایجاد برنامهها تنظیم کنید. ویژگیهایی مانند تولید نام گفتگو و پیشنهاد سوال بعدی نیز از مدل استنتاج پیشفرض استفاده خواهند کرد.","modelProvider.toBeConfigured": "پیکربندی شود",diff --git a/web/i18n/fr-FR/common.json b/web/i18n/fr-FR/common.jsonindex f9435a23762..42b40b2a2a6 100644--- a/web/i18n/fr-FR/common.json+++ b/web/i18n/fr-FR/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Ce modèle a été supprimé. Veuillez ajouter un modèle ou sélectionner un autre modèle.","modelProvider.setupModelFirst": "Veuillez d'abord configurer votre modèle","modelProvider.showModels": "Montrer les modèles",- "modelProvider.showModelsNum": "Afficher {{num}} Modèles","modelProvider.showMoreModelProvider": "Montrer plus de fournisseur de modèle","modelProvider.speechToTextModel.key": "Modèle de Texte-à-Parole","modelProvider.speechToTextModel.tip": "Définissez le modèle par défaut pour l'entrée de texte par la parole dans la conversation.","modelProvider.systemModelSettings": "Paramètres du Modèle Système",- "modelProvider.systemModelSettingsLink": "Pourquoi est-il nécessaire de mettre en place un modèle de système ?","modelProvider.systemReasoningModel.key": "Modèle de Raisonnement du Système","modelProvider.systemReasoningModel.tip": "Définissez le modèle d'inférence par défaut à utiliser pour la création d'applications, ainsi que des fonctionnalités telles que la génération de noms de dialogue et la suggestion de la prochaine question utiliseront également le modèle d'inférence par défaut.","modelProvider.toBeConfigured": "À configurer",diff --git a/web/i18n/hi-IN/common.json b/web/i18n/hi-IN/common.jsonindex 99d3e7e0b18..75ac76add89 100644--- a/web/i18n/hi-IN/common.json+++ b/web/i18n/hi-IN/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "इस मॉडल को हटा दिया गया है। कृपया एक मॉडल जोड़ें या किसी अन्य मॉडल का चयन करें।","modelProvider.setupModelFirst": "कृपया पहले अपना मॉडल सेट करें","modelProvider.showModels": "मॉडल्स दिखाएं",- "modelProvider.showModelsNum": "{{num}} मॉडल्स दिखाएं","modelProvider.showMoreModelProvider": "अधिक मॉडल प्रदाता दिखाएं","modelProvider.speechToTextModel.key": "भाषण-से-पाठ मॉडल","modelProvider.speechToTextModel.tip": "संवाद में भाषण-से-पाठ इनपुट के लिए डिफ़ॉल्ट मॉडल सेट करें।","modelProvider.systemModelSettings": "सिस्टम मॉडल सेटिंग्स",- "modelProvider.systemModelSettingsLink": "सिस्टम मॉडल सेट करना क्यों आवश्यक है?","modelProvider.systemReasoningModel.key": "सिस्टम तर्क मॉडल","modelProvider.systemReasoningModel.tip": "ऐप्लिकेशन बनाने के लिए उपयोग किए जाने वाले डिफ़ॉल्ट अनुमान मॉडल को सेट करें, साथ ही संवाद नाम पीढ़ी और अगले प्रश्न सुझाव जैसी सुविधाएँ भी डिफ़ॉल्ट अनुमान मॉडल का उपयोग करेंगी।","modelProvider.toBeConfigured": "कॉन्फ़िगर किया जाना है",diff --git a/web/i18n/id-ID/common.json b/web/i18n/id-ID/common.jsonindex 97df8312cc2..90531af7126 100644--- a/web/i18n/id-ID/common.json+++ b/web/i18n/id-ID/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Model ini telah dihapus. Silakan tambahkan model atau pilih model lain.","modelProvider.setupModelFirst": "Silakan atur model Anda terlebih dahulu","modelProvider.showModels": "Tampilkan Model",- "modelProvider.showModelsNum": "Tampilkan {{num}} Model","modelProvider.showMoreModelProvider": "Tampilkan lebih banyak penyedia model","modelProvider.speechToTextModel.key": "Model Ucapan-ke-Teks","modelProvider.speechToTextModel.tip": "Atur model default untuk input ucapan-ke-teks dalam percakapan.","modelProvider.systemModelSettings": "Pengaturan Model Sistem",- "modelProvider.systemModelSettingsLink": "Mengapa perlu menyiapkan model sistem?","modelProvider.systemReasoningModel.key": "Model Penalaran Sistem","modelProvider.systemReasoningModel.tip": "Atur model inferensi default yang akan digunakan untuk membuat aplikasi, serta fitur seperti pembuatan nama dialog dan saran pertanyaan berikutnya juga akan menggunakan model inferensi default.","modelProvider.toBeConfigured": "Untuk dikonfigurasi",diff --git a/web/i18n/it-IT/common.json b/web/i18n/it-IT/common.jsonindex 043aee1d879..d7b57d6d084 100644--- a/web/i18n/it-IT/common.json+++ b/web/i18n/it-IT/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Questo modello è stato rimosso. Per favore aggiungi un modello o seleziona un altro modello.","modelProvider.setupModelFirst": "Per favore, configura prima il tuo modello","modelProvider.showModels": "Mostra Modelli",- "modelProvider.showModelsNum": "Mostra {{num}} Modelli","modelProvider.showMoreModelProvider": "Mostra più fornitori di modelli","modelProvider.speechToTextModel.key": "Modello da Voce a Testo","modelProvider.speechToTextModel.tip": "Imposta il modello predefinito per l'input da voce a testo nella conversazione.","modelProvider.systemModelSettings": "Impostazioni Modello di Sistema",- "modelProvider.systemModelSettingsLink": "Perché è necessario configurare un modello di sistema?","modelProvider.systemReasoningModel.key": "Modello di Ragionamento di Sistema","modelProvider.systemReasoningModel.tip": "Imposta il modello di inferenza predefinito da utilizzare per creare applicazioni, così come funzionalità come la generazione del nome del dialogo e il suggerimento della domanda successiva utilizzeranno anche il modello di inferenza predefinito.","modelProvider.toBeConfigured": "Da configurare",diff --git a/web/i18n/ja-JP/app-debug.json b/web/i18n/ja-JP/app-debug.jsonindex 4b18745e5fe..274db252831 100644--- a/web/i18n/ja-JP/app-debug.json+++ b/web/i18n/ja-JP/app-debug.json@@ -235,11 +235,16 @@"inputs.run": "実行","inputs.title": "デバッグとプレビュー","inputs.userInputField": "ユーザー入力フィールド",+ "manageModels": "モデルを管理","modelConfig.modeType.chat": "チャット","modelConfig.modeType.completion": "完成","modelConfig.model": "モデル","modelConfig.setTone": "応答のトーンを設定する","modelConfig.title": "モデルとパラメータ",+ "noModelProviderConfigured": "モデルプロバイダーが設定されていません",+ "noModelProviderConfiguredTip": "モデルプロバイダーをインストールまたは設定して開始してください。",+ "noModelSelected": "モデルが選択されていません",+ "noModelSelectedTip": "続行するには、上でモデルを設定してください。","noResult": "出力はここに表示されます。","notSetAPIKey.description": "LLM プロバイダーキーが設定されていません。デバッグする前に設定する必要があります。","notSetAPIKey.settingBtn": "設定に移動",diff --git a/web/i18n/ja-JP/common.json b/web/i18n/ja-JP/common.jsonindex cd240caa5a9..98fe556ecf1 100644--- a/web/i18n/ja-JP/common.json+++ b/web/i18n/ja-JP/common.json@@ -340,11 +340,24 @@"modelProvider.auth.unAuthorized": "無許可","modelProvider.buyQuota": "クォータ購入","modelProvider.callTimes": "呼び出し回数",+ "modelProvider.card.aiCreditsInUse": "AI クレジットを使用中",+ "modelProvider.card.aiCreditsOption": "AI クレジット",+ "modelProvider.card.apiKeyOption": "API キー",+ "modelProvider.card.apiKeyRequired": "API キーの設定が必要です",+ "modelProvider.card.apiKeyUnavailableFallback": "API キーが利用できないため、AI クレジットを使用しています",+ "modelProvider.card.apiKeyUnavailableFallbackDescription": "API キーの設定を確認して元に戻してください","modelProvider.card.buyQuota": "クォータを購入","modelProvider.card.callTimes": "通話回数",+ "modelProvider.card.creditsExhaustedDescription": "プランを<upgradeLink>アップグレード</upgradeLink>するか、API キーを設定してください",+ "modelProvider.card.creditsExhaustedFallback": "AI クレジットを使い切ったため、API キーを使用しています",+ "modelProvider.card.creditsExhaustedFallbackDescription": "AI クレジットの優先利用を再開するには、<upgradeLink>プランをアップグレード</upgradeLink>してください。",+ "modelProvider.card.creditsExhaustedMessage": "AI クレジットを使い切りました","modelProvider.card.modelAPI": "{{modelName}} は現在 APIキーを使用しています。","modelProvider.card.modelNotSupported": "{{modelName}} 未インストール。","modelProvider.card.modelSupported": "このクォータは現在{{modelName}}に使用されています。",+ "modelProvider.card.noApiKeysDescription": "独自のモデル認証情報を使用するには、API キーを追加してください。",+ "modelProvider.card.noApiKeysFallback": "API キーが未設定のため、AI クレジットを使用しています",+ "modelProvider.card.noApiKeysTitle": "API キーはまだ設定されていません","modelProvider.card.onTrial": "トライアル中","modelProvider.card.paid": "有料","modelProvider.card.priorityUse": "優先利用",@@ -353,6 +366,8 @@"modelProvider.card.removeKey": "API キーを削除","modelProvider.card.tip": "メッセージ枠は{{modelNames}}のモデルを使用することをサポートしています。無料枠は有料枠が使い果たされた後に消費されます。","modelProvider.card.tokens": "トークン",+ "modelProvider.card.usagePriority": "使用優先順位",+ "modelProvider.card.usagePriorityTip": "モデル実行時に優先して使用するリソースを設定します。","modelProvider.collapse": "折り畳み","modelProvider.config": "設定","modelProvider.configLoadBalancing": "負荷分散の設定",@@ -403,18 +418,26 @@"modelProvider.resetDate": "{{date}} にリセット","modelProvider.searchModel": "検索モデル","modelProvider.selectModel": "モデルを選択",+ "modelProvider.selector.aiCredits": "AI クレジット",+ "modelProvider.selector.apiKeyUnavailable": "API キーが利用できません",+ "modelProvider.selector.apiKeyUnavailableTip": "API キーは削除されました。新しい API キーを設定してください。",+ "modelProvider.selector.configureRequired": "設定が必要です",+ "modelProvider.selector.creditsExhausted": "クレジットを使い切りました",+ "modelProvider.selector.creditsExhaustedTip": "AI クレジットを使い切りました。プランをアップグレードするか、API キーを追加してください。","modelProvider.selector.emptySetting": "設定に移動して構成してください","modelProvider.selector.emptyTip": "利用可能なモデルはありません",+ "modelProvider.selector.fromMarketplace": "マーケットプレイスから",+ "modelProvider.selector.incompatible": "非互換",+ "modelProvider.selector.incompatibleTip": "このモデルは現在のバージョンでは利用できません。別の利用可能なモデルを選択してください。",+ "modelProvider.selector.onlyCompatibleModelsShown": "互換性のあるモデルのみが表示されます","modelProvider.selector.rerankTip": "Rerank モデルを設定してください","modelProvider.selector.tip": "このモデルは削除されました。別のモデルを追加するか、別のモデルを選択してください。","modelProvider.setupModelFirst": "まずモデルをセットアップしてください","modelProvider.showModels": "モデルの表示",- "modelProvider.showModelsNum": "{{num}}のモデルを表示","modelProvider.showMoreModelProvider": "より多くのモデルプロバイダを表示","modelProvider.speechToTextModel.key": "音声-to-テキストモデル","modelProvider.speechToTextModel.tip": "会話での音声-to-テキスト入力に使用するデフォルトモデルを設定します。","modelProvider.systemModelSettings": "システムモデル設定",- "modelProvider.systemModelSettingsLink": "システムモデルの設定が必要な理由は何ですか?","modelProvider.systemReasoningModel.key": "システム推論モデル","modelProvider.systemReasoningModel.tip": "アプリの作成に使用されるデフォルトの推論モデルを設定します。また、対話名の生成や次の質問の提案などの機能もデフォルトの推論モデルを使用します。","modelProvider.toBeConfigured": "設定中",diff --git a/web/i18n/ja-JP/workflow.json b/web/i18n/ja-JP/workflow.jsonindex 6dd914e9bdf..f136363fb84 100644--- a/web/i18n/ja-JP/workflow.json+++ b/web/i18n/ja-JP/workflow.json@@ -861,6 +861,7 @@"nodes.templateTransform.codeSupportTip": "Jinja2 のみをサポートしています","nodes.templateTransform.inputVars": "入力変数","nodes.templateTransform.outputVars.output": "変換されたコンテンツ",+ "nodes.tool.authorizationRequired": "認証が必要です","nodes.tool.authorize": "認証する","nodes.tool.inputVars": "入力変数","nodes.tool.insertPlaceholder1": "タイプするか押してください",diff --git a/web/i18n/ko-KR/common.json b/web/i18n/ko-KR/common.jsonindex 2f94c3d29ee..8fa351c517c 100644--- a/web/i18n/ko-KR/common.json+++ b/web/i18n/ko-KR/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "이 모델은 삭제되었습니다. 다른 모델을 추가하거나 다른 모델을 선택하세요.","modelProvider.setupModelFirst": "먼저 모델을 설정하세요","modelProvider.showModels": "모델 표시",- "modelProvider.showModelsNum": "{{num}}개의 모델 표시","modelProvider.showMoreModelProvider": "더 많은 모델 제공자 표시","modelProvider.speechToTextModel.key": "음성-to-텍스트 모델","modelProvider.speechToTextModel.tip": "대화에서의 음성-to-텍스트 입력에 사용되는 기본 모델을 설정합니다.","modelProvider.systemModelSettings": "시스템 모델 설정",- "modelProvider.systemModelSettingsLink": "시스템 모델 설정이 필요한 이유는 무엇입니까?","modelProvider.systemReasoningModel.key": "시스템 추론 모델","modelProvider.systemReasoningModel.tip": "앱 구축에 사용되는 기본 추론 모델을 설정합니다. 또한 대화 이름 생성 및 다음 질문 제안과 같은 기능도 기본 추론 모델을 사용합니다.","modelProvider.toBeConfigured": "구성 예정",diff --git a/web/i18n/nl-NL/common.json b/web/i18n/nl-NL/common.jsonindex 74c94d07153..013f06b035f 100644--- a/web/i18n/nl-NL/common.json+++ b/web/i18n/nl-NL/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "This model has been removed. Please add a model or select another model.","modelProvider.setupModelFirst": "Please set up your model first","modelProvider.showModels": "Show Models",- "modelProvider.showModelsNum": "Show {{num}} Models","modelProvider.showMoreModelProvider": "Show more model provider","modelProvider.speechToTextModel.key": "Speech-to-Text Model","modelProvider.speechToTextModel.tip": "Set the default model for speech-to-text input in conversation.","modelProvider.systemModelSettings": "System Model Settings",- "modelProvider.systemModelSettingsLink": "Why is it necessary to set up a system model?","modelProvider.systemReasoningModel.key": "System Reasoning Model","modelProvider.systemReasoningModel.tip": "Set the default inference model to be used for creating applications, as well as features such as dialogue name generation and next question suggestion will also use the default inference model.","modelProvider.toBeConfigured": "To be configured",diff --git a/web/i18n/pl-PL/common.json b/web/i18n/pl-PL/common.jsonindex 9883f4527d2..029e9dd660a 100644--- a/web/i18n/pl-PL/common.json+++ b/web/i18n/pl-PL/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Ten model został usunięty. Proszę dodać model lub wybrać inny model.","modelProvider.setupModelFirst": "Proszę najpierw skonfigurować swój model","modelProvider.showModels": "Pokaż modele",- "modelProvider.showModelsNum": "Pokaż {{num}} modele","modelProvider.showMoreModelProvider": "Pokaż więcej dostawców modeli","modelProvider.speechToTextModel.key": "Model mowy na tekst","modelProvider.speechToTextModel.tip": "Ustaw domyślny model do przetwarzania mowy na tekst w rozmowach.","modelProvider.systemModelSettings": "Ustawienia modelu systemowego",- "modelProvider.systemModelSettingsLink": "Dlaczego konieczne jest skonfigurowanie modelu systemowego?","modelProvider.systemReasoningModel.key": "Model wnioskowania systemowego","modelProvider.systemReasoningModel.tip": "Ustaw domyślny model wnioskowania do użytku przy tworzeniu aplikacji, a także cechy takie jak generowanie nazw dialogów i sugestie następnego pytania będą również korzystać z domyślnego modelu wnioskowania.","modelProvider.toBeConfigured": "Do skonfigurowania",diff --git a/web/i18n/pt-BR/common.json b/web/i18n/pt-BR/common.jsonindex 8ea029fa490..0f2106b1eb3 100644--- a/web/i18n/pt-BR/common.json+++ b/web/i18n/pt-BR/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Este modelo foi removido. Adicione um modelo ou selecione outro modelo.","modelProvider.setupModelFirst": "Por favor, configure seu modelo primeiro","modelProvider.showModels": "Mostrar Modelos",- "modelProvider.showModelsNum": "Mostrar {{num}} Modelos","modelProvider.showMoreModelProvider": "Mostrar mais provedor de modelo","modelProvider.speechToTextModel.key": "Modelo de Fala para Texto","modelProvider.speechToTextModel.tip": "Defina o modelo padrão para entrada de fala para texto na conversa.","modelProvider.systemModelSettings": "Configurações do Modelo do Sistema",- "modelProvider.systemModelSettingsLink": "Por que é necessário configurar um modelo do sistema?","modelProvider.systemReasoningModel.key": "Modelo de Raciocínio do Sistema","modelProvider.systemReasoningModel.tip": "Defina o modelo de inferência padrão a ser usado para criar aplicativos, bem como recursos como geração de nomes de diálogo e sugestão de próxima pergunta também usarão o modelo de inferência padrão.","modelProvider.toBeConfigured": "A ser configurado",diff --git a/web/i18n/ro-RO/common.json b/web/i18n/ro-RO/common.jsonindex 398bb784b3a..8fdb09b3c13 100644--- a/web/i18n/ro-RO/common.json+++ b/web/i18n/ro-RO/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Acest model a fost eliminat. Vă rugăm să adăugați un model sau să selectați un alt model.","modelProvider.setupModelFirst": "Vă rugăm să configurați mai întâi modelul","modelProvider.showModels": "Arată modele",- "modelProvider.showModelsNum": "Arată {{num}} modele","modelProvider.showMoreModelProvider": "Arată mai multe furnizori de modele","modelProvider.speechToTextModel.key": "Model de conversie text-la-vorbire","modelProvider.speechToTextModel.tip": "Setați modelul implicit pentru intrarea de conversie text-la-vorbire în conversație.","modelProvider.systemModelSettings": "Setări model de sistem",- "modelProvider.systemModelSettingsLink": "De ce este necesar să se configureze un model de sistem?","modelProvider.systemReasoningModel.key": "Model de raționament de sistem","modelProvider.systemReasoningModel.tip": "Setați modelul de inferență implicit care va fi utilizat pentru crearea aplicațiilor, precum și caracteristici precum generarea de nume pentru dialog și sugestia următoarei întrebări vor utiliza, de asemenea, modelul de inferență implicit.","modelProvider.toBeConfigured": "De configurat",diff --git a/web/i18n/ru-RU/common.json b/web/i18n/ru-RU/common.jsonindex a5a5036c9c6..dc301e4ed9a 100644--- a/web/i18n/ru-RU/common.json+++ b/web/i18n/ru-RU/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Эта модель была удалена. Пожалуйста, добавьте модель или выберите другую модель.","modelProvider.setupModelFirst": "Пожалуйста, сначала настройте свою модель","modelProvider.showModels": "Показать модели",- "modelProvider.showModelsNum": "Показать {{num}} моделей","modelProvider.showMoreModelProvider": "Показать больше поставщиков моделей","modelProvider.speechToTextModel.key": "Модель преобразования речи в текст","modelProvider.speechToTextModel.tip": "Установите модель по умолчанию для ввода речи в текст в разговоре.","modelProvider.systemModelSettings": "Настройки системной модели",- "modelProvider.systemModelSettingsLink": "Зачем нужно настраивать системную модель?","modelProvider.systemReasoningModel.key": "Модель системного мышления","modelProvider.systemReasoningModel.tip": "Установите модель вывода по умолчанию, которая будет использоваться для создания приложений, а также такие функции, как генерация имени диалога и предложение следующего вопроса, также будут использовать модель вывода по умолчанию.","modelProvider.toBeConfigured": "Подлежит настройке",diff --git a/web/i18n/sl-SI/common.json b/web/i18n/sl-SI/common.jsonindex 8a793c6be2c..247874bb30c 100644--- a/web/i18n/sl-SI/common.json+++ b/web/i18n/sl-SI/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Ta model je bil odstranjen. Prosimo, dodajte model ali izberite drugega.","modelProvider.setupModelFirst": "Najprej nastavite svoj model","modelProvider.showModels": "Prikaži modele",- "modelProvider.showModelsNum": "Prikaži {{num}} modelov","modelProvider.showMoreModelProvider": "Prikaži več ponudnikov modelov","modelProvider.speechToTextModel.key": "Model za pretvorbo govora v besedilo","modelProvider.speechToTextModel.tip": "Nastavite privzeti model za vnos govora v besedilo v pogovoru.","modelProvider.systemModelSettings": "Nastavitve sistemskega modela",- "modelProvider.systemModelSettingsLink": "Zakaj je potrebno nastaviti sistemski model?","modelProvider.systemReasoningModel.key": "Sistemski model za sklepanja","modelProvider.systemReasoningModel.tip": "Nastavite privzeti model za sklepanja, ki se bo uporabljal za ustvarjanje aplikacij, kot tudi funkcije, kot so generiranje imen dialogov in predlaganje naslednjih vprašanj.","modelProvider.toBeConfigured": "Za konfiguracijo",diff --git a/web/i18n/th-TH/common.json b/web/i18n/th-TH/common.jsonindex d5b4b4cc194..71c9369599f 100644--- a/web/i18n/th-TH/common.json+++ b/web/i18n/th-TH/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "รุ่นนี้ถูกลบออกแล้ว โปรดเพิ่มรุ่นหรือเลือกรุ่นอื่น","modelProvider.setupModelFirst": "โปรดตั้งค่าโมเดลของคุณก่อน","modelProvider.showModels": "แสดงโมเดล",- "modelProvider.showModelsNum": "แสดง {{num}} โมเดล","modelProvider.showMoreModelProvider": "แสดงผู้ให้บริการรุ่นเพิ่มเติม","modelProvider.speechToTextModel.key": "โมเดลคําพูดเป็นข้อความ","modelProvider.speechToTextModel.tip": "ตั้งค่าโมเดลเริ่มต้นสําหรับการป้อนข้อมูลคําพูดเป็นข้อความในการสนทนา","modelProvider.systemModelSettings": "การตั้งค่ารุ่นระบบ",- "modelProvider.systemModelSettingsLink": "เหตุใดจึงจําเป็นต้องตั้งค่าโมเดลระบบ","modelProvider.systemReasoningModel.key": "แบบจําลองการให้เหตุผลของระบบ","modelProvider.systemReasoningModel.tip": "ตั้งค่าโมเดลการอนุมานเริ่มต้นที่จะใช้สําหรับการสร้างแอปพลิเคชัน ตลอดจนคุณลักษณะต่างๆ เช่น การสร้างชื่อบทสนทนาและคําแนะนําคําถามถัดไปจะใช้โมเดลการอนุมานเริ่มต้นด้วย","modelProvider.toBeConfigured": "ต้องกําหนดค่า",diff --git a/web/i18n/tr-TR/common.json b/web/i18n/tr-TR/common.jsonindex 787c14d23fa..9aeb24cd1e3 100644--- a/web/i18n/tr-TR/common.json+++ b/web/i18n/tr-TR/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Bu model kaldırıldı. Lütfen bir model ekleyin veya başka bir model seçin.","modelProvider.setupModelFirst": "Lütfen önce modelinizi ayarlayın","modelProvider.showModels": "Modelleri Göster",- "modelProvider.showModelsNum": "{{num}} Modeli Göster","modelProvider.showMoreModelProvider": "Daha fazla model sağlayıcı göster","modelProvider.speechToTextModel.key": "Konuşmadan Metne Modeli","modelProvider.speechToTextModel.tip": "Konuşmada konuşmadan metne giriş için varsayılan modeli ayarlayın.","modelProvider.systemModelSettings": "Sistem Model Ayarları",- "modelProvider.systemModelSettingsLink": "Sistem modelini ayarlamak neden gereklidir?","modelProvider.systemReasoningModel.key": "Sistem Çıkarım Modeli","modelProvider.systemReasoningModel.tip": "Uygulamalar oluşturmak ve diyalog adı oluşturma ve sonraki soru önerisi gibi özelliklerin otomatikleştirilmesi için kullanılacak varsayılan çıkarım modelini ayarlayın.","modelProvider.toBeConfigured": "Yapılandırılacak",diff --git a/web/i18n/uk-UA/common.json b/web/i18n/uk-UA/common.jsonindex dcd5140dd10..6745644573c 100644--- a/web/i18n/uk-UA/common.json+++ b/web/i18n/uk-UA/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Цю модель було видалено. Будь ласка, додайте модель або виберіть іншу.","modelProvider.setupModelFirst": "Будь ласка, спочатку налаштуйте свою модель","modelProvider.showModels": "Показати моделі",- "modelProvider.showModelsNum": "Показати {{num}} моделей","modelProvider.showMoreModelProvider": "Показати більше постачальників моделей","modelProvider.speechToTextModel.key": "Модель перетворення мовлення в текст","modelProvider.speechToTextModel.tip": "Встановіть модель за замовчуванням для введення мовлення в текст під час розмови.","modelProvider.systemModelSettings": "Налаштування системної моделі",- "modelProvider.systemModelSettingsLink": "Чому необхідно налаштовувати системну модель?","modelProvider.systemReasoningModel.key": "Системна модель міркування","modelProvider.systemReasoningModel.tip": "Встановіть модель висновку за замовчуванням, яка буде використовуватися для створення програм, а також для таких функцій, як генерація імені діалогу та пропозиція наступного питання також використовуватимуть модель висновку за замовчуванням.","modelProvider.toBeConfigured": "Підлягає налаштуванню",diff --git a/web/i18n/vi-VN/common.json b/web/i18n/vi-VN/common.jsonindex 75a00b89653..a47ee6da573 100644--- a/web/i18n/vi-VN/common.json+++ b/web/i18n/vi-VN/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "Mô hình này đã bị xóa. Vui lòng thêm một mô hình hoặc chọn mô hình khác.","modelProvider.setupModelFirst": "Vui lòng thiết lập mô hình của bạn trước","modelProvider.showModels": "Hiện Mô hình",- "modelProvider.showModelsNum": "Hiện {{num}} Mô hình","modelProvider.showMoreModelProvider": "Hiển thị thêm nhà cung cấp mô hình","modelProvider.speechToTextModel.key": "Mô hình Chuyển đổi Văn bản thành Tiếng nói","modelProvider.speechToTextModel.tip": "Thiết lập mô hình mặc định cho đầu vào chuyển đổi tiếng nói thành văn bản trong cuộc trò chuyện.","modelProvider.systemModelSettings": "Cài đặt Mô hình Hệ thống",- "modelProvider.systemModelSettingsLink": "Tại sao cần thiết phải thiết lập mô hình hệ thống?","modelProvider.systemReasoningModel.key": "Mô hình lập luận hệ thống","modelProvider.systemReasoningModel.tip": "Thiết lập mô hình suy luận mặc định sẽ được sử dụng để tạo ứng dụng. Các tính năng như tạo tên cuộc trò chuyện và đề xuất câu hỏi tiếp theo cũng sẽ sử dụng mô hình suy luận mặc định này.","modelProvider.toBeConfigured": "Được cấu hình",diff --git a/web/i18n/zh-Hans/app-debug.json b/web/i18n/zh-Hans/app-debug.jsonindex 7559bf2b568..fb4f2318529 100644--- a/web/i18n/zh-Hans/app-debug.json+++ b/web/i18n/zh-Hans/app-debug.json@@ -235,11 +235,16 @@"inputs.run": "运行","inputs.title": "调试与预览","inputs.userInputField": "用户输入",+ "manageModels": "管理模型","modelConfig.modeType.chat": "对话型","modelConfig.modeType.completion": "补全型","modelConfig.model": "语言模型","modelConfig.setTone": "模型设置","modelConfig.title": "模型及参数",+ "noModelProviderConfigured": "未配置模型供应商",+ "noModelProviderConfiguredTip": "请先安装或配置模型供应商以开始使用。",+ "noModelSelected": "未选择模型",+ "noModelSelectedTip": "请先在上方配置模型以继续。","noResult": "输出结果展示在这","notSetAPIKey.description": "在调试之前需要设置 LLM 提供者的密钥。","notSetAPIKey.settingBtn": "去设置",diff --git a/web/i18n/zh-Hans/common.json b/web/i18n/zh-Hans/common.jsonindex 035ebbd3189..9676b8efb24 100644--- a/web/i18n/zh-Hans/common.json+++ b/web/i18n/zh-Hans/common.json@@ -340,19 +340,38 @@"modelProvider.auth.unAuthorized": "未授权","modelProvider.buyQuota": "购买额度","modelProvider.callTimes": "调用次数",+ "modelProvider.card.aiCreditsInUse": "AI 额度使用中",+ "modelProvider.card.aiCreditsOption": "AI 额度",+ "modelProvider.card.apiKeyOption": "API Key",+ "modelProvider.card.apiKeyRequired": "需要配置 API Key",+ "modelProvider.card.apiKeyUnavailableFallback": "API Key 不可用,正在使用 AI 额度",+ "modelProvider.card.apiKeyUnavailableFallbackDescription": "检查你的 API Key 配置以切换回来","modelProvider.card.buyQuota": "购买额度","modelProvider.card.callTimes": "调用次数",+ "modelProvider.card.creditsExhaustedDescription": "请<upgradeLink>升级套餐</upgradeLink>或配置 API Key",+ "modelProvider.card.creditsExhaustedFallback": "AI 额度已用尽,正在使用 API Key",+ "modelProvider.card.creditsExhaustedFallbackDescription": "<upgradeLink>升级套餐</upgradeLink>以恢复 AI 额度优先使用。",+ "modelProvider.card.creditsExhaustedMessage": "AI 额度已用尽","modelProvider.card.modelAPI": "{{modelName}} 模型正在使用 API Key。",- "modelProvider.card.modelNotSupported": "{{modelName}} 模型未安装。",+ "modelProvider.card.modelNotSupported": "{{modelName}} 未安装","modelProvider.card.modelSupported": "{{modelName}} 模型正在使用此额度。",+ "modelProvider.card.noApiKeysDescription": "添加 API Key 以使用自有模型凭证。",+ "modelProvider.card.noApiKeysFallback": "未配置 API Key,正在使用 AI 额度",+ "modelProvider.card.noApiKeysTitle": "尚未配置 API Key",+ "modelProvider.card.noAvailableUsage": "无可用额度","modelProvider.card.onTrial": "试用中","modelProvider.card.paid": "已购买","modelProvider.card.priorityUse": "优先使用","modelProvider.card.quota": "额度",- "modelProvider.card.quotaExhausted": "配额已用完",+ "modelProvider.card.quotaExhausted": "额度已用尽","modelProvider.card.removeKey": "删除 API 密钥",- "modelProvider.card.tip": "消息额度支持使用 {{modelNames}} 的模型;免费额度会在付费额度用尽后才会消耗。",+ "modelProvider.card.tip": "AI Credits 支持使用 {{modelNames}} 的模型;试用额度会在付费额度用尽后才会消耗。","modelProvider.card.tokens": "Tokens",+ "modelProvider.card.unavailable": "不可用",+ "modelProvider.card.upgradePlan": "升级套餐",+ "modelProvider.card.usageLabel": "用量",+ "modelProvider.card.usagePriority": "使用优先级",+ "modelProvider.card.usagePriorityTip": "设置运行模型时优先使用的资源。","modelProvider.collapse": "收起","modelProvider.config": "配置","modelProvider.configLoadBalancing": "设置负载均衡",@@ -387,34 +406,51 @@"modelProvider.model": "模型","modelProvider.modelAndParameters": "模型及参数","modelProvider.modelHasBeenDeprecated": "该模型已废弃",+ "modelProvider.modelSettings": "模型设置","modelProvider.models": "模型列表","modelProvider.modelsNum": "{{num}} 个模型","modelProvider.noModelFound": "找不到模型 {{model}}",+ "modelProvider.noneConfigured": "配置默认系统模型以运行应用","modelProvider.notConfigured": "系统模型尚未完全配置","modelProvider.parameters": "参数","modelProvider.parametersInvalidRemoved": "部分参数无效,已移除","modelProvider.priorityUsing": "优先使用","modelProvider.providerManaged": "由模型供应商管理","modelProvider.providerManagedDescription": "使用模型供应商提供的单组凭据",- "modelProvider.quota": "额度",+ "modelProvider.quota": "AI Credits","modelProvider.quotaTip": "剩余免费额度","modelProvider.rerankModel.key": "Rerank 模型","modelProvider.rerankModel.tip": "重排序模型将根据候选文档列表与用户问题语义匹配度进行重新排序,从而改进语义排序的结果","modelProvider.resetDate": "于 {{date}} 重置","modelProvider.searchModel": "搜索模型","modelProvider.selectModel": "选择您的模型",+ "modelProvider.selector.aiCredits": "AI 积分",+ "modelProvider.selector.apiKeyUnavailable": "API Key 不可用",+ "modelProvider.selector.apiKeyUnavailableTip": "API Key 已被移除,请重新配置 API Key。",+ "modelProvider.selector.configure": "配置",+ "modelProvider.selector.configureRequired": "需要配置",+ "modelProvider.selector.creditsExhausted": "额度已用尽",+ "modelProvider.selector.creditsExhaustedTip": "AI 积分已用尽,请升级计划或添加 API Key。",+ "modelProvider.selector.disabled": "已禁用",+ "modelProvider.selector.discoverMoreInMarketplace": "在插件市场发现更多","modelProvider.selector.emptySetting": "请前往设置进行配置","modelProvider.selector.emptyTip": "无可用模型",+ "modelProvider.selector.fromMarketplace": "从插件市场安装",+ "modelProvider.selector.incompatible": "不兼容",+ "modelProvider.selector.incompatibleTip": "该模型在当前版本中不可用,请选择其他可用模型。",+ "modelProvider.selector.install": "安装",+ "modelProvider.selector.modelProviderSettings": "模型供应商设置",+ "modelProvider.selector.noProviderConfigured": "未配置模型提供商",+ "modelProvider.selector.noProviderConfiguredDesc": "前往插件市场安装,或在设置中配置提供商。",+ "modelProvider.selector.onlyCompatibleModelsShown": "仅显示兼容的模型","modelProvider.selector.rerankTip": "请设置 Rerank 模型","modelProvider.selector.tip": "该模型已被删除。请添模型或选择其他模型。","modelProvider.setupModelFirst": "请先设置您的模型","modelProvider.showModels": "显示模型",- "modelProvider.showModelsNum": "显示 {{num}} 个模型","modelProvider.showMoreModelProvider": "显示更多模型提供商","modelProvider.speechToTextModel.key": "语音转文本模型","modelProvider.speechToTextModel.tip": "设置对话中语音转文字输入的默认使用模型。",- "modelProvider.systemModelSettings": "系统模型设置",- "modelProvider.systemModelSettingsLink": "为什么需要设置系统模型?",+ "modelProvider.systemModelSettings": "默认模型设置","modelProvider.systemReasoningModel.key": "系统推理模型","modelProvider.systemReasoningModel.tip": "设置创建应用使用的默认推理模型,以及对话名称生成、下一步问题建议等功能也会使用该默认推理模型。","modelProvider.toBeConfigured": "待配置",diff --git a/web/i18n/zh-Hans/plugin.json b/web/i18n/zh-Hans/plugin.jsonindex 703bd4e6ea9..5d640b57233 100644--- a/web/i18n/zh-Hans/plugin.json+++ b/web/i18n/zh-Hans/plugin.json@@ -3,6 +3,7 @@"action.delete": "移除插件","action.deleteContentLeft": "是否要移除 ","action.deleteContentRight": " 插件?",+ "action.deleteSuccess": "插件移除成功","action.pluginInfo": "插件信息","action.usedInApps": "此插件正在 {{num}} 个应用中使用。","allCategories": "所有类别",@@ -114,7 +115,8 @@"detailPanel.operation.install": "安装","detailPanel.operation.remove": "移除","detailPanel.operation.update": "更新",- "detailPanel.operation.viewDetail": "查看详情",+ "detailPanel.operation.updateTooltip": "更新以获取最新模型。",+ "detailPanel.operation.viewDetail": "在 Marketplace 查看","detailPanel.serviceOk": "服务正常","detailPanel.strategyNum": "包含 {{num}} 个 {{strategy}}","detailPanel.switchVersion": "切换版本",@@ -231,12 +233,18 @@"source.local": "本地插件","source.marketplace": "Marketplace","task.clearAll": "清除所有",+ "task.errorMsg.github": "此插件无法自动安装。\n请从 GitHub 安装。",+ "task.errorMsg.marketplace": "此插件无法自动安装。\n请从插件市场安装。",+ "task.errorMsg.unknown": "此插件无法安装。\n无法识别插件来源。","task.errorPlugins": "安装失败的插件","task.installError": "{{errorLength}} 个插件安装失败,点击查看",+ "task.installFromGithub": "从 GitHub 安装",+ "task.installFromMarketplace": "从插件市场安装","task.installSuccess": "{{successLength}} 个插件安装成功","task.installed": "已安装","task.installedError": "{{errorLength}} 个插件安装失败","task.installing": "正在安装插件",+ "task.installingHint": "正在安装……可能需要几分钟。","task.installingWithError": "{{installingLength}} 个插件安装中,{{successLength}} 安装成功,{{errorLength}} 安装失败","task.installingWithSuccess": "{{installingLength}} 个插件安装中,{{successLength}} 安装成功","task.runningPlugins": "正在安装的插件",diff --git a/web/i18n/zh-Hans/workflow.json b/web/i18n/zh-Hans/workflow.jsonindex acda7db2fce..37ffa13b42f 100644--- a/web/i18n/zh-Hans/workflow.json+++ b/web/i18n/zh-Hans/workflow.json@@ -299,6 +299,7 @@"error.operations.updatingWorkflow": "更新工作流","error.startNodeRequired": "请先添加开始节点,然后再{{operation}}","errorMsg.authRequired": "请先授权",+ "errorMsg.configureModel": "请配置模型","errorMsg.fieldRequired": "{{field}} 不能为空","errorMsg.fields.code": "代码","errorMsg.fields.model": "模型",@@ -307,7 +308,8 @@"errorMsg.fields.variableValue": "变量值","errorMsg.fields.visionVariable": "视觉变量","errorMsg.invalidJson": "{{field}} 是非法的 JSON",- "errorMsg.invalidVariable": "无效的变量",+ "errorMsg.invalidVariable": "无效的变量。请选择一个已有的变量。",+ "errorMsg.modelPluginNotInstalled": "无效的变量。请配置模型以启用此变量。","errorMsg.noValidTool": "{{field}} 无可用工具","errorMsg.rerankModelRequired": "未配置 Rerank 模型","errorMsg.startNodeRequired": "请先添加开始节点,然后再{{operation}}",@@ -438,6 +440,7 @@"nodes.common.memory.windowSize": "记忆窗口","nodes.common.outputVars": "输出变量","nodes.common.pluginNotInstalled": "插件未安装",+ "nodes.common.pluginsNotInstalled": "{{count}} 个插件未安装","nodes.common.retry.maxRetries": "最大重试次数","nodes.common.retry.ms": "毫秒","nodes.common.retry.retries": "{{num}} 重试次数",@@ -676,9 +679,14 @@"nodes.knowledgeBase.chunksInput": "分块","nodes.knowledgeBase.chunksInputTip": "知识库节点的输入变量为 Chunks。该变量类型是符合特定 JSON Schema 的对象,必须与所选块结构一致。","nodes.knowledgeBase.chunksVariableIsRequired": "Chunks 变量是必需的",+ "nodes.knowledgeBase.embeddingModelApiKeyUnavailable": "API Key 不可用",+ "nodes.knowledgeBase.embeddingModelCreditsExhausted": "额度已用尽",+ "nodes.knowledgeBase.embeddingModelIncompatible": "不兼容","nodes.knowledgeBase.embeddingModelIsInvalid": "无效的 Embedding 模型","nodes.knowledgeBase.embeddingModelIsRequired": "Embedding 模型是必需的",+ "nodes.knowledgeBase.embeddingModelNotConfigured": "Embedding 模型未配置","nodes.knowledgeBase.indexMethodIsRequired": "索引方法是必需的",+ "nodes.knowledgeBase.notConfigured": "未配置","nodes.knowledgeBase.rerankingModelIsInvalid": "无效的 Reranking 模型","nodes.knowledgeBase.rerankingModelIsRequired": "Reranking 模型是必需的","nodes.knowledgeBase.retrievalSettingIsRequired": "检索设置是必需的",@@ -861,6 +869,7 @@"nodes.templateTransform.codeSupportTip": "只支持 Jinja2","nodes.templateTransform.inputVars": "输入变量","nodes.templateTransform.outputVars.output": "转换后内容",+ "nodes.tool.authorizationRequired": "需要授权","nodes.tool.authorize": "授权","nodes.tool.inputVars": "输入变量","nodes.tool.insertPlaceholder1": "键入",@@ -1051,10 +1060,12 @@"panel.change": "更改","panel.changeBlock": "更改节点","panel.checklist": "检查清单",+ "panel.checklistDescription": "发布前请解决以下问题","panel.checklistResolved": "所有问题均已解决","panel.checklistTip": "发布前确保所有问题均已解决","panel.createdBy": "作者","panel.goTo": "转到",+ "panel.goToFix": "前往修复","panel.helpLink": "查看帮助文档","panel.maximize": "最大化画布","panel.minimize": "退出最大化",diff --git a/web/i18n/zh-Hant/common.json b/web/i18n/zh-Hant/common.jsonindex d944b1c70f9..85ff9cc6872 100644--- a/web/i18n/zh-Hant/common.json+++ b/web/i18n/zh-Hant/common.json@@ -409,12 +409,10 @@"modelProvider.selector.tip": "該模型已被刪除。請添模型或選擇其他模型。","modelProvider.setupModelFirst": "請先設定您的模型","modelProvider.showModels": "顯示模型",- "modelProvider.showModelsNum": "顯示 {{num}} 個模型","modelProvider.showMoreModelProvider": "顯示更多模型提供商","modelProvider.speechToTextModel.key": "語音轉文字模型","modelProvider.speechToTextModel.tip": "設定對話中語音轉文字輸入的預設使用模型。","modelProvider.systemModelSettings": "系統模型設定",- "modelProvider.systemModelSettingsLink": "為什麼需要設定系統模型?","modelProvider.systemReasoningModel.key": "系統推理模型","modelProvider.systemReasoningModel.tip": "設定建立應用使用的預設推理模型,以及對話名稱生成、下一步問題建議等功能也會使用該預設推理模型。","modelProvider.toBeConfigured": "待配置",diff --git a/web/service/use-common.ts b/web/service/use-common.tsindex 002d154d1de..fbd83845ba8 100644--- a/web/service/use-common.ts+++ b/web/service/use-common.ts@@ -371,7 +371,7 @@ export const useNotionBinding = (code?: string | null, enabled?: boolean) => {export const useModelParameterRules = (provider?: string, model?: string, enabled?: boolean) => {return useQuery<{ data: ModelParameterRule[] }>({queryKey: commonQueryKeys.modelParameterRules(provider, model),- queryFn: () => get<{ data: ModelParameterRule[] }>(`/workspaces/current/model-providers/${provider}/models/parameter-rules`, { params: { model } }),+ queryFn: () => get<{ data: ModelParameterRule[] }>(`/workspaces/current/model-providers/${provider}/models/parameter-rules`, { params: { model }, silent: true }),enabled: !!provider && !!model && (enabled ?? true),})}diff --git a/web/service/use-plugins.ts b/web/service/use-plugins.tsindex ea32cf8ab70..17e8eb59031 100644--- a/web/service/use-plugins.ts+++ b/web/service/use-plugins.ts@@ -10,14 +10,12 @@ import type {DebugInfo as DebugInfoTypes,Dependency,GitHubItemAndMarketPlaceDependency,- InstalledLatestVersionResponse,InstalledPluginListWithTotalResponse,InstallPackageResponse,InstallStatusResponse,PackageDependency,Plugin,PluginDeclaration,- PluginDetail,PluginInfoFromMarketPlace,PluginsFromMarketplaceByInfoResponse,PluginsFromMarketplaceResponse,@@ -42,11 +40,12 @@ import { PluginCategoryEnum, TaskStatus } from '@/app/components/plugins/types'import { fetchModelProviderModelList } from '@/service/common'import { fetchPluginInfoFromMarketPlace, uninstallPlugin } from '@/service/plugins'import { get, getMarketplace, post, postMarketplace } from './base'+import { consoleQuery } from './client'import { useInvalidateAllBuiltInTools } from './use-tools'const NAME_SPACE = 'plugins'-const useInstalledPluginListKey = [NAME_SPACE, 'installedPluginList']+export const useCheckInstalled = ({pluginIds,enabled,@@ -54,16 +53,20 @@ export const useCheckInstalled = ({pluginIds: string[]enabled: boolean}) => {- return useQuery<{ plugins: PluginDetail[] }>({- queryKey: [NAME_SPACE, 'checkInstalled', pluginIds],- queryFn: () => post<{ plugins: PluginDetail[] }>('/workspaces/current/plugin/list/installations/ids', {- body: {- plugin_ids: pluginIds,- },- }),+ return useQuery(consoleQuery.plugins.checkInstalled.queryOptions({+ input: { body: { plugin_ids: pluginIds } },enabled,- staleTime: 0, // always fresh- })+ staleTime: 0,+ }))+}++export const useInvalidateCheckInstalled = () => {+ const queryClient = useQueryClient()+ return () => {+ queryClient.invalidateQueries({+ queryKey: consoleQuery.plugins.checkInstalled.key(),+ })+ }}const useRecommendedMarketplacePluginsKey = [NAME_SPACE, 'recommendedMarketplacePlugins']@@ -180,19 +183,6 @@ export const useInstalledPluginList = (disable?: boolean, pageSize = 100) => {}}-export const useInstalledLatestVersion = (pluginIds: string[]) => {- return useQuery<InstalledLatestVersionResponse>({- queryKey: [NAME_SPACE, 'installedLatestVersion', pluginIds],- queryFn: () => post<InstalledLatestVersionResponse>('/workspaces/current/plugin/list/latest-versions', {- body: {- plugin_ids: pluginIds,- },- }),- enabled: !!pluginIds.length,- initialData: pluginIds.length ? undefined : { versions: {} },- })-}-export const useInvalidateInstalledPluginList = () => {const queryClient = useQueryClient()const invalidateAllBuiltInTools = useInvalidateAllBuiltInTools()@@ -685,7 +675,7 @@ export const useModelInList = (currentProvider?: ModelProvider, modelId?: stringreturn falsetry {const modelsData = await fetchModelProviderModelList(`/workspaces/current/model-providers/${provider}/models`)- return !!modelId && !!modelsData.data.find(item => item.model === modelId)+ return !!modelId && modelsData.data.some(item => item.model === modelId)}catch {return falsediff --git a/web/service/use-tools.ts b/web/service/use-tools.tsindex 58cc8ef1d92..2feedacf691 100644--- a/web/service/use-tools.ts+++ b/web/service/use-tools.ts@@ -32,10 +32,11 @@ export const useInvalidateAllToolProviders = () => {}const useAllBuiltInToolsKey = [NAME_SPACE, 'builtIn']-export const useAllBuiltInTools = () => {+export const useAllBuiltInTools = (enabled = true) => {return useQuery<ToolWithProvider[]>({queryKey: useAllBuiltInToolsKey,queryFn: () => get<ToolWithProvider[]>('/workspaces/current/tools/builtin'),+ enabled,})}@@ -44,10 +45,11 @@ export const useInvalidateAllBuiltInTools = () => {}const useAllCustomToolsKey = [NAME_SPACE, 'customTools']-export const useAllCustomTools = () => {+export const useAllCustomTools = (enabled = true) => {return useQuery<ToolWithProvider[]>({queryKey: useAllCustomToolsKey,queryFn: () => get<ToolWithProvider[]>('/workspaces/current/tools/api'),+ enabled,})}@@ -56,10 +58,11 @@ export const useInvalidateAllCustomTools = () => {}const useAllWorkflowToolsKey = [NAME_SPACE, 'workflowTools']-export const useAllWorkflowTools = () => {+export const useAllWorkflowTools = (enabled = true) => {return useQuery<ToolWithProvider[]>({queryKey: useAllWorkflowToolsKey,queryFn: () => get<ToolWithProvider[]>('/workspaces/current/tools/workflow'),+ enabled,})}@@ -68,10 +71,11 @@ export const useInvalidateAllWorkflowTools = () => {}const useAllMCPToolsKey = [NAME_SPACE, 'MCPTools']-export const useAllMCPTools = () => {+export const useAllMCPTools = (enabled = true) => {return useQuery<ToolWithProvider[]>({queryKey: useAllMCPToolsKey,queryFn: () => get<ToolWithProvider[]>('/workspaces/current/tools/mcp'),+ enabled,})}