chore: 纳入本地 Dify 1.19.0 源码及品牌与免登改动
演示目录只保留可重建的源码。运行密钥、数据卷、依赖和带口令的本地配置不进入仓库。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
60158935f4
commit
6519682885
15831 files changed
+3063428
No files matched your search
+116
@@ -0,0 +1,116 @@
|
||||
import { screen, waitFor } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithAccountProfile as render } from '@/test/console/account-profile'
|
||||
import { DatasetACLPermission } from '@/utils/permission'
|
||||
import ApiAccess from '../index'
|
||||
|
||||
let mockDatasetId = 'dataset-123'
|
||||
let mockMutateDatasetRes = vi.fn()
|
||||
let mockDatasetPermissionKeys: string[] = [DatasetACLPermission.Edit]
|
||||
const mockEnableApi = vi.fn()
|
||||
const mockDisableApi = vi.fn()
|
||||
|
||||
vi.mock('@/context/workspace-state', async () => {
|
||||
const { createWorkspaceStateModuleMock } = await import('@/test/console/state-fixture')
|
||||
return createWorkspaceStateModuleMock(() => ({
|
||||
currentWorkspace: { id: 'workspace-1' },
|
||||
}))
|
||||
})
|
||||
|
||||
vi.mock('@/context/dataset-detail', () => ({
|
||||
useDatasetDetailContextWithSelector: (selector: (state: Record<string, unknown>) => unknown) =>
|
||||
selector({
|
||||
dataset: {
|
||||
id: mockDatasetId,
|
||||
permission_keys: mockDatasetPermissionKeys,
|
||||
},
|
||||
mutateDatasetRes: mockMutateDatasetRes,
|
||||
}),
|
||||
}))
|
||||
|
||||
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.byDatasetId.apiKeys.byStatus.post': (input) =>
|
||||
((input: { params: { status: string } }) =>
|
||||
input.params.status === 'enable' ? mockEnableApi(input) : mockDisableApi(input))(input),
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
vi.mock('@/hooks/use-api-access-url', () => ({
|
||||
useDatasetApiAccessUrl: () => 'https://docs.dify.ai/api-reference/datasets',
|
||||
}))
|
||||
|
||||
vi.mock('@/context/permission-state', async () => {
|
||||
const { createPermissionStateModuleMock } = await import('@/test/console/state-fixture')
|
||||
|
||||
return createPermissionStateModuleMock(() => ({
|
||||
workspacePermissionKeys: [],
|
||||
}))
|
||||
})
|
||||
|
||||
describe('Dataset API access', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockDatasetId = 'dataset-123'
|
||||
mockMutateDatasetRes = vi.fn()
|
||||
mockDatasetPermissionKeys = [DatasetACLPermission.Edit]
|
||||
})
|
||||
|
||||
it.each([true, false])(
|
||||
'opens API details from the keyboard when sidebar expanded=%s',
|
||||
async (expand) => {
|
||||
const user = userEvent.setup()
|
||||
render(<ApiAccess expand={expand} apiEnabled />)
|
||||
const trigger = screen.getByRole('button', { name: 'common.appMenus.apiAccess' })
|
||||
await user.tab()
|
||||
expect(trigger).toHaveFocus()
|
||||
await user.keyboard('{Enter}')
|
||||
expect(await screen.findByText('dataset.serviceApi.enabled')).toBeInTheDocument()
|
||||
expect(
|
||||
screen.getByRole('link', { name: 'appOverview.overview.apiInfo.doc' }),
|
||||
).toHaveAttribute('href', 'https://docs.dify.ai/api-reference/datasets')
|
||||
},
|
||||
)
|
||||
|
||||
it('enables the dataset API and refreshes dataset state', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockEnableApi.mockResolvedValue({ result: 'success' })
|
||||
render(<ApiAccess expand apiEnabled={false} />)
|
||||
await user.click(screen.getByRole('button', { name: 'common.appMenus.apiAccess' }))
|
||||
|
||||
await user.click(screen.getByRole('switch'))
|
||||
|
||||
expect(mockEnableApi).toHaveBeenCalledWith({
|
||||
params: { dataset_id: 'dataset-123', status: 'enable' },
|
||||
})
|
||||
await waitFor(() => expect(mockMutateDatasetRes).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('disables the dataset API and refreshes dataset state', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockDisableApi.mockResolvedValue({ result: 'success' })
|
||||
render(<ApiAccess expand apiEnabled />)
|
||||
await user.click(screen.getByRole('button', { name: 'common.appMenus.apiAccess' }))
|
||||
|
||||
await user.click(screen.getByRole('switch'))
|
||||
|
||||
expect(mockDisableApi).toHaveBeenCalledWith({
|
||||
params: { dataset_id: 'dataset-123', status: 'disable' },
|
||||
})
|
||||
await waitFor(() => expect(mockMutateDatasetRes).toHaveBeenCalledOnce())
|
||||
})
|
||||
|
||||
it('prevents API changes without dataset edit permission', async () => {
|
||||
const user = userEvent.setup()
|
||||
mockDatasetPermissionKeys = []
|
||||
render(<ApiAccess expand apiEnabled />)
|
||||
await user.click(screen.getByRole('button', { name: 'common.appMenus.apiAccess' }))
|
||||
|
||||
expect(screen.getByRole('switch')).toHaveAttribute('aria-disabled', 'true')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { StatusDot } from '@langgenius/dify-ui/status-dot'
|
||||
import { Switch } from '@langgenius/dify-ui/switch'
|
||||
import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useAtomValue } from 'jotai'
|
||||
import * as React from 'react'
|
||||
import { useCallback } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { useDatasetDetailContextWithSelector } from '@/context/dataset-detail'
|
||||
import { workspacePermissionKeysAtom } from '@/context/permission-state'
|
||||
import { userProfileQueryOptions } from '@/features/account-profile/client'
|
||||
import { useDatasetApiAccessUrl } from '@/hooks/use-api-access-url'
|
||||
import Link from '@/next/link'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { getDatasetACLCapabilities } from '@/utils/permission'
|
||||
|
||||
type CardProps = {
|
||||
apiEnabled: boolean
|
||||
}
|
||||
|
||||
const Card = ({ apiEnabled }: CardProps) => {
|
||||
const { t } = useTranslation(['appOverview', 'common', 'dataset'])
|
||||
const datasetId = useDatasetDetailContextWithSelector((state) => state.dataset?.id)
|
||||
const dataset = useDatasetDetailContextWithSelector((state) => state.dataset)
|
||||
const mutateDatasetRes = useDatasetDetailContextWithSelector((state) => state.mutateDatasetRes)
|
||||
const { data: currentUserId } = useSuspenseQuery({
|
||||
...userProfileQueryOptions(),
|
||||
select: (data) => data.profile.id,
|
||||
})
|
||||
const workspacePermissionKeys = useAtomValue(workspacePermissionKeysAtom)
|
||||
const { mutateAsync: updateDatasetServiceApiStatus } = useMutation(
|
||||
consoleQuery.datasets.byDatasetId.apiKeys.byStatus.post.mutationOptions(),
|
||||
)
|
||||
|
||||
const datasetACLCapabilities = React.useMemo(
|
||||
() =>
|
||||
getDatasetACLCapabilities(dataset?.permission_keys, {
|
||||
currentUserId,
|
||||
resourceMaintainer: dataset?.maintainer,
|
||||
workspacePermissionKeys,
|
||||
}),
|
||||
[dataset?.maintainer, dataset?.permission_keys, currentUserId, workspacePermissionKeys],
|
||||
)
|
||||
const canManageApiAccess = datasetACLCapabilities.canEdit
|
||||
|
||||
const apiReferenceUrl = useDatasetApiAccessUrl()
|
||||
|
||||
const onToggle = useCallback(
|
||||
async (state: boolean) => {
|
||||
const { result } = await updateDatasetServiceApiStatus({
|
||||
params: { dataset_id: datasetId ?? '', status: state ? 'enable' : 'disable' },
|
||||
})
|
||||
if (result === 'success') mutateDatasetRes?.()
|
||||
},
|
||||
[datasetId, updateDatasetServiceApiStatus, mutateDatasetRes],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="w-52 rounded-xl border-[0.5px] border-components-panel-border bg-components-panel-bg-blur shadow-lg">
|
||||
<div className="p-1">
|
||||
<div className="p-2">
|
||||
<div className="mb-1.5 flex justify-between">
|
||||
<div className="flex items-center gap-1">
|
||||
<StatusDot className="shrink-0" status={apiEnabled ? 'success' : 'warning'} />
|
||||
<div
|
||||
className={cn(
|
||||
'system-xs-semibold-uppercase',
|
||||
apiEnabled ? 'text-text-success' : 'text-text-warning',
|
||||
)}
|
||||
>
|
||||
{apiEnabled
|
||||
? t(($) => $['serviceApi.enabled'], { ns: 'dataset' })
|
||||
: t(($) => $['serviceApi.disabled'], { ns: 'dataset' })}
|
||||
</div>
|
||||
</div>
|
||||
<Switch
|
||||
checked={apiEnabled}
|
||||
onCheckedChange={onToggle}
|
||||
disabled={!canManageApiAccess}
|
||||
/>
|
||||
</div>
|
||||
<div className="system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['appMenus.apiAccessTip'], { ns: 'common' })}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="h-px bg-divider-subtle"></div>
|
||||
<div className="p-1">
|
||||
<Link
|
||||
href={apiReferenceUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex h-8 items-center space-x-1.75 rounded-lg px-2 text-text-tertiary hover:bg-state-base-hover"
|
||||
>
|
||||
<span className="i-ri-book-open-line size-3.5 shrink-0" />
|
||||
<div className="grow truncate system-sm-regular">
|
||||
{t(($) => $['overview.apiInfo.doc'], { ns: 'appOverview' })}
|
||||
</div>
|
||||
<span className="i-ri-arrow-right-up-line size-3.5 shrink-0" />
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(Card)
|
||||
@@ -0,0 +1,70 @@
|
||||
import { cn } from '@langgenius/dify-ui/cn'
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@langgenius/dify-ui/popover'
|
||||
import { StatusDot } from '@langgenius/dify-ui/status-dot'
|
||||
import * as React from 'react'
|
||||
import { useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import Card from './card'
|
||||
|
||||
type ApiAccessProps = {
|
||||
expand: boolean
|
||||
apiEnabled: boolean
|
||||
}
|
||||
|
||||
const ApiAccess = ({ expand, apiEnabled }: ApiAccessProps) => {
|
||||
const { t } = useTranslation(['common'])
|
||||
const [open, setOpen] = useState(false)
|
||||
|
||||
return (
|
||||
<div className={cn(expand ? 'px-1 py-2' : 'flex justify-center px-3 py-2')}>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger
|
||||
render={(props, state) => (
|
||||
<button
|
||||
{...props}
|
||||
type="button"
|
||||
aria-label={!expand ? t(($) => $['appMenus.apiAccess'], { ns: 'common' }) : undefined}
|
||||
className={cn(
|
||||
'nokey w-full rounded-lg border-none bg-transparent p-0 text-left',
|
||||
props.className,
|
||||
)}
|
||||
>
|
||||
<div
|
||||
className={cn(
|
||||
'relative flex h-8 cursor-pointer items-center gap-2 rounded-lg border border-components-panel-border px-3',
|
||||
!expand && 'w-8 justify-center',
|
||||
state.open ? 'bg-state-base-hover' : 'hover:bg-state-base-hover',
|
||||
)}
|
||||
>
|
||||
<span
|
||||
aria-hidden
|
||||
className="i-custom-vender-knowledge-api-aggregate size-4 shrink-0 text-text-secondary"
|
||||
/>
|
||||
{expand && (
|
||||
<div className="min-w-0 grow truncate system-sm-regular text-text-secondary">
|
||||
{t(($) => $['appMenus.apiAccess'], { ns: 'common' })}
|
||||
</div>
|
||||
)}
|
||||
<StatusDot
|
||||
className={cn('shrink-0', !expand && 'absolute -top-px -right-px')}
|
||||
status={apiEnabled ? 'success' : 'warning'}
|
||||
/>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
<PopoverContent
|
||||
side="top"
|
||||
align="start"
|
||||
sideOffset={4}
|
||||
alignOffset={-4}
|
||||
className="border-none bg-transparent shadow-none"
|
||||
>
|
||||
<Card apiEnabled={apiEnabled} />
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export default React.memo(ApiAccess)
|
||||
Reference in new issue
Block a user