chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动

演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
wuzilongandCursor committed 2026-11-18 13:59:25 +08:00
1 parent 60158935f4
commit 6519682885
15831 files changed
+3063428

No files matched your search

@@ -0,0 +1,16 @@
export type CreateExternalAPIReq = {
name: string
settings: {
endpoint: string
api_key: string
}
}
export type FormSchema = {
variable: string
type: 'text' | 'secret'
label: {
[key: string]: string
}
required: boolean
}
@@ -0,0 +1,116 @@
import type { FC, SubmitEventHandler } from 'react'
import type { CreateExternalAPIReq, FormSchema } from '../declarations'
import { cn } from '@langgenius/dify-ui/cn'
import { Field, FieldError } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
import { Input } from '@langgenius/dify-ui/input'
import { RiBookOpenLine } from '@remixicon/react'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { useDocLink } from '@/context/i18n'
type ExternalAPIFormProps = {
id: string
onSubmit: SubmitEventHandler<HTMLFormElement>
className?: string
itemClassName?: string
fieldLabelClassName?: string
value: CreateExternalAPIReq
onChange: (val: CreateExternalAPIReq) => void
formSchemas: FormSchema[]
inputClassName?: string
errors?: Partial<Record<'api_key' | 'endpoint' | 'name', string>>
}
const ExternalAPIForm: FC<ExternalAPIFormProps> = React.memo(
({
id,
onSubmit,
className,
itemClassName,
fieldLabelClassName,
value,
onChange,
formSchemas,
inputClassName,
errors,
}) => {
const { t, i18n } = useTranslation(['common', 'dataset'])
const docLink = useDocLink()
const handleFormChange = (key: string, val: string) => {
if (key === 'name') {
onChange({ ...value, [key]: val })
} else {
onChange({
...value,
settings: {
...value.settings,
[key]: val,
},
})
}
}
const renderField = (formSchema: FormSchema) => {
const { variable, type, label, required } = formSchema
const fieldValue =
variable === 'name'
? value[variable]
: value.settings[variable as keyof typeof value.settings] || ''
return (
<Field key={variable} name={variable} className={cn(itemClassName, 'self-stretch')}>
<div className="flex w-full items-center justify-between">
<label
className={cn(fieldLabelClassName, 'system-sm-semibold text-text-secondary')}
htmlFor={variable}
>
{label[i18n.language] || label.en_US}
{required && <span className="ml-1 text-red-500">*</span>}
</label>
{variable === 'endpoint' && (
<a
href={docLink('/use-dify/knowledge/external-knowledge-api') || '/'}
target="_blank"
rel="noopener noreferrer"
className="flex items-center body-xs-regular text-text-accent"
>
<RiBookOpenLine className="mr-1 size-3 text-text-accent" />
{t(($) => $.externalAPIPanelDocumentation, { ns: 'dataset' })}
</a>
)}
</div>
<Input
type={type === 'secret' ? 'password' : 'text'}
autoComplete="off"
inputMode={variable === 'endpoint' ? 'url' : undefined}
placeholder={t(($) => $['placeholder.input'], { ns: 'common' })}
spellCheck={variable === 'endpoint' || type === 'secret' ? false : undefined}
id={variable}
value={fieldValue}
onChange={(val) => handleFormChange(variable, val.target.value)}
required={required}
className={cn(inputClassName)}
/>
<FieldError />
</Field>
)
}
return (
<Form
id={id}
errors={errors}
onSubmit={onSubmit}
className={cn('flex flex-col items-start justify-center gap-4 self-stretch', className)}
>
{formSchemas.map((formSchema) => renderField(formSchema))}
</Form>
)
},
)
ExternalAPIForm.displayName = 'ExternalAPIForm'
export default ExternalAPIForm
@@ -0,0 +1,86 @@
import type { CreateExternalAPIReq, FormSchema } from '../../declarations'
import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useState } from 'react'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import ExternalAPIForm from '../Form'
vi.mock('@/context/i18n', () => ({
useDocLink: () => (path: string) => `https://docs.example.com${path}`,
}))
// Mock context for i18n doc link
describe('ExternalAPIForm', () => {
const defaultFormSchemas: FormSchema[] = [
{
variable: 'name',
type: 'text',
label: { en_US: 'Name', zh_CN: '名称' },
required: true,
},
{
variable: 'endpoint',
type: 'text',
label: { en_US: 'API Endpoint', zh_CN: 'API 端点' },
required: true,
},
{
variable: 'api_key',
type: 'secret',
label: { en_US: 'API Key', zh_CN: 'API 密钥' },
required: true,
},
]
const defaultValue: CreateExternalAPIReq = {
name: '',
settings: {
endpoint: '',
api_key: '',
},
}
const defaultProps = {
id: 'external-api-form',
onSubmit: vi.fn(),
value: defaultValue,
onChange: vi.fn(),
formSchemas: defaultFormSchemas,
}
beforeEach(() => {
vi.clearAllMocks()
})
it('edits the API name, endpoint and secret while preserving all fields', async () => {
const user = userEvent.setup()
const onChange = vi.fn()
const Harness = () => {
const [value, setValue] = useState(defaultValue)
return (
<ExternalAPIForm
{...defaultProps}
value={value}
onChange={(next) => {
setValue(next)
onChange(next)
}}
/>
)
}
render(<Harness />)
await user.type(screen.getByLabelText(/name/i), 'Knowledge API')
await user.type(screen.getByLabelText(/api endpoint/i), 'https://example.com/retrieval')
const secret = screen.getByLabelText(/api key/i)
expect(secret).toHaveAttribute('type', 'password')
await user.type(secret, 'secret-key')
expect(onChange).toHaveBeenLastCalledWith({
name: 'Knowledge API',
settings: { endpoint: 'https://example.com/retrieval', api_key: 'secret-key' },
})
expect(
screen.getByRole('link', { name: 'dataset.externalAPIPanelDocumentation' }),
).toHaveAttribute('href', 'https://docs.example.com/use-dify/knowledge/external-knowledge-api')
})
})
@@ -0,0 +1,135 @@
import type { ExternalKnowledgeApiResponse } from '@dify/contracts/api/console/datasets/types.gen'
import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { createExternalAPI } from '@/service/datasets'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import AddExternalAPIModal from '../index'
vi.mock('@/service/datasets', () => ({ createExternalAPI: vi.fn() }))
const { error } = vi.hoisted(() => ({ error: vi.fn() }))
vi.mock('@/app/notifications', () => ({ toast: { error, success: vi.fn() } }))
const data = {
name: 'Product API',
settings: { endpoint: 'https://api.example.com', api_key: 'secret-key' },
}
const response: ExternalKnowledgeApiResponse = {
...data,
id: 'api-1',
tenant_id: 'tenant-1',
description: '',
dataset_bindings: [],
created_by: 'user-1',
created_at: '2024-01-01T00:00:00Z',
}
const props = { onSave: vi.fn(), onCancel: vi.fn(), isEditMode: false }
const save = () => screen.getByRole('button', { name: 'dataset.externalAPIForm.save' })
async function fill(user: ReturnType<typeof userEvent.setup>, apiKey = data.settings.api_key) {
await user.type(screen.getByLabelText(/Name/), data.name)
await user.type(screen.getByLabelText(/API Endpoint/), data.settings.endpoint)
await user.type(screen.getByLabelText(/API Key/), apiKey)
}
beforeEach(() => {
vi.clearAllMocks()
vi.mocked(createExternalAPI).mockReset().mockResolvedValue(response)
})
it('creates an API with entered settings and returns the saved record before closing', async () => {
const user = userEvent.setup()
render(<AddExternalAPIModal {...props} />)
expect(save()).toBeDisabled()
await fill(user)
await user.click(save())
await waitFor(() => expect(props.onSave).toHaveBeenCalledWith(response))
expect(createExternalAPI).toHaveBeenCalledWith({ body: data })
expect(props.onCancel).toHaveBeenCalledOnce()
})
it('rejects short API keys without sending a request', async () => {
const user = userEvent.setup()
render(<AddExternalAPIModal {...props} />)
await fill(user, 'key')
await user.click(save())
expect(error).toHaveBeenCalledWith('common.apiBasedExtension.modal.apiKey.lengthError')
expect(createExternalAPI).not.toHaveBeenCalled()
expect(props.onCancel).not.toHaveBeenCalled()
})
it('shows one localized field error and does not request an invalid endpoint', async () => {
const user = userEvent.setup()
render(<AddExternalAPIModal {...props} />)
await user.type(screen.getByLabelText(/Name/), data.name)
const endpointInput = screen.getByLabelText(/API Endpoint/)
await user.type(endpointInput, 'not-a-url')
await user.type(screen.getByLabelText(/API Key/), 'key12345')
await user.click(save())
await waitFor(() => expect(endpointInput).toHaveFocus())
expect(screen.getAllByText('dataset.validation.invalidHttpUrl')).toHaveLength(1)
expect(endpointInput).toHaveAttribute('aria-invalid', 'true')
expect(endpointInput).toHaveAccessibleDescription('dataset.validation.invalidHttpUrl')
expect(createExternalAPI).not.toHaveBeenCalled()
expect(error).not.toHaveBeenCalled()
})
it('preserves entered settings for retry when creation fails', async () => {
const user = userEvent.setup()
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
vi.mocked(createExternalAPI)
.mockRejectedValueOnce(new Error('Offline'))
.mockResolvedValue(response)
render(<AddExternalAPIModal {...props} />)
await fill(user)
await user.click(save())
await waitFor(() => expect(error).toHaveBeenCalledWith('common.api.actionFailed'))
expect(props.onCancel).not.toHaveBeenCalled()
expect(screen.getByLabelText(/API Endpoint/)).toHaveValue(data.settings.endpoint)
await user.click(save())
await waitFor(() => expect(props.onSave).toHaveBeenCalledWith(response))
consoleError.mockRestore()
})
it('saves an unbound API through the edit callback with the updated fields', async () => {
const user = userEvent.setup()
const onEdit = vi.fn().mockResolvedValue(undefined)
render(<AddExternalAPIModal {...props} isEditMode data={data} onEdit={onEdit} />)
await user.type(screen.getByLabelText(/Name/), ' updated')
await user.click(save())
expect(onEdit).toHaveBeenCalledWith({ ...data, name: 'Product API updated' })
expect(createExternalAPI).not.toHaveBeenCalled()
})
it('requires confirmation before changing an API used by a dataset and allows backing out', async () => {
const user = userEvent.setup()
const onEdit = vi.fn().mockResolvedValue(undefined)
render(
<AddExternalAPIModal
{...props}
isEditMode
data={data}
onEdit={onEdit}
datasetBindings={[{ id: 'ds-1', name: 'Guide' }]}
/>,
)
await user.click(save())
let dialog = await screen.findByRole('alertdialog')
expect(onEdit).not.toHaveBeenCalled()
await user.click(within(dialog).getByRole('button', { name: 'common.operation.cancel' }))
expect(onEdit).not.toHaveBeenCalled()
expect(props.onCancel).not.toHaveBeenCalled()
await user.click(save())
dialog = await screen.findByRole('alertdialog')
await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
await waitFor(() => expect(onEdit).toHaveBeenCalledWith(data))
expect(props.onCancel).toHaveBeenCalledOnce()
expect(createExternalAPI).not.toHaveBeenCalled()
})
it.each(['dataset.externalAPIForm.cancel', 'common.operation.close'])(
'closes without saving through %s',
async (name) => {
const user = userEvent.setup()
render(<AddExternalAPIModal {...props} />)
await user.click(screen.getByRole('button', { name }))
expect(props.onCancel).toHaveBeenCalledOnce()
expect(createExternalAPI).not.toHaveBeenCalled()
},
)
@@ -0,0 +1,273 @@
import type { ExternalKnowledgeApiResponse } from '@dify/contracts/api/console/datasets/types.gen'
import type { FC } from 'react'
import type { CreateExternalAPIReq, FormSchema } from '../declarations'
import {
AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import {
Dialog,
DialogBody,
DialogContent,
DialogFooter,
DialogHeader,
DialogHeaderCloseButton,
DialogTitle,
} from '@langgenius/dify-ui/dialog'
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
import { RiBook2Line, RiInformation2Line } from '@remixicon/react'
import { memo, useId, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { EncryptedBottom } from '@/app/components/base/encrypted-bottom'
import { toast } from '@/app/notifications'
import { createExternalAPI } from '@/service/datasets'
import ExternalAPIForm from './Form'
type AddExternalAPIModalProps = {
data?: CreateExternalAPIReq
onSave: (api: ExternalKnowledgeApiResponse) => void
onCancel: () => void
onEdit?: (formValue: CreateExternalAPIReq) => Promise<void>
datasetBindings?: {
id: string
name: string
}[]
isEditMode: boolean
}
const formSchemas: FormSchema[] = [
{
variable: 'name',
type: 'text',
label: {
en_US: 'Name',
},
required: true,
},
{
variable: 'endpoint',
type: 'text',
label: {
en_US: 'API Endpoint',
},
required: true,
},
{
variable: 'api_key',
type: 'secret',
label: {
en_US: 'API Key',
},
required: true,
},
]
const emptyExternalAPIFormData: CreateExternalAPIReq = {
name: '',
settings: {
endpoint: '',
api_key: '',
},
}
function isValidHttpEndpoint(value: string) {
try {
const endpoint = new URL(value)
return (
(endpoint.protocol === 'http:' || endpoint.protocol === 'https:') && Boolean(endpoint.host)
)
} catch {
return false
}
}
const AddExternalAPIModal: FC<AddExternalAPIModalProps> = ({
data,
onSave,
onCancel,
datasetBindings,
isEditMode,
onEdit,
}) => {
const { t } = useTranslation(['common', 'dataset'])
const formId = useId()
const [loading, setLoading] = useState(false)
const [showConfirm, setShowConfirm] = useState(false)
const [endpointError, setEndpointError] = useState<string>()
const [formData, setFormData] = useState<CreateExternalAPIReq>(() =>
isEditMode && data ? data : emptyExternalAPIFormData,
)
const hasEmptyInputs = Object.values(formData).some((value) =>
typeof value === 'string'
? value.trim() === ''
: Object.values(value).some((v) => v.trim() === ''),
)
const handleDataChange = (val: CreateExternalAPIReq) => {
if (val.settings.endpoint !== formData.settings.endpoint) setEndpointError(undefined)
setFormData(val)
}
const handleSave = async () => {
const endpoint = formData.settings.endpoint.trim()
if (!isValidHttpEndpoint(endpoint)) {
setEndpointError(t(($) => $['validation.invalidHttpUrl'], { ns: 'dataset' }))
return
}
if (formData && formData.settings.api_key && formData.settings.api_key?.length < 5) {
toast.error(t(($) => $['apiBasedExtension.modal.apiKey.lengthError'], { ns: 'common' }))
setLoading(false)
return
}
try {
setLoading(true)
if (isEditMode && onEdit) {
// Only send [__HIDDEN__] when the user has not changed the key, otherwise
// send the actual api_key so updated tokens are persisted.
const apiKeyToSend =
formData.settings.api_key === '[__HIDDEN__]' ? '[__HIDDEN__]' : formData.settings.api_key
await onEdit({
...formData,
settings: { ...formData.settings, api_key: apiKeyToSend, endpoint },
})
} else {
const res = await createExternalAPI({
body: { ...formData, settings: { ...formData.settings, endpoint } },
})
if (res && res.id) onSave(res)
}
onCancel()
} catch (error) {
console.error('Error saving/updating external API:', error)
toast.error(t(($) => $['api.actionFailed'], { ns: 'common' }))
} finally {
setLoading(false)
}
}
const handleSubmit = () => {
if (hasEmptyInputs || loading) return
if (isEditMode && (datasetBindings?.length ?? 0) > 0) setShowConfirm(true)
else void handleSave()
}
return (
<Dialog
open
disablePointerDismissal
onOpenChange={(open) => {
if (!open) onCancel()
}}
>
<DialogContent>
<DialogHeader>
<DialogTitle>
{isEditMode
? t(($) => $.editExternalAPIFormTitle, { ns: 'dataset' })
: t(($) => $.createExternalAPI, { ns: 'dataset' })}
</DialogTitle>
{isEditMode && (datasetBindings?.length ?? 0) > 0 && (
<div className="flex items-center system-xs-regular text-text-tertiary">
{t(($) => $['editExternalAPIFormWarning.front'], { ns: 'dataset' })}
<span className="flex cursor-pointer items-center text-text-accent">
&nbsp;
{datasetBindings?.length}{' '}
{t(($) => $['editExternalAPIFormWarning.end'], { ns: 'dataset' })}
&nbsp;
<Popover>
<PopoverTrigger
openOnHover
aria-label={t(($) => $['editExternalAPIFormWarning.end'], { ns: 'dataset' })}
render={
<button
type="button"
className="flex size-3.5 items-center justify-center rounded-sm hover:bg-state-base-hover"
>
<RiInformation2Line className="size-3.5" />
</button>
}
/>
<PopoverContent className="flex w-[320px] items-center self-stretch px-3 py-2">
<div className="p-1">
<div className="flex items-start self-stretch pt-1 pr-3 pb-0.5 pl-2">
<div className="system-xs-medium-uppercase text-text-tertiary">{`${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="size-4 text-text-secondary" />
<div className="system-sm-medium text-text-secondary">{binding.name}</div>
</div>
))}
</div>
</PopoverContent>
</Popover>
</span>
</div>
)}
<DialogHeaderCloseButton aria-label={t(($) => $['operation.close'], { ns: 'common' })} />
</DialogHeader>
<DialogBody>
<ExternalAPIForm
id={formId}
value={formData}
onChange={handleDataChange}
onSubmit={(event) => {
event.preventDefault()
handleSubmit()
}}
formSchemas={formSchemas}
errors={{ endpoint: endpointError }}
/>
</DialogBody>
<DialogFooter>
<Button type="button" variant="secondary" onClick={onCancel}>
{t(($) => $['externalAPIForm.cancel'], { ns: 'dataset' })}
</Button>
<Button
form={formId}
type="submit"
variant="primary"
loading={loading}
disabled={hasEmptyInputs}
>
{t(($) => $['externalAPIForm.save'], { ns: 'dataset' })}
</Button>
</DialogFooter>
<EncryptedBottom
front={t(($) => $['externalAPIForm.encrypted.front'], { ns: 'dataset' })}
back={t(($) => $['externalAPIForm.encrypted.end'], { ns: 'dataset' })}
/>
<AlertDialog
open={showConfirm && (datasetBindings?.length ?? 0) > 0}
onOpenChange={(open) => !open && setShowConfirm(false)}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Warning</AlertDialogTitle>
<AlertDialogDescription>
{`${t(($) => $['editExternalAPIConfirmWarningContent.front'], { ns: 'dataset' })} ${datasetBindings?.length} ${t(($) => $['editExternalAPIConfirmWarningContent.end'], { ns: 'dataset' })}`}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancelButton>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</AlertDialogCancelButton>
<AlertDialogConfirmButton onClick={handleSave}>
{t(($) => $['operation.confirm'], { ns: 'common' })}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</DialogContent>
</Dialog>
)
}
export default memo(AddExternalAPIModal)
@@ -0,0 +1,109 @@
import type { ExternalKnowledgeApiListResponse } from '@dify/contracts/api/console/datasets/types.gen'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
import { createExternalAPI } from '@/service/datasets'
import { renderWithConfigurationModals as render } from '@/test/configuration-modals'
import ExternalAPIPanel from '../index'
const { getApis } = vi.hoisted(() => ({ getApis: vi.fn() }))
vi.mock('@/service/datasets', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/datasets')>()),
createExternalAPI: vi.fn(),
}))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'datasets.externalKnowledgeApi.get': getApis,
}),
}
})
const response: ExternalKnowledgeApiListResponse = {
data: [
{
id: 'api-1',
tenant_id: 'tenant-1',
name: 'Product knowledge',
description: '',
settings: { endpoint: 'https://knowledge.example.com', api_key: 'key' },
dataset_bindings: [],
created_by: 'user-1',
created_at: '2021-01-01T00:00:00Z',
},
],
has_more: false,
limit: 20,
page: 1,
total: 1,
}
describe('ExternalAPIPanel', () => {
beforeEach(() => {
getApis.mockResolvedValue(response)
vi.mocked(createExternalAPI).mockResolvedValue(response.data[0]!)
})
it('replaces loading with API cards and allows the panel to close', async () => {
const user = userEvent.setup()
let resolve!: (value: ExternalKnowledgeApiListResponse) => void
getApis.mockReturnValue(
new Promise<ExternalKnowledgeApiListResponse>((done) => {
resolve = done
}),
)
const onClose = vi.fn()
render(<ExternalAPIPanel canManageExternalKnowledgeApi onClose={onClose} />)
expect(screen.getByLabelText('common.loading')).toBeInTheDocument()
await act(async () => resolve(response))
expect(await screen.findByText('Product knowledge')).toBeInTheDocument()
expect(screen.getByText('https://knowledge.example.com')).toBeInTheDocument()
expect(screen.queryByLabelText('common.loading')).not.toBeInTheDocument()
await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
expect(onClose).toHaveBeenCalledOnce()
})
it('shows read-only API cards when management is unavailable', async () => {
render(<ExternalAPIPanel canManageExternalKnowledgeApi={false} onClose={vi.fn()} />)
expect(await screen.findByText('Product knowledge')).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: 'dataset.createExternalAPI' }),
).not.toBeInTheDocument()
expect(screen.queryByRole('button', { name: /common.operation.edit/ })).not.toBeInTheDocument()
expect(
screen.queryByRole('button', { name: /common.operation.delete/ }),
).not.toBeInTheDocument()
})
it('opens a blank creation form and refreshes the actual list after save', async () => {
const user = userEvent.setup()
getApis.mockResolvedValueOnce({ ...response, data: [], total: 0 })
render(<ExternalAPIPanel canManageExternalKnowledgeApi onClose={vi.fn()} />)
await user.click(screen.getByRole('button', { name: 'dataset.createExternalAPI' }))
const dialog = await screen.findByRole('dialog', { name: 'dataset.createExternalAPI' })
expect(within(dialog).getByLabelText(/Name/)).toHaveValue('')
expect(within(dialog).getByLabelText(/API Endpoint/)).toHaveValue('')
expect(within(dialog).getByLabelText(/API Key/)).toHaveValue('')
await user.type(within(dialog).getByLabelText(/Name/), 'Product knowledge')
await user.type(within(dialog).getByLabelText(/API Endpoint/), 'https://knowledge.example.com')
await user.type(within(dialog).getByLabelText(/API Key/), 'secret-key')
await user.click(within(dialog).getByRole('button', { name: 'dataset.externalAPIForm.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(createExternalAPI).toHaveBeenCalledWith({
body: {
name: 'Product knowledge',
settings: { endpoint: 'https://knowledge.example.com', api_key: 'secret-key' },
},
})
expect(await screen.findByText('Product knowledge')).toBeInTheDocument()
expect(
screen.getByRole('button', { name: /common.operation.edit Product knowledge/ }),
).toBeInTheDocument()
expect(
screen.getByRole('button', { name: /common.operation.delete Product knowledge/ }),
).toBeInTheDocument()
})
})
@@ -0,0 +1,115 @@
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { RiAddLine, RiBookOpenLine, RiCloseLine } from '@remixicon/react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import { useDocLink } from '@/context/i18n'
import { useModalContext } from '@/context/modal-context'
import { consoleQuery } from '@/service/console'
import ExternalKnowledgeAPICard from '../external-knowledge-api-card'
type ExternalAPIPanelProps = {
canManageExternalKnowledgeApi: boolean
onClose: () => void
}
const ExternalAPIPanel: React.FC<ExternalAPIPanelProps> = ({
canManageExternalKnowledgeApi,
onClose,
}) => {
const { t } = useTranslation(['common', 'dataset'])
const docLink = useDocLink()
const { setShowExternalKnowledgeAPIModal } = useModalContext()
const queryClient = useQueryClient()
const externalKnowledgeApiQueryOptions =
consoleQuery.datasets.externalKnowledgeApi.get.queryOptions({ input: {} })
const { data, isLoading } = useQuery(externalKnowledgeApiQueryOptions)
const externalKnowledgeApiList = data?.data ?? []
const handleOpenExternalAPIModal = () => {
if (!canManageExternalKnowledgeApi) return
setShowExternalKnowledgeAPIModal({
payload: { name: '', settings: { endpoint: '', api_key: '' } },
datasetBindings: [],
onSaveCallback: () => {
void queryClient.invalidateQueries({
queryKey: externalKnowledgeApiQueryOptions.queryKey,
})
},
isEditMode: false,
})
}
return (
<div tabIndex={-1} className={cn('absolute top-14 right-0 bottom-2 z-10 flex outline-hidden')}>
<div
className={cn(
'relative flex h-full w-105 flex-col rounded-l-2xl border border-components-panel-border bg-components-panel-bg-alt',
)}
>
<div className="flex items-start self-stretch p-4 pb-0">
<div className="flex grow flex-col items-start gap-1">
<div className="self-stretch system-xl-semibold text-text-primary">
{t(($) => $.externalAPIPanelTitle, { ns: 'dataset' })}
</div>
<div className="self-stretch body-xs-regular text-text-tertiary">
{t(($) => $.externalAPIPanelDescription, { ns: 'dataset' })}
</div>
<a
className="flex cursor-pointer items-center justify-center gap-1 self-stretch"
href={docLink('/use-dify/knowledge/external-knowledge-api')}
target="_blank"
>
<RiBookOpenLine className="size-3 text-text-accent" />
<div className="grow body-xs-regular text-text-accent">
{t(($) => $.externalAPIPanelDocumentation, { ns: 'dataset' })}
</div>
</a>
</div>
<div className="flex items-center">
<IconButton
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
onClick={() => onClose()}
>
<RiCloseLine aria-hidden className="size-4 text-text-tertiary" />
</IconButton>
</div>
</div>
{canManageExternalKnowledgeApi && (
<div className="flex flex-col items-start justify-center gap-2 self-stretch px-4 py-3">
<Button
variant="primary"
className="flex items-center justify-center px-3 py-2"
onClick={handleOpenExternalAPIModal}
>
<RiAddLine className="size-4 text-components-button-primary-text" />
<div className="system-sm-medium text-components-button-primary-text">
{t(($) => $.createExternalAPI, { ns: 'dataset' })}
</div>
</Button>
</div>
)}
<div className="flex grow flex-col items-start gap-1 self-stretch px-4 py-0">
{isLoading ? (
<LoadingPlaceholder />
) : (
externalKnowledgeApiList.map((api, index) => (
<ExternalKnowledgeAPICard
key={api.id}
api={api}
canManageExternalKnowledgeApi={canManageExternalKnowledgeApi}
position={index + 1}
/>
))
)}
</div>
</div>
</div>
)
}
export default ExternalAPIPanel
@@ -0,0 +1,250 @@
import type { ExternalKnowledgeApiResponse } from '@dify/contracts/api/console/datasets/types.gen'
import { useQuery } from '@tanstack/react-query'
import { act, screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { consoleQuery } from '@/service/console'
import {
checkUsageExternalAPI,
deleteExternalAPI,
fetchExternalAPI,
updateExternalAPI,
} from '@/service/datasets'
import { renderWithConfigurationModals } from '@/test/configuration-modals'
import { createConsoleQueryClient } from '@/test/console/query-data'
import { createDeferred } from '@/test/deferred'
import ExternalKnowledgeAPICard from '../index'
vi.mock('@/service/datasets', async (importOriginal) => ({
...(await importOriginal<typeof import('@/service/datasets')>()),
fetchExternalAPI: vi.fn(),
updateExternalAPI: vi.fn(),
deleteExternalAPI: vi.fn(),
checkUsageExternalAPI: vi.fn(),
}))
const { getApis } = vi.hoisted(() => ({ getApis: vi.fn() }))
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
'datasets.externalKnowledgeApi.get': getApis,
}),
}
})
const api = {
id: 'api-123',
tenant_id: 'tenant-1',
name: 'Test External API',
description: 'Test API description',
settings: { endpoint: 'https://api.example.com/knowledge', api_key: 'secret-key-123' },
dataset_bindings: [],
created_by: 'user-1',
created_at: '2021-01-01T00:00:00Z',
} satisfies ExternalKnowledgeApiResponse
const listResponse = (data: ExternalKnowledgeApiResponse[]) => ({
data,
has_more: false,
page: 1,
limit: 20,
total: data.length,
})
const listOptions = consoleQuery.datasets.externalKnowledgeApi.get.queryOptions({ input: {} })
function setup({ apis = [api], canManage = true } = {}) {
const queryClient = createConsoleQueryClient()
queryClient.setQueryData(listOptions.queryKey, listResponse(apis))
function ApiCards() {
const { data } = useQuery(listOptions)
return data?.data.map((item, index) => (
<ExternalKnowledgeAPICard
key={item.id}
api={item}
position={index + 1}
canManageExternalKnowledgeApi={canManage}
/>
))
}
return renderWithConfigurationModals(<ApiCards />, { queryClient })
}
const edit = () =>
screen.getByRole('button', {
name: `common.operation.edit ${api.name} ${api.settings.endpoint} 1`,
})
const remove = () =>
screen.getByRole('button', {
name: `common.operation.delete ${api.name} ${api.settings.endpoint} 1`,
})
beforeEach(() => {
vi.mocked(fetchExternalAPI).mockReset().mockResolvedValue(api)
vi.mocked(updateExternalAPI).mockReset().mockResolvedValue(api)
vi.mocked(deleteExternalAPI).mockReset().mockResolvedValue({ result: 'success' })
vi.mocked(checkUsageExternalAPI).mockReset().mockResolvedValue({ is_using: false, count: 0 })
getApis.mockReset().mockResolvedValue(listResponse([api]))
})
it('targets the correct API when cards have duplicate names and endpoints', async () => {
const user = userEvent.setup()
setup({ apis: [api, { ...api, id: 'api-456' }] })
await user.click(
screen.getByRole('button', {
name: `common.operation.delete ${api.name} ${api.settings.endpoint} 2`,
}),
)
expect(checkUsageExternalAPI).toHaveBeenCalledWith({ apiTemplateId: 'api-456' })
expect(await screen.findByRole('alertdialog')).toBeVisible()
})
it('hides management actions without permission', () => {
setup({ canManage: false })
expect(screen.getByText(api.name)).toBeVisible()
expect(
screen.queryByRole('button', { name: /common.operation.(edit|delete)/ }),
).not.toBeInTheDocument()
})
it('loads API details and bindings into the real edit dialog', async () => {
const user = userEvent.setup()
vi.mocked(fetchExternalAPI).mockResolvedValue({
...api,
dataset_bindings: [{ id: 'ds-1', name: 'Dataset 1' }],
})
setup()
await user.click(edit())
const dialog = await screen.findByRole('dialog', { name: 'dataset.editExternalAPIFormTitle' })
expect(fetchExternalAPI).toHaveBeenCalledWith({ apiTemplateId: api.id })
expect(within(dialog).getByLabelText(/Name/)).toHaveValue(api.name)
expect(within(dialog).getByLabelText(/API Endpoint/)).toHaveValue(api.settings.endpoint)
expect(within(dialog).getByLabelText(/API Key/)).toHaveValue(api.settings.api_key)
expect(dialog).toHaveTextContent('1 dataset.editExternalAPIFormWarning.end')
})
it('saves edits through the modal and refreshes the displayed card', async () => {
const user = userEvent.setup()
const updated = {
...api,
name: 'Updated External API',
settings: { endpoint: 'https://updated.example.com/knowledge', api_key: 'updated-secret-key' },
}
getApis.mockResolvedValue(listResponse([updated]))
setup()
await user.click(edit())
const dialog = await screen.findByRole('dialog', { name: 'dataset.editExternalAPIFormTitle' })
for (const [label, value] of [
[/Name/, updated.name],
[/API Endpoint/, updated.settings.endpoint],
[/API Key/, updated.settings.api_key],
] as const) {
await user.clear(within(dialog).getByLabelText(label))
await user.type(within(dialog).getByLabelText(label), value)
}
await user.click(within(dialog).getByRole('button', { name: 'dataset.externalAPIForm.save' }))
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
expect(updateExternalAPI).toHaveBeenCalledWith({
apiTemplateId: api.id,
body: { name: updated.name, settings: updated.settings },
})
expect(await screen.findByText(updated.name)).toBeVisible()
expect(screen.getByText(updated.settings.endpoint)).toBeVisible()
expect(screen.queryByText(api.name)).not.toBeInTheDocument()
})
it('shows the usage count before deleting a connected API', async () => {
const user = userEvent.setup()
vi.mocked(checkUsageExternalAPI).mockResolvedValue({ is_using: true, count: 3 })
setup()
await user.click(remove())
expect(await screen.findByRole('alertdialog')).toHaveTextContent('3')
expect(deleteExternalAPI).not.toHaveBeenCalled()
})
it('deletes a confirmed API and removes its card after refreshing the list', async () => {
const user = userEvent.setup()
getApis.mockResolvedValue(listResponse([]))
setup()
await user.click(remove())
await user.click(
within(await screen.findByRole('alertdialog')).getByRole('button', {
name: 'common.operation.confirm',
}),
)
await waitFor(() => expect(screen.queryByText(api.name)).not.toBeInTheDocument())
expect(deleteExternalAPI).toHaveBeenCalledWith({ apiTemplateId: api.id })
expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
})
it('keeps deletion pending in the dialog and prevents duplicate requests', async () => {
const user = userEvent.setup()
const request = createDeferred<{ result: string }>()
vi.mocked(deleteExternalAPI).mockReturnValueOnce(request.promise)
getApis.mockResolvedValue(listResponse([]))
setup()
await user.click(remove())
const dialog = await screen.findByRole('alertdialog')
const confirm = within(dialog).getByRole('button', { name: 'common.operation.confirm' })
const cancel = within(dialog).getByRole('button', { name: 'common.operation.cancel' })
await user.click(confirm)
expect(confirm).toHaveAttribute('aria-disabled', 'true')
expect(cancel).toBeDisabled()
expect(deleteExternalAPI).toHaveBeenCalledTimes(1)
await user.click(confirm)
await user.keyboard('{Escape}')
expect(screen.getByRole('alertdialog')).toBeVisible()
expect(deleteExternalAPI).toHaveBeenCalledTimes(1)
await act(async () => request.resolve({ result: 'success' }))
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(screen.queryByText(api.name)).not.toBeInTheDocument()
})
it('cancels deletion without changing the list', async () => {
const user = userEvent.setup()
setup()
await user.click(remove())
await user.click(
within(await screen.findByRole('alertdialog')).getByRole('button', {
name: 'common.operation.cancel',
}),
)
await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())
expect(screen.getByText(api.name)).toBeVisible()
expect(deleteExternalAPI).not.toHaveBeenCalled()
expect(getApis).not.toHaveBeenCalled()
})
it.each(['fetch', 'usage', 'delete'] as const)(
'preserves the card when the %s request fails',
async (operation) => {
const user = userEvent.setup()
const failure = new Error('Request failed')
const service =
operation === 'fetch'
? fetchExternalAPI
: operation === 'usage'
? checkUsageExternalAPI
: deleteExternalAPI
const request = createDeferred<never>()
vi.mocked(service).mockReturnValueOnce(request.promise)
const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
setup()
await user.click(operation === 'fetch' ? edit() : remove())
if (operation === 'delete')
await user.click(
within(await screen.findByRole('alertdialog')).getByRole('button', {
name: 'common.operation.confirm',
}),
)
await act(async () => request.reject(failure))
expect(screen.getByText(api.name)).toBeVisible()
expect(getApis).not.toHaveBeenCalled()
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
if (operation !== 'delete') expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
} finally {
consoleError.mockRestore()
}
},
)
@@ -0,0 +1,186 @@
import type { ExternalKnowledgeApiResponse } from '@dify/contracts/api/console/datasets/types.gen'
import type { CreateExternalAPIReq } from '../declarations'
import {
AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useQueryClient } from '@tanstack/react-query'
import * as React from 'react'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useModalContext } from '@/context/modal-context'
import { consoleQuery } from '@/service/console'
import {
checkUsageExternalAPI,
deleteExternalAPI,
fetchExternalAPI,
updateExternalAPI,
} from '@/service/datasets'
type ExternalKnowledgeAPICardProps = {
api: ExternalKnowledgeApiResponse
canManageExternalKnowledgeApi: boolean
position: number
}
const ExternalKnowledgeAPICard: React.FC<ExternalKnowledgeAPICardProps> = ({
api,
canManageExternalKnowledgeApi,
position,
}) => {
const { setShowExternalKnowledgeAPIModal } = useModalContext()
const [showConfirm, setShowConfirm] = useState(false)
const [isDeleting, setIsDeleting] = useState(false)
const [isHovered, setIsHovered] = useState(false)
const [usageCount, setUsageCount] = useState(0)
const queryClient = useQueryClient()
const externalKnowledgeApiQueryKey = consoleQuery.datasets.externalKnowledgeApi.get.queryOptions({
input: {},
}).queryKey
const endpoint =
api.settings && typeof api.settings.endpoint === 'string' ? api.settings.endpoint : ''
const { t } = useTranslation(['common', 'dataset'])
const handleEditClick = async () => {
if (!canManageExternalKnowledgeApi) return
try {
const response = await fetchExternalAPI({ apiTemplateId: api.id })
const formValue: CreateExternalAPIReq = {
name: response.name,
settings: {
endpoint: response.settings?.endpoint ?? '',
api_key: response.settings?.api_key ?? '',
},
}
setShowExternalKnowledgeAPIModal({
payload: formValue,
isEditMode: true,
datasetBindings: response.dataset_bindings,
onEditCallback: async (updatedData: CreateExternalAPIReq) => {
try {
await updateExternalAPI({
apiTemplateId: api.id,
body: { name: updatedData.name, settings: updatedData.settings },
})
await queryClient.invalidateQueries({ queryKey: externalKnowledgeApiQueryKey })
} catch (error) {
console.error('Error updating external knowledge API:', error)
}
},
})
} catch (error) {
console.error('Error fetching external knowledge API data:', error)
}
}
const handleDeleteClick = async () => {
if (!canManageExternalKnowledgeApi) return
try {
const usage = await checkUsageExternalAPI({ apiTemplateId: api.id })
if (usage.is_using) setUsageCount(usage.count)
setShowConfirm(true)
} catch (error) {
console.error('Error checking external API usage:', error)
}
}
const handleConfirmDelete = async () => {
if (!canManageExternalKnowledgeApi || isDeleting) return
setIsDeleting(true)
try {
await deleteExternalAPI({ apiTemplateId: api.id })
setShowConfirm(false)
await queryClient.invalidateQueries({ queryKey: externalKnowledgeApiQueryKey })
} catch (error) {
console.error('Error deleting external knowledge API:', error)
} finally {
setIsDeleting(false)
}
}
return (
<>
<div
className={`flex items-start self-stretch rounded-lg border-[0.5px] border-components-panel-border-subtle bg-components-panel-on-panel-item-bg p-2 ps-3 ${isHovered ? 'border-state-destructive-border bg-state-destructive-hover' : ''}`}
>
<div className="flex grow flex-col items-start justify-center gap-1.5 py-1">
<div className="flex items-center gap-1 self-stretch text-text-secondary">
<span
aria-hidden
className="i-custom-vender-solid-development-api-connection-mod size-4"
/>
<div className="system-sm-medium">{api.name}</div>
</div>
<div className="self-stretch system-xs-regular text-text-tertiary">{endpoint}</div>
</div>
{canManageExternalKnowledgeApi && (
<div className="flex items-start gap-1">
<IconButton
aria-label={`${t(($) => $['operation.edit'], { ns: 'common' })} ${api.name} ${endpoint} ${position}`}
onClick={handleEditClick}
>
<span
aria-hidden
className="i-ri-edit-line size-4 text-text-tertiary hover:text-text-secondary"
/>
</IconButton>
<IconButton
aria-label={`${t(($) => $['operation.delete'], { ns: 'common' })} ${api.name} ${endpoint} ${position}`}
tone="destructive"
onClick={handleDeleteClick}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
<span aria-hidden className="i-ri-delete-bin-line size-4" />
</IconButton>
</div>
)}
</div>
<AlertDialog
open={showConfirm}
onOpenChange={(open, details) => {
if (!open && isDeleting) details.cancel()
else setShowConfirm(open)
}}
>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>
{`${t(($) => $['deleteExternalAPIConfirmWarningContent.title.front'], { ns: 'dataset' })} ${api.name}${t(($) => $['deleteExternalAPIConfirmWarningContent.title.end'], { ns: 'dataset' })}`}
</AlertDialogTitle>
<AlertDialogDescription>
{usageCount > 0
? `${t(($) => $['deleteExternalAPIConfirmWarningContent.content.front'], { ns: 'dataset' })} ${usageCount} ${t(($) => $['deleteExternalAPIConfirmWarningContent.content.end'], { ns: 'dataset' })}`
: t(($) => $['deleteExternalAPIConfirmWarningContent.noConnectionContent'], {
ns: 'dataset',
})}
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancelButton disabled={isDeleting}>
{t(($) => $['operation.cancel'], { ns: 'common' })}
</AlertDialogCancelButton>
<AlertDialogConfirmButton loading={isDeleting} onClick={handleConfirmDelete}>
{t(($) => $['operation.confirm'], { ns: 'common' })}
</AlertDialogConfirmButton>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
)
}
export default ExternalKnowledgeAPICard