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
+204
@@ -0,0 +1,204 @@
|
||||
import { Dialog } from '@langgenius/dify-ui/dialog'
|
||||
import { screen, waitFor, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { renderWithConsoleQuery } from '@/test/console/query-data'
|
||||
import { DatasetApiKeyDialogContent } from '../dataset-api-key-dialog-content'
|
||||
import { useDatasetApiKeyMutations } from '../use-dataset-api-key-mutations'
|
||||
|
||||
const apiMocks = vi.hoisted(() => ({
|
||||
datasetKeys: [] as Array<Record<string, unknown>>,
|
||||
knowledgeSpaces: [] as Array<{ control_space_id: string; technical_summary: { name: string } }>,
|
||||
knowledgeSpacePages: null as null | Array<
|
||||
Array<{ control_space_id: string; technical_summary: { name: string } }>
|
||||
>,
|
||||
knowledgeSpacesFailures: 0,
|
||||
knowledgeFsEnabled: false,
|
||||
createDataset: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/service/console/browser', () => ({
|
||||
consoleBrowserLink: {
|
||||
call: async (path: string[], input: unknown) => {
|
||||
switch (path.join('.')) {
|
||||
case 'datasets.apiKeys.get':
|
||||
return { data: apiMocks.datasetKeys }
|
||||
case 'datasets.apiKeys.post':
|
||||
apiMocks.createDataset(input)
|
||||
return { id: 'new-key', token: 'new-dataset-token-123', type: 'dataset', created_at: 2 }
|
||||
case 'datasets.get':
|
||||
return { data: [], page: 1, limit: 20, has_more: false, total: 0 }
|
||||
case 'knowledgeFs.spaces.get': {
|
||||
if (apiMocks.knowledgeSpacesFailures > 0) {
|
||||
apiMocks.knowledgeSpacesFailures -= 1
|
||||
throw new Error('KnowledgeFS unavailable')
|
||||
}
|
||||
const page = (input as { query: { page: number } }).query.page
|
||||
if (!apiMocks.knowledgeSpacePages)
|
||||
return { data: apiMocks.knowledgeSpaces, page, limit: 20, has_more: false }
|
||||
return {
|
||||
data: apiMocks.knowledgeSpacePages[page - 1] ?? [],
|
||||
page,
|
||||
limit: 20,
|
||||
has_more: page < apiMocks.knowledgeSpacePages.length,
|
||||
}
|
||||
}
|
||||
default:
|
||||
throw new Error(`Unexpected API call: ${path.join('.')}`)
|
||||
}
|
||||
},
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/use-timestamp', () => ({
|
||||
default: () => ({ formatTime: (value: number) => `Formatted: ${value}` }),
|
||||
}))
|
||||
|
||||
function DatasetApiKeys() {
|
||||
const mutations = useDatasetApiKeyMutations()
|
||||
return (
|
||||
<Dialog open>
|
||||
<DatasetApiKeyDialogContent canManage mutations={mutations} />
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
function renderDialog() {
|
||||
// KnowledgeFS spaces only show up in the scope picker when the workspace has KnowledgeFS.
|
||||
return renderWithConsoleQuery(<DatasetApiKeys />, {
|
||||
currentWorkspace: { id: 'workspace-1' },
|
||||
features: { enable_knowledge_fs: apiMocks.knowledgeFsEnabled },
|
||||
})
|
||||
}
|
||||
|
||||
describe('DatasetApiKeyDialogContent', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
apiMocks.datasetKeys = []
|
||||
apiMocks.knowledgeSpaces = []
|
||||
apiMocks.knowledgeSpacePages = null
|
||||
apiMocks.knowledgeSpacesFailures = 0
|
||||
apiMocks.knowledgeFsEnabled = false
|
||||
})
|
||||
|
||||
it('counts KnowledgeFS space bindings in the scope label', async () => {
|
||||
apiMocks.datasetKeys = [
|
||||
{ id: 'all', token: 'dataset-all-token-123456789', type: 'dataset', created_at: 1 },
|
||||
{
|
||||
id: 'scoped',
|
||||
token: 'dataset-scoped-token-987654321',
|
||||
type: 'dataset',
|
||||
created_at: 1,
|
||||
dataset_ids: [],
|
||||
knowledge_space_ids: ['space-1'],
|
||||
},
|
||||
]
|
||||
renderDialog()
|
||||
|
||||
expect(await screen.findByText('appApi.apiKeyModal.scopeAllDatasets')).toBeInTheDocument()
|
||||
expect(screen.getByText('appApi.apiKeyModal.scopeCount:{"count":1}')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('creates an all-access key with empty bindings for both knowledge base kinds', async () => {
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
|
||||
)
|
||||
await user.click(await screen.findByRole('button', { name: 'common.operation.create' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(apiMocks.createDataset).toHaveBeenCalledWith({
|
||||
body: { dataset_ids: [], knowledge_space_ids: [] },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('scopes a key to a KnowledgeFS space through knowledge_space_ids', async () => {
|
||||
apiMocks.knowledgeFsEnabled = true
|
||||
apiMocks.knowledgeSpaces = [
|
||||
{ control_space_id: 'space-1', technical_summary: { name: 'Space One' } },
|
||||
]
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
|
||||
)
|
||||
await user.click(await screen.findByText('appApi.apiKeyModal.scopeSpecificDatasets'))
|
||||
await user.click(screen.getByRole('combobox', { name: 'appApi.apiKeyModal.addKnowledgeBase' }))
|
||||
// KnowledgeFS spaces are listed under their own heading and picked like any dataset.
|
||||
expect(
|
||||
await screen.findByRole('group', { name: 'appApi.apiKeyModal.pickerKnowledgeSpaces' }),
|
||||
).toBeInTheDocument()
|
||||
await user.click(await screen.findByRole('option', { name: 'Space One' }))
|
||||
await user.keyboard('{Escape}')
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
|
||||
|
||||
// The space id travels in knowledge_space_ids, never in the legacy dataset_ids list.
|
||||
await waitFor(() =>
|
||||
expect(apiMocks.createDataset).toHaveBeenCalledWith({
|
||||
body: { dataset_ids: [], knowledge_space_ids: ['space-1'] },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('loads further KnowledgeFS pages so every matching space can be scoped', async () => {
|
||||
apiMocks.knowledgeFsEnabled = true
|
||||
apiMocks.knowledgeSpacePages = [
|
||||
[{ control_space_id: 'space-1', technical_summary: { name: 'Space One' } }],
|
||||
[{ control_space_id: 'space-21', technical_summary: { name: 'Space Twenty-One' } }],
|
||||
]
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
|
||||
)
|
||||
await user.click(await screen.findByText('appApi.apiKeyModal.scopeSpecificDatasets'))
|
||||
await user.click(screen.getByRole('combobox', { name: 'appApi.apiKeyModal.addKnowledgeBase' }))
|
||||
expect(await screen.findByRole('option', { name: 'Space One' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('option', { name: 'Space Twenty-One' })).not.toBeInTheDocument()
|
||||
|
||||
await user.click(
|
||||
screen.getByRole('button', { name: 'appApi.apiKeyModal.loadMoreKnowledgeSpaces' }),
|
||||
)
|
||||
await user.click(await screen.findByRole('option', { name: 'Space Twenty-One' }))
|
||||
expect(
|
||||
screen.queryByRole('button', { name: 'appApi.apiKeyModal.loadMoreKnowledgeSpaces' }),
|
||||
).not.toBeInTheDocument()
|
||||
await user.keyboard('{Escape}')
|
||||
await user.click(screen.getByRole('button', { name: 'common.operation.create' }))
|
||||
|
||||
await waitFor(() =>
|
||||
expect(apiMocks.createDataset).toHaveBeenCalledWith({
|
||||
body: { dataset_ids: [], knowledge_space_ids: ['space-21'] },
|
||||
}),
|
||||
)
|
||||
})
|
||||
|
||||
it('shows a retryable error instead of an empty result when the KnowledgeFS lookup fails', async () => {
|
||||
apiMocks.knowledgeFsEnabled = true
|
||||
apiMocks.knowledgeSpacesFailures = 1
|
||||
apiMocks.knowledgeSpaces = [
|
||||
{ control_space_id: 'space-1', technical_summary: { name: 'Space One' } },
|
||||
]
|
||||
const user = userEvent.setup()
|
||||
renderDialog()
|
||||
|
||||
await user.click(
|
||||
await screen.findByRole('button', { name: 'appApi.apiKeyModal.createNewSecretKey' }),
|
||||
)
|
||||
await user.click(await screen.findByText('appApi.apiKeyModal.scopeSpecificDatasets'))
|
||||
await user.click(screen.getByRole('combobox', { name: 'appApi.apiKeyModal.addKnowledgeBase' }))
|
||||
|
||||
const alert = await screen.findByRole('alert')
|
||||
expect(alert).toHaveTextContent('appApi.apiKeyModal.loadKnowledgeSpacesError')
|
||||
expect(screen.queryByText('common.noData')).not.toBeInTheDocument()
|
||||
|
||||
await user.click(within(alert).getByRole('button', { name: 'common.operation.retry' }))
|
||||
|
||||
expect(await screen.findByRole('option', { name: 'Space One' })).toBeInTheDocument()
|
||||
expect(screen.queryByRole('alert')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,116 @@
|
||||
'use client'
|
||||
import type { ButtonProps } from '@langgenius/dify-ui/button'
|
||||
import type { DialogContentProps } from '@langgenius/dify-ui/dialog'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import {
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import { QueryErrorResetBoundary } from '@tanstack/react-query'
|
||||
import { Suspense, useId } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import ErrorBoundary from '@/app/components/base/error-boundary'
|
||||
import { SkeletonContainer, SkeletonRectangle, SkeletonRow } from '@/app/components/base/skeleton'
|
||||
|
||||
type ApiKeyDialogContentProps = Pick<DialogContentProps, 'children' | 'finalFocus'> & {
|
||||
limitDescription?: string
|
||||
closeDisabled?: boolean
|
||||
}
|
||||
|
||||
export function ApiKeyDialogContent({
|
||||
limitDescription,
|
||||
closeDisabled,
|
||||
children,
|
||||
finalFocus,
|
||||
}: ApiKeyDialogContentProps) {
|
||||
const { t } = useTranslation(['appApi', 'common'])
|
||||
return (
|
||||
<DialogContent finalFocus={finalFocus} className="w-200">
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t(($) => $['apiKeyModal.apiSecretKey'])}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(($) => $['apiKeyModal.apiSecretKeyTips'])}
|
||||
{limitDescription && <span className="block">{limitDescription}</span>}
|
||||
</DialogDescription>
|
||||
<DialogHeaderCloseButton
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
disabled={closeDisabled}
|
||||
/>
|
||||
</DialogHeader>
|
||||
<QueryErrorResetBoundary>
|
||||
{({ reset }) => (
|
||||
<ErrorBoundary
|
||||
onReset={reset}
|
||||
fallback={(_error, retry) => (
|
||||
<div className="flex items-center gap-2 border-y border-divider-subtle px-6 py-4">
|
||||
<p role="status">{t(($) => $['api.actionFailed'], { ns: 'common' })}</p>
|
||||
<Button variant="secondary" size="small" onClick={retry}>
|
||||
{t(($) => $['operation.retry'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
>
|
||||
<Suspense
|
||||
fallback={
|
||||
<div role="status" className="border-y border-divider-subtle px-6 py-4">
|
||||
<span className="sr-only">{t(($) => $.loading, { ns: 'common' })}</span>
|
||||
<SkeletonContainer aria-hidden>
|
||||
{[0, 1, 2].map((row) => (
|
||||
<SkeletonRow key={row} className="gap-6 py-2">
|
||||
<SkeletonRectangle className="w-1/3" />
|
||||
<SkeletonRectangle className="w-1/4" />
|
||||
<SkeletonRectangle className="w-1/4" />
|
||||
</SkeletonRow>
|
||||
))}
|
||||
</SkeletonContainer>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
{children}
|
||||
</Suspense>
|
||||
</ErrorBoundary>
|
||||
)}
|
||||
</QueryErrorResetBoundary>
|
||||
</DialogContent>
|
||||
)
|
||||
}
|
||||
|
||||
export const API_KEY_LIMIT = 10
|
||||
|
||||
type ApiKeyCreateActionProps = Pick<
|
||||
ButtonProps,
|
||||
'ref' | 'disabled' | 'loading' | 'onClick' | 'focusableWhenDisabled'
|
||||
> & {
|
||||
atLimit?: boolean
|
||||
}
|
||||
|
||||
export function ApiKeyCreateAction({
|
||||
atLimit = false,
|
||||
disabled,
|
||||
...props
|
||||
}: ApiKeyCreateActionProps) {
|
||||
const { t } = useTranslation(['appApi'])
|
||||
const descriptionId = useId()
|
||||
|
||||
return (
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-x-3 gap-y-2 px-6 py-4">
|
||||
<Button
|
||||
{...props}
|
||||
className="shrink-0"
|
||||
disabled={disabled || atLimit}
|
||||
aria-describedby={atLimit ? descriptionId : undefined}
|
||||
>
|
||||
<span aria-hidden className="i-ri-add-line size-4 shrink-0" />
|
||||
{t(($) => $['apiKeyModal.createNewSecretKey'])}
|
||||
</Button>
|
||||
{atLimit && (
|
||||
<p id={descriptionId} className="min-w-40 flex-1 system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.keyLimitReached'])}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
'use client'
|
||||
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
|
||||
import type { ComponentProps, ReactNode, RefObject } from 'react'
|
||||
import type { ApiKeyDeleteTarget } from './api-key-table'
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogCancelButton,
|
||||
AlertDialogConfirmButton,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@langgenius/dify-ui/alert-dialog'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { ApiKeyTable } from './api-key-table'
|
||||
import { maskApiKey } from './mask-api-key'
|
||||
|
||||
type ApiKeyListContentProps = ComponentProps<typeof ApiKeyTable> & {
|
||||
children: ReactNode
|
||||
isDeleting: boolean
|
||||
isFetching: boolean
|
||||
isError: boolean
|
||||
onRetry: () => void
|
||||
onDelete: (keyId: string, onSuccess: () => void) => void
|
||||
finalFocus: RefObject<HTMLButtonElement | null>
|
||||
}
|
||||
|
||||
export function ApiKeyListContent({
|
||||
apiKeys,
|
||||
canManage,
|
||||
showScope,
|
||||
allowCopy,
|
||||
children,
|
||||
isDeleting,
|
||||
isFetching,
|
||||
isError,
|
||||
onRetry,
|
||||
onDelete,
|
||||
finalFocus,
|
||||
}: ApiKeyListContentProps) {
|
||||
const { t } = useTranslation(['appApi', 'common'])
|
||||
const deleteActionsRef = useRef<AlertDialogActions>(null)
|
||||
const deleteSucceededRef = useRef(false)
|
||||
|
||||
const handleDelete = (keyId: string | undefined) => {
|
||||
if (!keyId || !canManage || isDeleting) return
|
||||
onDelete(keyId, () => {
|
||||
deleteSucceededRef.current = true
|
||||
deleteActionsRef.current?.close()
|
||||
})
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<span role="status" className="sr-only">
|
||||
{isDeleting || isFetching ? t(($) => $.loading, { ns: 'common' }) : ''}
|
||||
</span>
|
||||
{isError && (
|
||||
<div className="flex items-center gap-2 px-6 py-4">
|
||||
<p role="status">{t(($) => $['api.actionFailed'], { ns: 'common' })}</p>
|
||||
<Button variant="secondary" size="small" onClick={onRetry}>
|
||||
{t(($) => $['operation.retry'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
<AlertDialog<ApiKeyDeleteTarget>
|
||||
actionsRef={deleteActionsRef}
|
||||
onOpenChange={(nextOpen, details) => {
|
||||
if (nextOpen) deleteSucceededRef.current = false
|
||||
if (!nextOpen && isDeleting && details.reason !== 'imperative-action') {
|
||||
details.cancel()
|
||||
}
|
||||
}}
|
||||
>
|
||||
{({ payload }) => (
|
||||
<>
|
||||
<ApiKeyTable
|
||||
apiKeys={apiKeys}
|
||||
canManage={canManage}
|
||||
showScope={showScope}
|
||||
allowCopy={allowCopy}
|
||||
/>
|
||||
<AlertDialogContent
|
||||
backdropProps={{ forceRender: true }}
|
||||
finalFocus={() => (deleteSucceededRef.current ? finalFocus.current : true)}
|
||||
>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{t(($) => $['actionMsg.deleteConfirmTitle'], { ns: 'appApi' })}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
<span className="mb-2 block font-mono" translate="no">
|
||||
{payload && maskApiKey(payload.token)}
|
||||
</span>
|
||||
{t(($) => $['actionMsg.deleteConfirmTips'], { ns: 'appApi' })}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancelButton disabled={isDeleting}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</AlertDialogCancelButton>
|
||||
<AlertDialogConfirmButton
|
||||
loading={isDeleting}
|
||||
disabled={!canManage}
|
||||
onClick={() => handleDelete(payload?.id)}
|
||||
>
|
||||
{t(($) => $['operation.delete'], { ns: 'common' })}
|
||||
</AlertDialogConfirmButton>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</>
|
||||
)}
|
||||
</AlertDialog>
|
||||
{children}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { ApiKeyItem } from '@dify/contracts/api/console/apps/types.gen'
|
||||
import type { EnvironmentApiKey } from '@dify/contracts/enterprise-app-deploy/types.gen'
|
||||
import { AlertDialogTrigger } from '@langgenius/dify-ui/alert-dialog'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { CopyFeedback } from '@/app/components/base/copy-feedback'
|
||||
import useTimestamp from '@/hooks/use-timestamp'
|
||||
import { maskApiKey } from './mask-api-key'
|
||||
|
||||
export type ApiKeyDeleteTarget = Pick<ApiKeyItem, 'id' | 'token'>
|
||||
|
||||
type ApiKeyTableProps = {
|
||||
apiKeys: Array<ApiKeyItem | EnvironmentApiKey>
|
||||
canManage: boolean
|
||||
// Dataset keys carry a knowledge-base scope; enable the SCOPE column to surface it.
|
||||
showScope?: boolean
|
||||
allowCopy?: boolean
|
||||
}
|
||||
|
||||
export function ApiKeyTable({
|
||||
apiKeys,
|
||||
canManage,
|
||||
showScope = false,
|
||||
allowCopy = false,
|
||||
}: ApiKeyTableProps) {
|
||||
const { t } = useTranslation(['appApi', 'common', 'time'])
|
||||
const { formatTime } = useTimestamp()
|
||||
|
||||
// Only dataset keys expose bound knowledge bases (legacy dataset_ids plus KnowledgeFS
|
||||
// knowledge_space_ids); both empty/absent means the key can access every knowledge base
|
||||
// in the workspace.
|
||||
const scopeLabel = (apiKey: ApiKeyItem | EnvironmentApiKey) => {
|
||||
const datasetIds = 'dataset_ids' in apiKey ? apiKey.dataset_ids : undefined
|
||||
const knowledgeSpaceIds =
|
||||
'knowledge_space_ids' in apiKey ? apiKey.knowledge_space_ids : undefined
|
||||
const count = (datasetIds?.length ?? 0) + (knowledgeSpaceIds?.length ?? 0)
|
||||
if (!count) return t(($) => $['apiKeyModal.scopeAllDatasets'], { ns: 'appApi' })
|
||||
return t(($) => $['apiKeyModal.scopeCount'], { ns: 'appApi', count })
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-6 min-h-0 min-w-0 overflow-auto border-y border-divider-subtle">
|
||||
<table className="w-full min-w-180 table-fixed text-start system-sm-regular text-text-secondary">
|
||||
<caption className="sr-only">
|
||||
{t(($) => $['apiKeyModal.apiSecretKey'], { ns: 'appApi' })}
|
||||
</caption>
|
||||
<thead className="sticky top-0 bg-components-panel-bg system-xs-semibold-uppercase text-text-tertiary">
|
||||
<tr className="border-b border-divider-regular">
|
||||
<th className="w-60 px-3 py-2 text-start" scope="col">
|
||||
{t(($) => $['apiKeyModal.secretKey'], { ns: 'appApi' })}
|
||||
</th>
|
||||
{showScope && (
|
||||
<th className="w-28 px-3 py-2 text-start" scope="col">
|
||||
{t(($) => $['apiKeyModal.scope'], { ns: 'appApi' })}
|
||||
</th>
|
||||
)}
|
||||
<th className="w-40 px-3 py-2 text-start" scope="col">
|
||||
{t(($) => $['apiKeyModal.created'], { ns: 'appApi' })}
|
||||
</th>
|
||||
<th className="w-40 px-3 py-2 text-start" scope="col">
|
||||
{t(($) => $['apiKeyModal.lastUsed'], { ns: 'appApi' })}
|
||||
</th>
|
||||
<th className="w-28 px-3 py-2 text-start" scope="col">
|
||||
<span className="sr-only">
|
||||
{t(($) => $['apiKeyModal.actions'], { ns: 'appApi' })}
|
||||
</span>
|
||||
</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{apiKeys.length === 0 && (
|
||||
<tr>
|
||||
<td colSpan={showScope ? 5 : 4} className="h-20 px-6 text-center text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.emptyState'], { ns: 'appApi' })}
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{apiKeys.map((apiKey) => (
|
||||
<tr className="border-b border-divider-regular last:border-b-0" key={apiKey.id}>
|
||||
<td className="truncate px-3 py-2 font-mono">{maskApiKey(apiKey.token)}</td>
|
||||
{showScope && <td className="truncate px-3 py-2">{scopeLabel(apiKey)}</td>}
|
||||
<td className="truncate px-3 py-2">
|
||||
{apiKey.created_at == null
|
||||
? '—'
|
||||
: formatTime(
|
||||
apiKey.created_at,
|
||||
t(($) => $['dateFormats.withSeconds'], { ns: 'time' }) as string,
|
||||
)}
|
||||
</td>
|
||||
<td className="truncate px-3 py-2">
|
||||
{apiKey.last_used_at
|
||||
? formatTime(
|
||||
Number(apiKey.last_used_at),
|
||||
t(($) => $['dateFormats.withSeconds'], { ns: 'time' }) as string,
|
||||
)
|
||||
: t(($) => $.never, { ns: 'appApi' })}
|
||||
</td>
|
||||
<td className="px-3 py-1">
|
||||
<div className="flex justify-end gap-1">
|
||||
{allowCopy && <CopyFeedback content={apiKey.token} />}
|
||||
{canManage && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger
|
||||
render={
|
||||
<AlertDialogTrigger
|
||||
id={apiKey.id}
|
||||
payload={apiKey}
|
||||
render={
|
||||
<IconButton
|
||||
tone="destructive"
|
||||
aria-label={`${t(($) => $['operation.delete'], { ns: 'common' })} ${maskApiKey(apiKey.token)}`}
|
||||
>
|
||||
<span aria-hidden className="i-ri-delete-bin-line size-4" />
|
||||
</IconButton>
|
||||
}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
<TooltipContent>
|
||||
{t(($) => $['operation.delete'], { ns: 'common' })}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
'use client'
|
||||
import type { DialogContentProps, DialogProps } from '@langgenius/dify-ui/dialog'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogBody,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import { InputGroup, InputGroupAddon, InputGroupInput } from '@langgenius/dify-ui/input-group'
|
||||
import { useRef } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { CopyFeedback } from '@/app/components/base/copy-feedback'
|
||||
|
||||
type CreatedApiKeyDialogProps = Required<Pick<DialogProps, 'open' | 'onOpenChange'>> &
|
||||
Pick<DialogContentProps, 'finalFocus'> & {
|
||||
value: string | undefined
|
||||
revealOnce?: boolean
|
||||
}
|
||||
|
||||
export function CreatedApiKeyDialog({
|
||||
open,
|
||||
onOpenChange,
|
||||
value,
|
||||
finalFocus,
|
||||
revealOnce = false,
|
||||
}: CreatedApiKeyDialogProps) {
|
||||
const { t } = useTranslation(['appApi'])
|
||||
const copyButtonRef = useRef<HTMLButtonElement>(null)
|
||||
|
||||
return (
|
||||
<Dialog open={open} disablePointerDismissal onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
initialFocus={copyButtonRef}
|
||||
finalFocus={finalFocus}
|
||||
backdropProps={{ forceRender: true }}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t(($) => $['apiKeyModal.createdTitle'], { ns: 'appApi' })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{revealOnce
|
||||
? t(($) => $['apiKeyModal.revealOnceTips'], { ns: 'appApi' })
|
||||
: t(($) => $['apiKeyModal.generateTips'], { ns: 'appApi' })}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<DialogBody>
|
||||
<InputGroup>
|
||||
<InputGroupInput
|
||||
aria-label={t(($) => $['apiKeyModal.secretKey'], { ns: 'appApi' })}
|
||||
autoComplete="off"
|
||||
className="font-mono"
|
||||
readOnly
|
||||
spellCheck={false}
|
||||
value={value ?? ''}
|
||||
/>
|
||||
<InputGroupAddon align="inline-end" className="pe-1">
|
||||
<CopyFeedback ref={copyButtonRef} content={value ?? ''} />
|
||||
</InputGroupAddon>
|
||||
</InputGroup>
|
||||
</DialogBody>
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="primary" />}>
|
||||
{t(($) => $['apiKeyModal.saved'], { ns: 'appApi' })}
|
||||
</DialogClose>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
'use client'
|
||||
|
||||
import type { DialogContentProps } from '@langgenius/dify-ui/dialog'
|
||||
import type { ComponentProps } from 'react'
|
||||
import type { DatasetApiKeyScopeSelection } from './dataset-scope-dialog'
|
||||
import type { useDatasetApiKeyMutations } from './use-dataset-api-key-mutations'
|
||||
import { useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
import { API_KEY_LIMIT, ApiKeyCreateAction, ApiKeyDialogContent } from './api-key-dialog-content'
|
||||
import { ApiKeyListContent } from './api-key-list-content'
|
||||
import { CreatedApiKeyDialog } from './created-api-key-dialog'
|
||||
import { DatasetScopeDialog } from './dataset-scope-dialog'
|
||||
|
||||
type DatasetApiKeyDialogContentProps = Pick<DialogContentProps, 'finalFocus'> & {
|
||||
canManage: boolean
|
||||
mutations: ReturnType<typeof useDatasetApiKeyMutations>
|
||||
}
|
||||
|
||||
// Workspace dataset API keys. The caller owns the Dialog root so it can keep its own trigger
|
||||
// and cancel closing while `mutations.pending`.
|
||||
export function DatasetApiKeyDialogContent({
|
||||
canManage,
|
||||
mutations: { createKey, deleteKey, pending },
|
||||
finalFocus,
|
||||
}: DatasetApiKeyDialogContentProps) {
|
||||
const { t } = useTranslation(['appApi'])
|
||||
return (
|
||||
<ApiKeyDialogContent
|
||||
limitDescription={t(($) => $['apiKeyModal.workspaceKeyLimit'], {
|
||||
ns: 'appApi',
|
||||
limit: API_KEY_LIMIT,
|
||||
})}
|
||||
closeDisabled={pending}
|
||||
finalFocus={finalFocus}
|
||||
>
|
||||
<DatasetApiKeys
|
||||
canManage={canManage}
|
||||
isCreating={createKey.isPending}
|
||||
isDeleting={deleteKey.isPending}
|
||||
createdKey={createKey.data?.token}
|
||||
onCreate={({ datasetIds, knowledgeSpaceIds }, onSuccess) => {
|
||||
if (!canManage || pending) return
|
||||
// Legacy datasets and KnowledgeFS spaces are bound separately; both empty = all access.
|
||||
createKey.mutate(
|
||||
{ body: { dataset_ids: datasetIds, knowledge_space_ids: knowledgeSpaceIds } },
|
||||
{ onSuccess },
|
||||
)
|
||||
}}
|
||||
onDelete={(keyId, onSuccess) => {
|
||||
if (!canManage || pending) return
|
||||
deleteKey.mutate({ params: { api_key_id: keyId } }, { onSuccess })
|
||||
}}
|
||||
/>
|
||||
</ApiKeyDialogContent>
|
||||
)
|
||||
}
|
||||
|
||||
type DatasetApiKeysProps = Pick<
|
||||
ComponentProps<typeof ApiKeyListContent>,
|
||||
'canManage' | 'isDeleting' | 'onDelete'
|
||||
> & {
|
||||
isCreating: boolean
|
||||
createdKey: string | undefined
|
||||
onCreate: (selection: DatasetApiKeyScopeSelection, onSuccess: () => void) => void
|
||||
}
|
||||
|
||||
function DatasetApiKeys({
|
||||
canManage,
|
||||
isCreating,
|
||||
isDeleting,
|
||||
createdKey,
|
||||
onCreate,
|
||||
onDelete,
|
||||
}: DatasetApiKeysProps) {
|
||||
const keys = useSuspenseQuery(consoleQuery.datasets.apiKeys.get.queryOptions())
|
||||
const [scopeOpen, setScopeOpen] = useState(false)
|
||||
const [createdOpen, setCreatedOpen] = useState(false)
|
||||
const createButtonRef = useRef<HTMLButtonElement>(null)
|
||||
const atLimit = keys.data.data.length >= API_KEY_LIMIT
|
||||
return (
|
||||
<ApiKeyListContent
|
||||
apiKeys={keys.data.data}
|
||||
canManage={canManage}
|
||||
showScope
|
||||
isDeleting={isDeleting}
|
||||
isFetching={keys.isFetching}
|
||||
isError={keys.isError}
|
||||
onRetry={() => {
|
||||
void keys.refetch()
|
||||
}}
|
||||
onDelete={onDelete}
|
||||
finalFocus={createButtonRef}
|
||||
>
|
||||
<ApiKeyCreateAction
|
||||
ref={createButtonRef}
|
||||
atLimit={atLimit}
|
||||
disabled={!canManage}
|
||||
focusableWhenDisabled={canManage}
|
||||
loading={isCreating}
|
||||
onClick={() => setScopeOpen(true)}
|
||||
/>
|
||||
<CreatedApiKeyDialog
|
||||
open={createdOpen}
|
||||
onOpenChange={setCreatedOpen}
|
||||
value={createdKey}
|
||||
revealOnce
|
||||
finalFocus={createButtonRef}
|
||||
/>
|
||||
<DatasetScopeDialog
|
||||
open={scopeOpen}
|
||||
onOpenChange={setScopeOpen}
|
||||
isCreating={isCreating}
|
||||
createDisabled={!canManage || atLimit}
|
||||
finalFocus={() => (createdOpen ? false : createButtonRef.current)}
|
||||
onConfirm={(selection) =>
|
||||
onCreate(selection, () => {
|
||||
setCreatedOpen(true)
|
||||
setScopeOpen(false)
|
||||
})
|
||||
}
|
||||
/>
|
||||
</ApiKeyListContent>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,474 @@
|
||||
'use client'
|
||||
|
||||
import type { DialogContentProps, DialogProps } from '@langgenius/dify-ui/dialog'
|
||||
import type { UseInfiniteQueryResult } from '@tanstack/react-query'
|
||||
import { Button } from '@langgenius/dify-ui/button'
|
||||
import { Checkbox } from '@langgenius/dify-ui/checkbox'
|
||||
import {
|
||||
Combobox,
|
||||
ComboboxCollection,
|
||||
ComboboxEmpty,
|
||||
ComboboxGroup,
|
||||
ComboboxGroupLabel,
|
||||
ComboboxInput,
|
||||
ComboboxInputGroup,
|
||||
ComboboxItem,
|
||||
ComboboxList,
|
||||
ComboboxPopup,
|
||||
ComboboxPortal,
|
||||
ComboboxPositioner,
|
||||
ComboboxStatus,
|
||||
ComboboxTrigger,
|
||||
} from '@langgenius/dify-ui/combobox'
|
||||
import {
|
||||
Dialog,
|
||||
DialogBody,
|
||||
DialogClose,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogHeaderCloseButton,
|
||||
DialogTitle,
|
||||
} from '@langgenius/dify-ui/dialog'
|
||||
import { IconButton } from '@langgenius/dify-ui/icon-button'
|
||||
import { Radio, RadioGroup } from '@langgenius/dify-ui/radio-group'
|
||||
import { useInfiniteQuery, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { useId, useMemo, useRef, useState } from 'react'
|
||||
import { useTranslation } from 'react-i18next'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
|
||||
type Scope = 'all' | 'specific'
|
||||
// Legacy knowledge bases (datasets) and KnowledgeFS spaces live in different tables, so
|
||||
// a selection keeps track of which kind each entry is and reports the ids separately.
|
||||
type KnowledgeBaseKind = 'dataset' | 'knowledge_space'
|
||||
type SelectedKb = { id: string; name: string; kind: KnowledgeBaseKind }
|
||||
|
||||
export type DatasetApiKeyScopeSelection = {
|
||||
datasetIds: string[]
|
||||
knowledgeSpaceIds: string[]
|
||||
}
|
||||
|
||||
const PICKER_PAGE_SIZE = 20
|
||||
|
||||
type DatasetScopeDialogProps = Required<Pick<DialogProps, 'open' | 'onOpenChange'>> &
|
||||
Pick<DialogContentProps, 'finalFocus'> & {
|
||||
isCreating: boolean
|
||||
createDisabled: boolean
|
||||
// Emits the knowledge-base ids to scope the new key to, split by kind. Both lists empty
|
||||
// means the key can access every knowledge base in the workspace (the "all" scope).
|
||||
onConfirm: (selection: DatasetApiKeyScopeSelection) => void
|
||||
}
|
||||
|
||||
export function DatasetScopeDialog({
|
||||
open,
|
||||
finalFocus,
|
||||
onOpenChange,
|
||||
...props
|
||||
}: DatasetScopeDialogProps) {
|
||||
return (
|
||||
<Dialog
|
||||
open={open}
|
||||
onOpenChange={(nextOpen, details) => {
|
||||
if (!nextOpen && props.isCreating) details.cancel()
|
||||
else onOpenChange(nextOpen, details)
|
||||
}}
|
||||
>
|
||||
<DialogContent
|
||||
finalFocus={finalFocus}
|
||||
backdropProps={{ forceRender: true }}
|
||||
className="w-140"
|
||||
>
|
||||
<DatasetScopeContent {...props} />
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
type PickerPageQuery = Pick<
|
||||
UseInfiniteQueryResult,
|
||||
| 'fetchNextPage'
|
||||
| 'hasNextPage'
|
||||
| 'isError'
|
||||
| 'isFetchNextPageError'
|
||||
| 'isFetchingNextPage'
|
||||
| 'isRefetching'
|
||||
| 'refetch'
|
||||
>
|
||||
|
||||
// Each picker source pages independently: a failed source shows its own retry, and a source with
|
||||
// more matches offers the next page so every match stays selectable.
|
||||
function PickerPagination({
|
||||
query,
|
||||
errorLabel,
|
||||
loadMoreLabel,
|
||||
onSettled,
|
||||
}: {
|
||||
query: PickerPageQuery
|
||||
errorLabel: string
|
||||
loadMoreLabel: string
|
||||
// Returns focus to the picker input once the pagination control may have unmounted.
|
||||
onSettled: () => void
|
||||
}) {
|
||||
const { t } = useTranslation(['common'])
|
||||
|
||||
if (query.isError) {
|
||||
const retry = async () => {
|
||||
await (query.isFetchNextPageError ? query.fetchNextPage() : query.refetch())
|
||||
onSettled()
|
||||
}
|
||||
return (
|
||||
<div
|
||||
role="alert"
|
||||
className="flex items-center justify-between gap-2 px-3 py-2 system-xs-regular text-text-destructive"
|
||||
>
|
||||
<span className="min-w-0">{errorLabel}</span>
|
||||
<Button
|
||||
size="small"
|
||||
className="shrink-0"
|
||||
loading={query.isRefetching || query.isFetchingNextPage}
|
||||
onClick={() => void retry()}
|
||||
>
|
||||
{t(($) => $['operation.retry'], { ns: 'common' })}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
if (!query.hasNextPage) return null
|
||||
|
||||
return (
|
||||
<div className="px-1 pb-1">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="small"
|
||||
className="w-full"
|
||||
loading={query.isFetchingNextPage}
|
||||
disabled={query.isFetchingNextPage}
|
||||
onClick={async () => {
|
||||
await query.fetchNextPage()
|
||||
onSettled()
|
||||
}}
|
||||
>
|
||||
{loadMoreLabel}
|
||||
</Button>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function DatasetScopeContent({
|
||||
isCreating,
|
||||
createDisabled,
|
||||
onConfirm,
|
||||
}: Omit<DatasetScopeDialogProps, 'open' | 'finalFocus' | 'onOpenChange'>) {
|
||||
const { t } = useTranslation(['appApi', 'common'])
|
||||
const scopeId = useId()
|
||||
const { data: knowledgeFsEnabled } = useSuspenseQuery(
|
||||
consoleQuery.features.get.queryOptions({
|
||||
select: (features) => features.enable_knowledge_fs,
|
||||
}),
|
||||
)
|
||||
const [scope, setScope] = useState<Scope>('all')
|
||||
const [selected, setSelected] = useState<SelectedKb[]>([])
|
||||
const [keyword, setKeyword] = useState('')
|
||||
const pickerInputRef = useRef<HTMLInputElement>(null)
|
||||
const focusPickerInput = () => pickerInputRef.current?.focus()
|
||||
|
||||
const datasetsQuery = useInfiniteQuery(
|
||||
consoleQuery.datasets.get.infiniteOptions({
|
||||
input: (page: number) => ({ query: { page, ...(keyword ? { keyword } : {}) } }),
|
||||
getNextPageParam: (lastPage) => (lastPage.has_more ? lastPage.page + 1 : undefined),
|
||||
initialPageParam: 1,
|
||||
enabled: scope === 'specific',
|
||||
staleTime: 0,
|
||||
refetchOnMount: 'always',
|
||||
}),
|
||||
)
|
||||
const datasets = useMemo<SelectedKb[]>(
|
||||
() =>
|
||||
(datasetsQuery.data?.pages ?? []).flatMap((page) =>
|
||||
page.data.map(({ id, name }) => ({ id, name, kind: 'dataset' })),
|
||||
),
|
||||
[datasetsQuery.data],
|
||||
)
|
||||
// KnowledgeFS spaces come from their own list endpoint, which only exists when the
|
||||
// workspace has KnowledgeFS enabled.
|
||||
const knowledgeSpacesQuery = useInfiniteQuery({
|
||||
...consoleQuery.knowledgeFs.spaces.get.infiniteOptions({
|
||||
input: (pageParam) => ({
|
||||
query: {
|
||||
limit: PICKER_PAGE_SIZE,
|
||||
page: pageParam,
|
||||
...(keyword ? { query: keyword } : {}),
|
||||
},
|
||||
}),
|
||||
getNextPageParam: (lastPage) => (lastPage.has_more ? lastPage.page + 1 : undefined),
|
||||
initialPageParam: 1,
|
||||
}),
|
||||
enabled: scope === 'specific' && knowledgeFsEnabled,
|
||||
})
|
||||
const knowledgeSpaces = useMemo<SelectedKb[]>(
|
||||
() =>
|
||||
(knowledgeSpacesQuery.data?.pages ?? [])
|
||||
.flatMap((page) => page.data)
|
||||
.map((space) => ({
|
||||
kind: 'knowledge_space',
|
||||
id: space.control_space_id,
|
||||
name: space.technical_summary?.name ?? space.control_space_id,
|
||||
})),
|
||||
[knowledgeSpacesQuery.data],
|
||||
)
|
||||
const pickerItems = useMemo(() => [...knowledgeSpaces, ...datasets], [knowledgeSpaces, datasets])
|
||||
const isLoading =
|
||||
datasetsQuery.isLoading || (knowledgeFsEnabled && knowledgeSpacesQuery.isLoading)
|
||||
// "No data" is only true once every enabled lookup succeeded; a failed lookup gets its own
|
||||
// error state so it is not mistaken for an empty search.
|
||||
const hasLookupError =
|
||||
datasetsQuery.isError || (knowledgeFsEnabled && knowledgeSpacesQuery.isError)
|
||||
const selectedIds = useMemo(() => new Set(selected.map((kb) => kb.id)), [selected])
|
||||
const addLabel = t(($) => $['apiKeyModal.addKnowledgeBase'], { ns: 'appApi' })
|
||||
const searchLabel = t(($) => $['apiKeyModal.searchKnowledgeBases'], { ns: 'appApi' })
|
||||
|
||||
const removeKb = (id: string) => setSelected((prev) => prev.filter((kb) => kb.id !== id))
|
||||
|
||||
const canCreate = !createDisabled && (scope === 'all' || selected.length > 0)
|
||||
|
||||
const handleConfirm = () => {
|
||||
if (!canCreate || isCreating) return
|
||||
if (scope !== 'specific') {
|
||||
onConfirm({ datasetIds: [], knowledgeSpaceIds: [] })
|
||||
return
|
||||
}
|
||||
onConfirm({
|
||||
datasetIds: selected.filter((kb) => kb.kind === 'dataset').map((kb) => kb.id),
|
||||
knowledgeSpaceIds: selected.filter((kb) => kb.kind === 'knowledge_space').map((kb) => kb.id),
|
||||
})
|
||||
}
|
||||
|
||||
const renderPickerOption = (kb: SelectedKb) => (
|
||||
<ComboboxItem<SelectedKb> key={kb.id} value={kb} className="grid-cols-[auto_1fr]">
|
||||
{/* Visual only: the option owns the click target and the selected state. */}
|
||||
<span aria-hidden inert className="flex">
|
||||
<Checkbox checked={selectedIds.has(kb.id)} />
|
||||
</span>
|
||||
<span className="min-w-0 truncate system-sm-regular text-text-secondary">{kb.name}</span>
|
||||
</ComboboxItem>
|
||||
)
|
||||
|
||||
return (
|
||||
<form
|
||||
className="contents"
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault()
|
||||
handleConfirm()
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{t(($) => $['apiKeyModal.addTitle'], { ns: 'appApi' })}</DialogTitle>
|
||||
<DialogDescription>
|
||||
{t(($) => $['apiKeyModal.addSubtitle'], { ns: 'appApi' })}
|
||||
</DialogDescription>
|
||||
<DialogHeaderCloseButton
|
||||
aria-label={t(($) => $['operation.close'], { ns: 'common' })}
|
||||
disabled={isCreating}
|
||||
/>
|
||||
</DialogHeader>
|
||||
|
||||
<DialogBody className="flex flex-col gap-3">
|
||||
<div id={scopeId} className="system-sm-semibold text-text-secondary">
|
||||
{t(($) => $['apiKeyModal.knowledgeBaseAccess'], { ns: 'appApi' })}
|
||||
</div>
|
||||
<RadioGroup<Scope>
|
||||
name="knowledgeBaseScope"
|
||||
aria-labelledby={scopeId}
|
||||
disabled={isCreating}
|
||||
value={scope}
|
||||
onValueChange={setScope}
|
||||
>
|
||||
<div className="flex flex-col gap-3">
|
||||
<label htmlFor={`${scopeId}-all`} className="flex cursor-pointer items-start gap-2">
|
||||
<Radio id={`${scopeId}-all`} value="all" className="mt-0.5" />
|
||||
<div className="flex flex-col">
|
||||
<span className="system-sm-medium text-text-secondary">
|
||||
{t(($) => $['apiKeyModal.scopeAllDatasets'], { ns: 'appApi' })}
|
||||
</span>
|
||||
<span className="system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.scopeAllDatasetsTip'], { ns: 'appApi' })}
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
<label
|
||||
htmlFor={`${scopeId}-specific`}
|
||||
className="flex cursor-pointer items-start gap-2"
|
||||
>
|
||||
<Radio id={`${scopeId}-specific`} value="specific" className="mt-0.5" />
|
||||
<div className="flex flex-col">
|
||||
<span className="system-sm-medium text-text-secondary">
|
||||
{t(($) => $['apiKeyModal.scopeSpecificDatasets'], { ns: 'appApi' })}
|
||||
</span>
|
||||
<span className="system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.scopeSpecificDatasetsTip'], { ns: 'appApi' })}
|
||||
</span>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
|
||||
{scope === 'specific' && (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="system-sm-semibold text-text-secondary">
|
||||
{t(($) => $['apiKeyModal.selectedKnowledgeBases'], { ns: 'appApi' })}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2 rounded-lg border-[0.5px] border-divider-subtle bg-components-panel-bg p-3">
|
||||
{selected.length === 0 ? (
|
||||
<div className="py-0.5 system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.noKnowledgeBasesSelected'], { ns: 'appApi' })}
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="system-xs-regular text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.selectedKnowledgeBasesCount'], {
|
||||
ns: 'appApi',
|
||||
count: selected.length,
|
||||
})}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1.5">
|
||||
{selected.map((kb) => (
|
||||
<div
|
||||
key={kb.id}
|
||||
className="flex items-center gap-1 rounded-md border-[0.5px] border-components-panel-border bg-components-panel-bg px-2 py-1"
|
||||
>
|
||||
<span className="max-w-40 truncate system-xs-medium text-text-secondary">
|
||||
{kb.name}
|
||||
</span>
|
||||
{kb.kind === 'knowledge_space' && (
|
||||
<span className="shrink-0 rounded-sm bg-components-badge-bg-gray-soft px-1 system-2xs-medium-uppercase text-text-tertiary">
|
||||
{t(($) => $['apiKeyModal.knowledgeSpaceBadge'], { ns: 'appApi' })}
|
||||
</span>
|
||||
)}
|
||||
<IconButton
|
||||
size="xs"
|
||||
disabled={isCreating}
|
||||
aria-label={`${t(($) => $['operation.remove'], { ns: 'common' })} ${kb.name}`}
|
||||
className="shrink-0"
|
||||
onClick={() => removeKb(kb.id)}
|
||||
>
|
||||
<span aria-hidden className="i-ri-close-line size-3.5" />
|
||||
</IconButton>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<Combobox<SelectedKb, true>
|
||||
multiple
|
||||
disabled={isCreating}
|
||||
items={pickerItems}
|
||||
filter={null}
|
||||
value={selected}
|
||||
inputValue={keyword}
|
||||
itemToStringLabel={(kb) => kb.name}
|
||||
isItemEqualToValue={(item, value) => item.id === value.id}
|
||||
onValueChange={setSelected}
|
||||
onInputValueChange={(value, details) => {
|
||||
// Keep the query so several results of one search can be picked.
|
||||
if (details.isItemPress) details.cancel()
|
||||
else setKeyword(value)
|
||||
}}
|
||||
>
|
||||
<ComboboxTrigger
|
||||
aria-label={addLabel}
|
||||
render={
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
className="w-full data-popup-open:bg-components-button-secondary-bg-hover data-popup-open:inset-ring-components-button-secondary-border-hover"
|
||||
/>
|
||||
}
|
||||
>
|
||||
<span aria-hidden className="me-1 i-ri-add-line size-4" />
|
||||
{addLabel}
|
||||
</ComboboxTrigger>
|
||||
<ComboboxPortal>
|
||||
<ComboboxPositioner align="center">
|
||||
<ComboboxPopup
|
||||
aria-label={searchLabel}
|
||||
className="w-[min(20rem,var(--available-width))]"
|
||||
>
|
||||
<ComboboxInputGroup>
|
||||
<ComboboxInput
|
||||
ref={pickerInputRef}
|
||||
aria-label={searchLabel}
|
||||
placeholder={searchLabel}
|
||||
/>
|
||||
</ComboboxInputGroup>
|
||||
<ComboboxStatus>
|
||||
{isLoading ? t(($) => $.loading, { ns: 'common' }) : null}
|
||||
</ComboboxStatus>
|
||||
<ComboboxList<SelectedKb>
|
||||
aria-label={t(($) => $['apiKeyModal.scopeSpecificDatasets'], {
|
||||
ns: 'appApi',
|
||||
})}
|
||||
>
|
||||
{knowledgeFsEnabled && (
|
||||
<ComboboxGroup items={knowledgeSpaces}>
|
||||
<ComboboxGroupLabel>
|
||||
{t(($) => $['apiKeyModal.pickerKnowledgeSpaces'], { ns: 'appApi' })}
|
||||
</ComboboxGroupLabel>
|
||||
<ComboboxCollection<SelectedKb>>
|
||||
{renderPickerOption}
|
||||
</ComboboxCollection>
|
||||
</ComboboxGroup>
|
||||
)}
|
||||
<ComboboxGroup items={datasets}>
|
||||
{knowledgeFsEnabled && (
|
||||
<ComboboxGroupLabel>
|
||||
{t(($) => $['apiKeyModal.pickerLegacyDatasets'], { ns: 'appApi' })}
|
||||
</ComboboxGroupLabel>
|
||||
)}
|
||||
<ComboboxCollection<SelectedKb>>{renderPickerOption}</ComboboxCollection>
|
||||
</ComboboxGroup>
|
||||
</ComboboxList>
|
||||
<ComboboxEmpty>
|
||||
{isLoading || hasLookupError ? null : t(($) => $.noData, { ns: 'common' })}
|
||||
</ComboboxEmpty>
|
||||
{knowledgeFsEnabled && (
|
||||
<PickerPagination
|
||||
query={knowledgeSpacesQuery}
|
||||
errorLabel={t(($) => $['apiKeyModal.loadKnowledgeSpacesError'], {
|
||||
ns: 'appApi',
|
||||
})}
|
||||
loadMoreLabel={t(($) => $['apiKeyModal.loadMoreKnowledgeSpaces'], {
|
||||
ns: 'appApi',
|
||||
})}
|
||||
onSettled={focusPickerInput}
|
||||
/>
|
||||
)}
|
||||
<PickerPagination
|
||||
query={datasetsQuery}
|
||||
errorLabel={t(($) => $['apiKeyModal.loadDatasetsError'], { ns: 'appApi' })}
|
||||
loadMoreLabel={t(($) => $['apiKeyModal.loadMoreDatasets'], {
|
||||
ns: 'appApi',
|
||||
})}
|
||||
onSettled={focusPickerInput}
|
||||
/>
|
||||
</ComboboxPopup>
|
||||
</ComboboxPositioner>
|
||||
</ComboboxPortal>
|
||||
</Combobox>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</DialogBody>
|
||||
|
||||
<DialogFooter>
|
||||
<DialogClose render={<Button variant="secondary" disabled={isCreating} />}>
|
||||
{t(($) => $['operation.cancel'], { ns: 'common' })}
|
||||
</DialogClose>
|
||||
<Button type="submit" disabled={!canCreate} loading={isCreating}>
|
||||
{t(($) => $['operation.create'], { ns: 'common' })}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
export function maskApiKey(token: string) {
|
||||
// Knowledge API list responses are already masked by the server.
|
||||
if (token.includes('...') || token === '***') return token
|
||||
return `${token.slice(0, 5)}...${token.slice(-4)}`
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
import { useMutation } from '@tanstack/react-query'
|
||||
import { consoleQuery } from '@/service/console'
|
||||
|
||||
export function useDatasetApiKeyMutations() {
|
||||
const createKey = useMutation(consoleQuery.datasets.apiKeys.post.mutationOptions())
|
||||
const deleteKey = useMutation(consoleQuery.datasets.apiKeys.byApiKeyId.delete.mutationOptions())
|
||||
return { createKey, deleteKey, pending: createKey.isPending || deleteKey.isPending }
|
||||
}
|
||||
Reference in new issue
Block a user