Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix(web): complete API key deletion confirmation lifecycle (#43969)
yyh69b9b486402b
diff --git a/web/app/components/api-key/__tests__/api-key-modal.spec.tsx b/web/app/components/api-key/__tests__/api-key-modal.spec.tsxindex e1f131793d9..7aaae13ab80 100644--- a/web/app/components/api-key/__tests__/api-key-modal.spec.tsx+++ b/web/app/components/api-key/__tests__/api-key-modal.spec.tsx@@ -2,10 +2,9 @@ import type { ApiKeyList as AppApiKeyList } from '@dify/contracts/api/console/apimport type { ApiKeyList as DatasetApiKeyList } from '@dify/contracts/api/console/datasets/types.gen'import type { EnvironmentApiKey } from '@dify/contracts/enterprise-app-deploy/types.gen'import type { ComponentProps } from 'react'-import { QueryClientProvider, skipToken } from '@tanstack/react-query'+import { QueryClientProvider } from '@tanstack/react-query'import { act, screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import { afterEach } from 'vite-plus/test'import { render } from '@/test/console/render'import { createTestQueryClient } from '@/test/query-client'import { ApiKeyModal } from '../api-key-modal'@@ -25,90 +24,34 @@ const apiMocks = vi.hoisted(() => ({deleteEnvironment: vi.fn(),}))-vi.mock('@/service/console', () => ({- consoleQuery: {- apps: {- byResourceId: {- apiKeys: {- get: {- queryOptions: ({ input }: { input: unknown }) => ({- queryKey: ['apps', 'api-keys', input],- queryFn:- input === skipToken- ? skipToken- : () => {- apiMocks.listApp(input)- return Promise.resolve({ data: apiMocks.appKeys })- },- }),- },- post: {- mutationOptions: () => ({- mutationFn: (variables: unknown) => apiMocks.createApp(variables),- }),- },- byApiKeyId: {- delete: {- mutationOptions: () => ({- mutationFn: (variables: unknown) => apiMocks.deleteApp(variables),- }),- },- },- },- },- },- datasets: {- apiKeys: {- get: {- queryOptions: () => ({- queryKey: ['datasets', 'api-keys'],- queryFn: () => {- apiMocks.listDataset()- return Promise.resolve({ data: apiMocks.datasetKeys })- },- }),- },- post: {- mutationOptions: () => ({- mutationFn: (variables: unknown) => apiMocks.createDataset(variables),- }),- },- byApiKeyId: {- delete: {- mutationOptions: () => ({- mutationFn: (variables: unknown) => apiMocks.deleteDataset(variables),- }),- },- },- },- },- enterprise: {- appDeploy: {- accessService: {- listEnvironmentApiKeys: {- queryOptions: ({ input }: { input: unknown }) => ({- queryKey: ['environment', 'api-keys', input],- queryFn:- input === skipToken- ? skipToken- : () => {- apiMocks.listEnvironment(input)- return Promise.resolve({ data: apiMocks.environmentKeys })- },- }),- },- createEnvironmentApiKey: {- mutationOptions: () => ({- mutationFn: (variables: unknown) => apiMocks.createEnvironment(variables),- }),- },- deleteEnvironmentApiKey: {- mutationOptions: () => ({- mutationFn: (variables: unknown) => apiMocks.deleteEnvironment(variables),- }),- },- },- },+vi.mock('@/service/console/browser', () => ({+ consoleBrowserLink: {+ call: async (path: string[], input: unknown) => {+ switch (path.join('.')) {+ case 'apps.byResourceId.apiKeys.get':+ apiMocks.listApp(input)+ return { data: apiMocks.appKeys }+ case 'apps.byResourceId.apiKeys.post':+ return apiMocks.createApp(input)+ case 'apps.byResourceId.apiKeys.byApiKeyId.delete':+ return apiMocks.deleteApp(input)+ case 'datasets.apiKeys.get':+ apiMocks.listDataset()+ return { data: apiMocks.datasetKeys }+ case 'datasets.apiKeys.post':+ return apiMocks.createDataset(input)+ case 'datasets.apiKeys.byApiKeyId.delete':+ return apiMocks.deleteDataset(input)+ case 'enterprise.appDeploy.accessService.listEnvironmentApiKeys':+ apiMocks.listEnvironment(input)+ return { data: apiMocks.environmentKeys }+ case 'enterprise.appDeploy.accessService.createEnvironmentApiKey':+ return apiMocks.createEnvironment(input)+ case 'enterprise.appDeploy.accessService.deleteEnvironmentApiKey':+ return apiMocks.deleteEnvironment(input)+ default:+ throw new Error(`Unexpected API call: ${path.join('.')}`)+ }},},}))@@ -171,26 +114,19 @@ async function renderModal(/></QueryClientProvider>,)- await act(async () => {- vi.runAllTimers()- })+ await waitFor(() => expect(queryClient.isFetching()).toBe(0))return { ...result, onOpenChange }}async function confirmKeyDeletion(accessibleName: string) {- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const user = userEvent.setup()const deleteButton = screen.getByRole('button', { name: accessibleName })await user.click(deleteButton)- await act(async () => {- vi.runAllTimers()- })- await user.click(await screen.findByText('common.operation.confirm'))+ await user.click(await screen.findByRole('button', { name: 'common.operation.confirm' }))}describe('ApiKeyModal', () => {beforeEach(() => {- vi.clearAllMocks()- vi.useFakeTimers({ shouldAdvanceTime: true })mockCurrentWorkspace.mockReturnValue({ id: 'workspace-1', name: 'Test Workspace' })apiMocks.appKeys = []apiMocks.datasetKeys = []@@ -208,11 +144,6 @@ describe('ApiKeyModal', () => {apiMocks.deleteEnvironment.mockResolvedValue(undefined)})- afterEach(() => {- vi.runOnlyPendingTimers()- vi.useRealTimers()- })-it('loads and renders app API keys through the generated query input', async () => {apiMocks.appKeys = [{@@ -254,7 +185,7 @@ describe('ApiKeyModal', () => {})it('creates an app API key through the generated mutation input', async () => {- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const user = userEvent.setup()await renderModal(appScope)await user.click(screen.getByText('appApi.apiKeyModal.createNewSecretKey'))@@ -270,7 +201,7 @@ describe('ApiKeyModal', () => {})it('creates a workspace dataset API key scoped to all knowledge bases', async () => {- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const user = userEvent.setup()await renderModal(datasetScope)await user.click(screen.getByText('appApi.apiKeyModal.createNewSecretKey'))@@ -287,35 +218,8 @@ describe('ApiKeyModal', () => {).toHaveValue('new-dataset-token-123')})- it('deletes an app API key through the generated mutation input', async () => {- apiMocks.appKeys = [- {- id: 'app-key-0',- token: 'other-app-secret-token-987654321',- type: 'app',- created_at: 1,- },- {- id: 'app-key-1',- token: 'app-secret-token-123456789',- type: 'app',- created_at: 1,- },- ]- await renderModal(appScope)- await screen.findByText('app...cret-token-123456789')-- await confirmKeyDeletion('common.operation.delete app...cret-token-123456789')-- await waitFor(() => {- expect(apiMocks.deleteApp).toHaveBeenCalledWith({- params: { resource_id: 'app-123', api_key_id: 'app-key-1' },- })- })- })-it('searches for a knowledge base and creates a key scoped to the selection', async () => {- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const user = userEvent.setup()await renderModal(datasetScope)await user.click(screen.getByText('appApi.apiKeyModal.createNewSecretKey'))@@ -349,33 +253,6 @@ describe('ApiKeyModal', () => {).toHaveValue('new-dataset-token-123')})- it('deletes a dataset API key through the generated mutation input', async () => {- apiMocks.datasetKeys = [- {- id: 'dataset-key-0',- token: 'other-dataset-secret-token-987654321',- type: 'dataset',- created_at: 1,- },- {- id: 'dataset-key-1',- token: 'dataset-secret-token-123456789',- type: 'dataset',- created_at: 1,- },- ]- await renderModal(datasetScope)- await screen.findByText('dat...cret-token-123456789')-- await confirmKeyDeletion('common.operation.delete dat...cret-token-123456789')-- await waitFor(() => {- expect(apiMocks.deleteDataset).toHaveBeenCalledWith({- params: { api_key_id: 'dataset-key-1' },- })- })- })-it('loads environment-scoped keys without requesting built-in app keys', async () => {apiMocks.environmentKeys = [{@@ -399,7 +276,7 @@ describe('ApiKeyModal', () => {})it('creates an environment-scoped API key', async () => {- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const user = userEvent.setup()await renderModal(environmentScope)await user.click(screen.getByText('appApi.apiKeyModal.createNewSecretKey'))@@ -417,30 +294,110 @@ describe('ApiKeyModal', () => {).toHaveValue('env-created-secret-key-abcdefghijklmnopqrst')})- it('deletes an environment-scoped API key', async () => {- apiMocks.environmentKeys = [- {- id: 'environment-key-1',- token: 'env-existing-secret-key-abcdefghijklmnopqrst',- type: 'api',- created_at: 1,- },- ]- await renderModal(environmentScope)-- await screen.findByText(/^env\.\.\./)- await confirmKeyDeletion('common.operation.delete env...abcdefghijklmnopqrst')+ it.each(['cancel', 'escape'] as const)(+ 'cancels deletion with %s without closing key management, then targets another key',+ async (dismiss) => {+ const user = userEvent.setup()+ apiMocks.appKeys = [+ { id: 'first', token: 'app-first', type: 'app', created_at: 1 },+ { id: 'second', token: 'app-second', type: 'app', created_at: 1 },+ ]+ const { onOpenChange } = await renderModal(appScope)+ const firstTrigger = screen.getByRole('button', {+ name: 'common.operation.delete app...app-first',+ })+ await user.click(firstTrigger)+ const dialog = await screen.findByRole('alertdialog', {+ name: 'appApi.actionMsg.deleteConfirmTitle',+ })+ expect(dialog).toHaveAccessibleDescription('appApi.actionMsg.deleteConfirmTips')++ if (dismiss === 'cancel')+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ else await user.keyboard('{Escape}')++ await waitFor(() => expect(dialog).not.toBeInTheDocument())+ expect(firstTrigger).toHaveFocus()+ expect(onOpenChange).not.toHaveBeenCalled()+ expect(apiMocks.deleteApp).not.toHaveBeenCalled()++ await confirmKeyDeletion('common.operation.delete app...app-second')+ await waitFor(() =>+ expect(apiMocks.deleteApp).toHaveBeenCalledWith({+ params: { resource_id: 'app-123', api_key_id: 'second' },+ }),+ )+ },+ )- await waitFor(() => {- expect(apiMocks.deleteEnvironment).toHaveBeenCalledWith({- params: {- api_key_id: 'environment-key-1',- app_id: 'app-123',- environment_id: 'staging',- },+ it.each([+ {+ scope: appScope,+ keys: 'appKeys',+ remove: 'deleteApp',+ list: 'listApp',+ params: { resource_id: 'app-123', api_key_id: 'key-1' },+ },+ {+ scope: datasetScope,+ keys: 'datasetKeys',+ remove: 'deleteDataset',+ list: 'listDataset',+ params: { api_key_id: 'key-1' },+ },+ {+ scope: environmentScope,+ keys: 'environmentKeys',+ remove: 'deleteEnvironment',+ list: 'listEnvironment',+ params: { app_id: 'app-123', environment_id: 'staging', api_key_id: 'key-1' },+ },+ ] as const)(+ 'keeps $scope.type deletion pending, allows retry after failure, and refreshes after success',+ async ({ scope, keys, remove, list, params }) => {+ const user = userEvent.setup()+ apiMocks[keys] = [{ id: 'key-1', token: 'key-secret', type: 'api', created_at: 1 }]+ let rejectDeletion!: (reason: Error) => void+ const request = new Promise<void>((_resolve, reject) => {+ rejectDeletion = reject})- })- })+ apiMocks[remove].mockReturnValueOnce(request)+ const { onOpenChange } = await renderModal(scope)+ await confirmKeyDeletion('common.operation.delete key...key-secret')+ const dialog = screen.getByRole('alertdialog')+ const confirm = screen.getByRole('button', { name: 'common.operation.confirm' })+ const cancel = screen.getByRole('button', { name: 'common.operation.cancel' })+ expect(confirm).toHaveAttribute('aria-disabled', 'true')+ expect(cancel).toBeDisabled()+ await user.click(confirm)+ await user.click(cancel)+ await user.keyboard('{Escape}')+ expect(dialog).toBeInTheDocument()+ expect(onOpenChange).not.toHaveBeenCalled()+ expect(apiMocks[remove]).toHaveBeenCalledExactlyOnceWith({ params })++ await act(async () => rejectDeletion(new Error('Deletion failed')))+ await waitFor(() => expect(cancel).toBeEnabled())+ expect(dialog).toBeInTheDocument()+ expect(screen.getByRole('button', { name: 'common.operation.confirm' })).not.toHaveAttribute(+ 'aria-disabled',+ 'true',+ )++ apiMocks[remove].mockImplementationOnce(async () => {+ apiMocks[keys] = []+ })+ await user.click(confirm)+ await waitFor(() => expect(dialog).not.toBeInTheDocument())+ await waitFor(() => expect(apiMocks[list]).toHaveBeenCalledTimes(2))+ expect(+ screen.queryByRole('button', { name: 'common.operation.delete key...key-secret' }),+ ).not.toBeInTheDocument()+ expect(screen.getByRole('dialog')).toBeInTheDocument()+ expect(onOpenChange).not.toHaveBeenCalled()+ expect(apiMocks[remove]).toHaveBeenCalledTimes(2)+ },+ )it('disables creation when the caller cannot manage keys', async () => {await renderModal(datasetScope, { canManage: false })@@ -454,7 +411,7 @@ describe('ApiKeyModal', () => {it('exposes an accessible close button', async () => {const { onOpenChange } = await renderModal(datasetScope)- const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime })+ const user = userEvent.setup()await user.click(screen.getByRole('button', { name: 'common.operation.close' }))diff --git a/web/app/components/api-key/api-key-modal.tsx b/web/app/components/api-key/api-key-modal.tsxindex f76a435aff0..21056db3d7e 100644--- a/web/app/components/api-key/api-key-modal.tsx+++ b/web/app/components/api-key/api-key-modal.tsx@@ -1,5 +1,6 @@'use client'import type { ApiKeyItem } from '@dify/contracts/api/console/apps/types.gen'+import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'import {AlertDialog,AlertDialogCancelButton,@@ -20,7 +21,7 @@ import {import { IconButton } from '@langgenius/dify-ui/icon-button'import { skipToken, useMutation, useQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'-import { useState } from 'react'+import { useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'import { currentWorkspaceAtom } from '@/context/workspace-state'@@ -45,7 +46,7 @@ type ApiKeyModalProps = {export function ApiKeyModal({ open, canManage, scope, onOpenChange }: ApiKeyModalProps) {const { t } = useTranslation(['appApi', 'common'])const currentWorkspace = useAtomValue(currentWorkspaceAtom)- const [deleteKeyId, setDeleteKeyId] = useState<string>()+ const deleteActionsRef = useRef<AlertDialogActions>(null)const [createdApiKey, setCreatedApiKey] = useState<CreatedApiKey>()const [scopeDialogOpen, setScopeDialogOpen] = useState(false)// Bumped on each open so the scope dialog remounts with fresh selection state.@@ -102,17 +103,16 @@ export function ApiKeyModal({ open, canManage, scope, onOpenChange }: ApiKeyModa: scope.type === 'dataset'? createDatasetApiKey.isPending: createEnvironmentApiKey.isPending- const isDeleting =+ const deleteMutation =scope.type === 'app'- ? deleteAppApiKey.isPending+ ? deleteAppApiKey: scope.type === 'dataset'- ? deleteDatasetApiKey.isPending- : deleteEnvironmentApiKey.isPending+ ? deleteDatasetApiKey+ : deleteEnvironmentApiKeyconst createDisabled = !currentWorkspace.id || !canManageconst handleOpenChange = (nextOpen: boolean) => {if (!nextOpen) {- setDeleteKeyId(undefined)setCreatedApiKey(undefined)setScopeDialogOpen(false)}@@ -157,10 +157,12 @@ export function ApiKeyModal({ open, canManage, scope, onOpenChange }: ApiKeyModa)}- const handleDelete = () => {- if (!deleteKeyId || isDeleting) return+ const handleDelete = (deleteKeyId: string | undefined) => {+ if (!deleteKeyId || !canManage || deleteMutation.isPending) return- const onSuccess = () => setDeleteKeyId(undefined)+ const onSuccess = () => {+ deleteActionsRef.current?.close()+ }switch (scope.type) {case 'app':deleteAppApiKey.mutate(@@ -214,14 +216,48 @@ export function ApiKeyModal({ open, canManage, scope, onOpenChange }: ApiKeyModa<LoadingPlaceholder /></div>)}- {!!apiKeys?.length && (- <ApiKeyTable- apiKeys={apiKeys}- canManage={canManage}- showScope={scope.type === 'dataset'}- onDeleteRequest={setDeleteKeyId}- />- )}+ <AlertDialog<string>+ actionsRef={deleteActionsRef}+ onOpenChange={(nextOpen, details) => {+ if (!nextOpen && deleteMutation.isPending && details.reason !== 'imperative-action') {+ details.cancel()+ }+ }}+ >+ {({ payload }) => (+ <>+ {!!apiKeys?.length && (+ <ApiKeyTable+ apiKeys={apiKeys}+ canManage={canManage}+ showScope={scope.type === 'dataset'}+ />+ )}+ <AlertDialogContent backdropProps={{ forceRender: true }}>+ <div className="flex flex-col gap-2 px-6 pt-6 pb-4">+ <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">+ {t(($) => $['actionMsg.deleteConfirmTitle'], { ns: 'appApi' })}+ </AlertDialogTitle>+ <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">+ {t(($) => $['actionMsg.deleteConfirmTips'], { ns: 'appApi' })}+ </AlertDialogDescription>+ </div>+ <AlertDialogFooter>+ <AlertDialogCancelButton disabled={deleteMutation.isPending}>+ {t(($) => $['operation.cancel'], { ns: 'common' })}+ </AlertDialogCancelButton>+ <AlertDialogConfirmButton+ loading={deleteMutation.isPending}+ disabled={!canManage}+ onClick={() => handleDelete(payload)}+ >+ {t(($) => $['operation.confirm'], { ns: 'common' })}+ </AlertDialogConfirmButton>+ </AlertDialogFooter>+ </AlertDialogContent>+ </>+ )}+ </AlertDialog><div className="flex shrink-0 px-6 py-4"><Button disabled={createDisabled} loading={isCreating} onClick={handleCreate}><span aria-hidden className="i-ri-add-line size-4 shrink-0" />@@ -230,31 +266,6 @@ export function ApiKeyModal({ open, canManage, scope, onOpenChange }: ApiKeyModa</div></DialogContent></Dialog>- <AlertDialog- open={deleteKeyId !== undefined}- onOpenChange={(open) => {- if (!open && !isDeleting) setDeleteKeyId(undefined)- }}- >- <AlertDialogContent>- <div className="flex flex-col gap-2 px-6 pt-6 pb-4">- <AlertDialogTitle className="w-full truncate title-2xl-semi-bold text-text-primary">- {t(($) => $['actionMsg.deleteConfirmTitle'], { ns: 'appApi' })}- </AlertDialogTitle>- <AlertDialogDescription className="w-full system-md-regular wrap-break-word whitespace-pre-wrap text-text-tertiary">- {t(($) => $['actionMsg.deleteConfirmTips'], { ns: 'appApi' })}- </AlertDialogDescription>- </div>- <AlertDialogFooter>- <AlertDialogCancelButton disabled={isDeleting}>- {t(($) => $['operation.cancel'], { ns: 'common' })}- </AlertDialogCancelButton>- <AlertDialogConfirmButton loading={isDeleting} onClick={handleDelete}>- {t(($) => $['operation.confirm'], { ns: 'common' })}- </AlertDialogConfirmButton>- </AlertDialogFooter>- </AlertDialogContent>- </AlertDialog><CreatedApiKeyDialogopen={open && createdApiKey !== undefined}onOpenChange={(nextOpen) => {diff --git a/web/app/components/api-key/api-key-table.tsx b/web/app/components/api-key/api-key-table.tsxindex fb25e25b02c..20ba7396620 100644--- a/web/app/components/api-key/api-key-table.tsx+++ b/web/app/components/api-key/api-key-table.tsx@@ -1,5 +1,6 @@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 { useTranslation } from 'react-i18next'import useTimestamp from '@/hooks/use-timestamp'@@ -9,15 +10,9 @@ type ApiKeyTableProps = {canManage: boolean// Dataset keys carry a knowledge-base scope; enable the SCOPE column to surface it.showScope?: boolean- onDeleteRequest: (apiKeyId: string) => void}-export function ApiKeyTable({- apiKeys,- canManage,- showScope = false,- onDeleteRequest,-}: ApiKeyTableProps) {+export function ApiKeyTable({ apiKeys, canManage, showScope = false }: ApiKeyTableProps) {const { t } = useTranslation(['appApi', 'common', 'time'])const { formatTime } = useTimestamp()const maskToken = (token: string) => `${token.slice(0, 3)}...${token.slice(-20)}`@@ -76,12 +71,17 @@ export function ApiKeyTable({<td className="px-6 py-1"><div className="flex justify-end gap-1">{canManage && (- <IconButton- aria-label={`${t(($) => $['operation.delete'], { ns: 'common' })} ${maskToken(apiKey.token)}`}- onClick={() => onDeleteRequest(apiKey.id)}- >- <span aria-hidden className="i-ri-delete-bin-line size-4" />- </IconButton>+ <AlertDialogTrigger+ id={apiKey.id}+ payload={apiKey.id}+ render={+ <IconButton+ aria-label={`${t(($) => $['operation.delete'], { ns: 'common' })} ${maskToken(apiKey.token)}`}+ >+ <span aria-hidden className="i-ri-delete-bin-line size-4" />+ </IconButton>+ }+ />)}</div></td>