Skip to content

armgit / dify

Public Imported from GitHub
0

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.

refactor(web): open confirm dialogs from triggers and close them when the request settles (#43888)

yyhf22585209472
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 80eab1a9606..d6814817438 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -4333,7 +4333,7 @@
"count": 1
},
"typescript/no-explicit-any": {
- "count": 4
+ "count": 3
}
},
"web/service/apps.ts": {
diff --git a/web/app/components/app/annotation/__tests__/batch-action.spec.tsx b/web/app/components/app/annotation/__tests__/batch-action.spec.tsx
index 95342615d15..b72dbb0587e 100644
--- a/web/app/components/app/annotation/__tests__/batch-action.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/batch-action.spec.tsx
@@ -53,4 +53,21 @@ describe('BatchAction', () => {
})
expect(onBatchDelete).not.toHaveBeenCalled()
})
+
+ it('should keep the delete confirmation open when batch delete fails', async () => {
+ const onBatchDelete = vi.fn().mockRejectedValue(new Error('failed'))
+ render(<BatchAction {...baseProps} onBatchDelete={onBatchDelete} />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'common.operation.delete' }))
+ const dialog = await screen.findByRole('alertdialog')
+ fireEvent.click(within(dialog).getByRole('button', { name: 'common.operation.delete' }))
+
+ await waitFor(() => {
+ expect(onBatchDelete).toHaveBeenCalledTimes(1)
+ })
+ await waitFor(() => {
+ expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeEnabled()
+ })
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ })
})
diff --git a/web/app/components/app/annotation/__tests__/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsx
index 286dc435a11..b919d82bd65 100644
--- a/web/app/components/app/annotation/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/index.spec.tsx
@@ -80,7 +80,7 @@ vi.mock('../list', () => ({
<button data-testid="list-view" onClick={() => props.onView(props.list[0])}>
view
</button>
- <button data-testid="list-remove" onClick={() => props.onRemove(props.list[0].id)}>
+ <button data-testid="list-remove" onClick={() => props.onRemoved()}>
remove
</button>
<button data-testid="list-batch-delete" onClick={() => props.onBatchDelete()}>
@@ -266,6 +266,20 @@ describe('Annotation', () => {
expect(fetchAnnotationListMock).toHaveBeenCalledTimes(2)
})
+ it('should refetch the list after a row is removed', async () => {
+ fetchAnnotationListMock.mockResolvedValue({ data: [createAnnotation()], total: 1 })
+
+ renderComponent()
+ await screen.findByTestId('list')
+ const fetchCount = fetchAnnotationListMock.mock.calls.length
+
+ fireEvent.click(screen.getByTestId('list-remove'))
+
+ await waitFor(() => {
+ expect(fetchAnnotationListMock.mock.calls.length).toBeGreaterThan(fetchCount)
+ })
+ })
+
it('should support viewing items and running batch deletion success flow', async () => {
const annotation = createAnnotation()
fetchAnnotationListMock.mockResolvedValue({ data: [annotation], total: 1 })
@@ -323,7 +337,7 @@ describe('Annotation', () => {
})
await act(async () => {
- await latestListProps.onBatchDelete()
+ await expect(latestListProps.onBatchDelete()).rejects.toThrow(error.message)
})
await waitFor(() => {
diff --git a/web/app/components/app/annotation/__tests__/list.spec.tsx b/web/app/components/app/annotation/__tests__/list.spec.tsx
index 031c667556f..764651a9633 100644
--- a/web/app/components/app/annotation/__tests__/list.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/list.spec.tsx
@@ -1,6 +1,8 @@
import type { AnnotationItem } from '../type'
-import { fireEvent, render, screen, within } from '@testing-library/react'
+import { fireEvent, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import * as React from 'react'
+import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import { List } from '../list'
const mockFormatTime = vi.fn(() => 'formatted-time')
@@ -11,6 +13,16 @@ vi.mock('@/hooks/use-timestamp', () => ({
}),
}))
+const { mockedRequest } = vi.hoisted(() => ({
+ mockedRequest:
+ vi.fn<(url: string, init: RequestInit, options: { request: Request }) => Promise<Response>>(),
+}))
+
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request: mockedRequest,
+}))
+
const createAnnotation = (overrides: Partial<AnnotationItem> = {}): AnnotationItem => ({
id: overrides.id ?? 'annotation-id',
question: overrides.question ?? 'question 1',
@@ -30,9 +42,10 @@ describe('List', () => {
render(
<List
+ appId="app-1"
list={[item]}
onView={onView}
- onRemove={vi.fn()}
+ onRemoved={vi.fn()}
selectedIds={[]}
onSelectedIdsChange={vi.fn()}
onBatchDelete={vi.fn()}
@@ -53,9 +66,10 @@ describe('List', () => {
const onSelectedIdsChange = vi.fn()
const { rerender } = render(
<List
+ appId="app-1"
list={list}
onView={vi.fn()}
- onRemove={vi.fn()}
+ onRemoved={vi.fn()}
selectedIds={[]}
onSelectedIdsChange={onSelectedIdsChange}
onBatchDelete={vi.fn()}
@@ -67,9 +81,10 @@ describe('List', () => {
rerender(
<List
+ appId="app-1"
list={list}
onView={vi.fn()}
- onRemove={vi.fn()}
+ onRemoved={vi.fn()}
selectedIds={['a']}
onSelectedIdsChange={onSelectedIdsChange}
onBatchDelete={vi.fn()}
@@ -84,12 +99,14 @@ describe('List', () => {
it('should confirm before removing an annotation and expose batch actions', async () => {
const item = createAnnotation({ id: 'to-delete', question: 'Delete me' })
- const onRemove = vi.fn()
+ const onRemoved = vi.fn()
+ mockedRequest.mockResolvedValue(Response.json({ result: 'success' }))
render(
<List
+ appId="app-1"
list={[item]}
onView={vi.fn()}
- onRemove={onRemove}
+ onRemoved={onRemoved}
selectedIds={[item.id]}
onSelectedIdsChange={vi.fn()}
onBatchDelete={vi.fn()}
@@ -105,8 +122,51 @@ describe('List', () => {
)!.toBeInTheDocument()
const confirmButton = await screen.findByRole('button', { name: 'common.operation.confirm' })
fireEvent.click(confirmButton)
- expect(onRemove).toHaveBeenCalledWith(item.id)
+ await waitFor(() => {
+ expect(onRemoved).toHaveBeenCalledTimes(1)
+ })
+ const [url, , options] = mockedRequest.mock.calls[0]!
+ expect(url).toMatch(/\/apps\/app-1\/annotations\/to-delete$/)
+ expect(options.request.method).toBe('DELETE')
expect(screen.getByText('appAnnotation.batchAction.selected'))!.toBeInTheDocument()
})
+
+ it('should keep the remove confirmation open until the removal settles', async () => {
+ const user = userEvent.setup()
+ const item = createAnnotation({ id: 'to-delete', question: 'Delete me' })
+ let settleRemove: (response: Response) => void = () => {}
+ mockedRequest.mockReturnValue(
+ new Promise<Response>((resolve) => {
+ settleRemove = resolve
+ }),
+ )
+ render(
+ <List
+ appId="app-1"
+ list={[item]}
+ onView={vi.fn()}
+ onRemoved={vi.fn()}
+ selectedIds={[]}
+ onSelectedIdsChange={vi.fn()}
+ onBatchDelete={vi.fn()}
+ />,
+ )
+
+ await user.click(screen.getByRole('button', { name: 'appDebug.feature.annotation.remove' }))
+ const dialog = await screen.findByRole('alertdialog')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.confirm' }))
+
+ await waitFor(() => {
+ expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
+ })
+ await user.keyboard('{Escape}')
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+
+ settleRemove(Response.json({ result: 'success' }))
+
+ await waitFor(() => {
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
+ })
})
diff --git a/web/app/components/app/annotation/batch-action.tsx b/web/app/components/app/annotation/batch-action.tsx
index cf0fda80d1d..c5c85432fe1 100644
--- a/web/app/components/app/annotation/batch-action.tsx
+++ b/web/app/components/app/annotation/batch-action.tsx
@@ -1,3 +1,4 @@
+import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import type { FC } from 'react'
import {
AlertDialog,
@@ -6,6 +7,7 @@ import {
AlertDialogContent,
AlertDialogFooter,
AlertDialogTitle,
+ AlertDialogTrigger,
} from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
@@ -30,15 +32,19 @@ const BatchAction: FC<IBatchActionProps> = ({
onSelectedIdsChange,
}) => {
const { t } = useTranslation(['appAnnotation', 'common'])
- const [isShowDeleteConfirm, { setTrue: showDeleteConfirm, setFalse: hideDeleteConfirm }] =
- useBoolean(false)
+ const deleteConfirmActionsRef = React.useRef<AlertDialogActions>(null)
const [isDeleting, { setTrue: setIsDeleting, setFalse: setIsNotDeleting }] = useBoolean(false)
const handleBatchDelete = async () => {
setIsDeleting()
- await onBatchDelete()
- hideDeleteConfirm()
- setIsNotDeleting()
+ try {
+ await onBatchDelete()
+ deleteConfirmActionsRef.current?.close()
+ } catch {
+ // The owner reports the failure; the dialog stays open so the user can retry.
+ } finally {
+ setIsNotDeleting()
+ }
}
return (
<div className={cn('pointer-events-none flex w-full justify-center gap-x-2', className)}>
@@ -52,33 +58,38 @@ const BatchAction: FC<IBatchActionProps> = ({
</span>
</div>
<Separator decorative orientation="vertical" className="mx-0.5 h-3.5" />
- <Button variant="ghost" tone="destructive" onClick={showDeleteConfirm}>
- <span aria-hidden className="i-ri-delete-bin-line size-4" />
- <span>{t(($) => $['operation.delete'], { ns: 'common' })}</span>
- </Button>
+ <AlertDialog
+ actionsRef={deleteConfirmActionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && isDeleting && details.reason !== 'imperative-action') details.cancel()
+ }}
+ >
+ <AlertDialogTrigger render={<Button variant="ghost" tone="destructive" />}>
+ <span aria-hidden className="i-ri-delete-bin-line size-4" />
+ <span>{t(($) => $['operation.delete'], { ns: 'common' })}</span>
+ </AlertDialogTrigger>
+ <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(($) => $['list.delete.title'], { ns: 'appAnnotation' })}
+ </AlertDialogTitle>
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={isDeleting}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton loading={isDeleting} onClick={handleBatchDelete}>
+ {t(($) => $['operation.delete'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
<Separator decorative orientation="vertical" className="mx-0.5 h-3.5" />
<Button variant="ghost" onClick={() => onSelectedIdsChange([])}>
<span>{t(($) => $['operation.cancel'], { ns: 'common' })}</span>
</Button>
</div>
- <AlertDialog open={isShowDeleteConfirm} onOpenChange={(open) => !open && hideDeleteConfirm()}>
- <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(($) => $['list.delete.title'], { ns: 'appAnnotation' })}
- </AlertDialogTitle>
- </div>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton loading={isDeleting} onClick={handleBatchDelete}>
- {t(($) => $['operation.delete'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
</div>
)
}
diff --git a/web/app/components/app/annotation/clear-all-annotations-confirm-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/clear-all-annotations-confirm-modal/__tests__/index.spec.tsx
deleted file mode 100644
index 268e3c9ea15..00000000000
--- a/web/app/components/app/annotation/clear-all-annotations-confirm-modal/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,81 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
-import ClearAllAnnotationsConfirmModal from '../index'
-
-vi.mock('react-i18next', async () => {
- const { withSelectorKey } = await import('@/test/i18n-mock')
- return {
- useTranslation: () => ({
- t: withSelectorKey((key: string, options?: { ns?: string }) => {
- const translations: Record<string, string> = {
- 'table.header.clearAllConfirm': 'Clear all annotations?',
- 'operation.confirm': 'Confirm',
- 'operation.cancel': 'Cancel',
- }
- if (translations[key]) return translations[key]
- const prefix = options?.ns ? `${options.ns}.` : ''
- return `${prefix}${key}`
- }),
- }),
- }
-})
-
-beforeEach(() => {
- vi.clearAllMocks()
-})
-
-describe('ClearAllAnnotationsConfirmModal', () => {
- // Rendering visibility toggled by isShow flag
- describe('Rendering', () => {
- it('should show confirmation dialog when isShow is true', () => {
- // Arrange
- render(<ClearAllAnnotationsConfirmModal isShow onHide={vi.fn()} onConfirm={vi.fn()} />)
-
- // Assert
- expect(screen.getByText('Clear all annotations?')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Confirm' })).toBeInTheDocument()
- })
-
- it('should not render anything when isShow is false', () => {
- // Arrange
- render(
- <ClearAllAnnotationsConfirmModal isShow={false} onHide={vi.fn()} onConfirm={vi.fn()} />,
- )
-
- // Assert
- expect(screen.queryByText('Clear all annotations?')).not.toBeInTheDocument()
- })
- })
-
- // User confirms or cancels clearing annotations
- describe('Interactions', () => {
- it('should trigger onHide when cancel is clicked', () => {
- const onHide = vi.fn()
- const onConfirm = vi.fn()
- // Arrange
- render(<ClearAllAnnotationsConfirmModal isShow onHide={onHide} onConfirm={onConfirm} />)
-
- // Act
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
-
- // Assert
- expect(onHide).toHaveBeenCalledTimes(1)
- expect(onConfirm).not.toHaveBeenCalled()
- })
-
- it('should trigger onConfirm when confirm is clicked', () => {
- const onHide = vi.fn()
- const onConfirm = vi.fn()
- // Arrange
- render(<ClearAllAnnotationsConfirmModal isShow onHide={onHide} onConfirm={onConfirm} />)
-
- // Act
- fireEvent.click(screen.getByRole('button', { name: 'Confirm' }))
-
- // Assert
- expect(onConfirm).toHaveBeenCalledTimes(1)
- expect(onHide).not.toHaveBeenCalled()
- })
- })
-})
diff --git a/web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.tsx b/web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.tsx
index 1cd07a42140..1d0bf80746f 100644
--- a/web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.tsx
+++ b/web/app/components/app/annotation/clear-all-annotations-confirm-modal/index.tsx
@@ -1,49 +1,41 @@
'use client'
-import type { FC } from 'react'
import {
- AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogFooter,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
-import * as React from 'react'
import { useTranslation } from 'react-i18next'
type Props = Readonly<{
- isShow: boolean
- onHide: () => void
+ isPending: boolean
onConfirm: () => void
}>
-const ClearAllAnnotationsConfirmModal: FC<Props> = ({ isShow, onHide, onConfirm }) => {
+export function ClearAllAnnotationsConfirmContent({ isPending, onConfirm }: Props) {
const { t } = useTranslation(['appAnnotation', 'common'])
const title = t(($) => $['table.header.clearAllConfirm'], { ns: 'appAnnotation' })
return (
- <AlertDialog open={isShow} onOpenChange={(open) => !open && onHide()}>
- <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"
- title={title}
- >
- {title}
- </AlertDialogTitle>
- </div>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton onClick={onConfirm}>
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ <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"
+ title={title}
+ >
+ {title}
+ </AlertDialogTitle>
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton loading={isPending} onClick={onConfirm}>
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
)
}
-
-export default React.memo(ClearAllAnnotationsConfirmModal)
diff --git a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
index 95a731cd7d0..840c71a1b53 100644
--- a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx
@@ -1,3 +1,4 @@
+import type { Window } from 'happy-dom'
import type { ComponentProps } from 'react'
import type { Mock } from 'vite-plus/test'
import type { AnnotationItemBasic } from '../../type'
@@ -6,7 +7,7 @@ import { act, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { useLocale } from '#i18n'
import { LanguagesSupported } from '@/i18n/language'
-import { clearAllAnnotations, fetchExportAnnotationList } from '@/service/annotation'
+import { fetchExportAnnotationList } from '@/service/annotation'
import { renderWithConsoleQuery as render } from '@/test/console/query-data'
import HeaderOptions from '../index'
@@ -23,7 +24,16 @@ vi.mock('react-papaparse', () => ({
vi.mock('@/service/annotation', () => ({
fetchExportAnnotationList: vi.fn(),
- clearAllAnnotations: vi.fn(),
+}))
+
+const { mockedRequest } = vi.hoisted(() => ({
+ mockedRequest:
+ vi.fn<(url: string, init: RequestInit, options: { request: Request }) => Promise<Response>>(),
+}))
+
+vi.mock('@/service/base', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/service/base')>()),
+ request: mockedRequest,
}))
vi.mock('@/app/components/billing/annotation-full', () => ({
@@ -95,9 +105,10 @@ const mockAnnotations: AnnotationItemBasic[] = [
]
const mockedFetchAnnotations = vi.mocked(fetchExportAnnotationList)
-const mockedClearAllAnnotations = vi.mocked(clearAllAnnotations)
describe('HeaderOptions', () => {
+ const originalUrl = window.location.href
+
beforeEach(() => {
vi.clearAllMocks()
vi.useRealTimers()
@@ -107,6 +118,8 @@ describe('HeaderOptions', () => {
afterEach(() => {
vi.restoreAllMocks()
+ // Earlier cases can leave the test window on a URL the console client cannot build requests from.
+ ;(window as unknown as Window).happyDOM.setURL(originalUrl)
})
it('should fetch annotations on mount and render enabled export actions when data exist', async () => {
@@ -295,7 +308,7 @@ describe('HeaderOptions', () => {
})
it('should clear all annotations when confirmation succeeds', async () => {
- mockedClearAllAnnotations.mockResolvedValue(undefined)
+ mockedRequest.mockResolvedValue(Response.json({ result: 'success' }))
const user = userEvent.setup()
const onAdded = vi.fn()
renderComponent({ onAdded })
@@ -308,14 +321,19 @@ describe('HeaderOptions', () => {
await user.click(confirmButton)
await waitFor(() => {
- expect(mockedClearAllAnnotations).toHaveBeenCalledWith('test-app-id')
expect(onAdded).toHaveBeenCalled()
})
+ const [url, , options] = mockedRequest.mock.calls[0]!
+ expect(url).toMatch(/\/apps\/test-app-id\/annotations$/)
+ expect(options.request.method).toBe('DELETE')
+ await waitFor(() => {
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
})
- it('should handle clear all failures gracefully', async () => {
+ it('should keep the clear all confirmation open when clearing fails', async () => {
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(vi.fn())
- mockedClearAllAnnotations.mockRejectedValue(new Error('network'))
+ mockedRequest.mockRejectedValue(new Error('network'))
const user = userEvent.setup()
const onAdded = vi.fn()
renderComponent({ onAdded })
@@ -327,10 +345,13 @@ describe('HeaderOptions', () => {
await user.click(confirmButton)
await waitFor(() => {
- expect(mockedClearAllAnnotations).toHaveBeenCalled()
- expect(onAdded).not.toHaveBeenCalled()
- expect(consoleSpy).toHaveBeenCalled()
+ expect(mockedRequest).toHaveBeenCalled()
})
+ await waitFor(() => {
+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeEnabled()
+ })
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+ expect(onAdded).not.toHaveBeenCalled()
consoleSpy.mockRestore()
})
diff --git a/web/app/components/app/annotation/header-opts/index.tsx b/web/app/components/app/annotation/header-opts/index.tsx
index cc90e1d62f4..ce031d78623 100644
--- a/web/app/components/app/annotation/header-opts/index.tsx
+++ b/web/app/components/app/annotation/header-opts/index.tsx
@@ -1,6 +1,7 @@
'use client'
import type { FC } from 'react'
import type { AnnotationItemBasic } from '../type'
+import { AlertDialog } from '@langgenius/dify-ui/alert-dialog'
import { Button } from '@langgenius/dify-ui/button'
import {
DropdownMenu,
@@ -11,17 +12,19 @@ import {
DropdownMenuSubTrigger,
DropdownMenuTrigger,
} from '@langgenius/dify-ui/dropdown-menu'
+import { useMutation } from '@tanstack/react-query'
import * as React from 'react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { jsonToCSV } from 'react-papaparse'
import { useLocale } from '#i18n'
import { LanguagesSupported } from '@/i18n/language'
-import { clearAllAnnotations, fetchExportAnnotationList } from '@/service/annotation'
+import { fetchExportAnnotationList } from '@/service/annotation'
+import { consoleQuery } from '@/service/console'
import { downloadBlob } from '@/utils/download'
import AddAnnotationModal from '../add-annotation-modal'
import BatchAddModal from '../batch-add-annotation-modal'
-import ClearAllAnnotationsConfirmModal from '../clear-all-annotations-confirm-modal'
+import { ClearAllAnnotationsConfirmContent } from '../clear-all-annotations-confirm-modal'
const CSV_HEADER_QA_EN = ['Question', 'Answer']
const CSV_HEADER_QA_CN = ['问题', '答案']
@@ -150,6 +153,14 @@ const HeaderOptions: FC<Props> = ({ appId, onAdd, onAdded, controlUpdateList })
const [showBulkImportModal, setShowBulkImportModal] = useState(false)
const [showClearConfirm, setShowClearConfirm] = useState(false)
+ const clearAllMutation = useMutation(
+ consoleQuery.apps.byAppId.annotations.delete.mutationOptions({
+ onSuccess: () => {
+ onAdded()
+ setShowClearConfirm(false)
+ },
+ }),
+ )
const [isOperationsMenuOpen, setIsOperationsMenuOpen] = useState(false)
const handleShowBulkImportModal = React.useCallback(() => {
setShowBulkImportModal(true)
@@ -160,17 +171,6 @@ const HeaderOptions: FC<Props> = ({ appId, onAdd, onAdded, controlUpdateList })
const handleExportJsonl = React.useCallback(() => {
downloadAnnotationJsonl(list, locale)
}, [list, locale])
- const handleConfirmed = async () => {
- try {
- await clearAllAnnotations(appId)
- onAdded()
- } catch (e) {
- console.error(`failed to clear all annotations, ${e}`)
- } finally {
- setShowClearConfirm(false)
- }
- }
-
const [showAddModal, setShowAddModal] = React.useState(false)
return (
@@ -216,13 +216,21 @@ const HeaderOptions: FC<Props> = ({ appId, onAdd, onAdded, controlUpdateList })
onAdded={onAdded}
/>
)}
- {showClearConfirm && (
- <ClearAllAnnotationsConfirmModal
- isShow={showClearConfirm}
- onHide={() => setShowClearConfirm(false)}
- onConfirm={handleConfirmed}
+ <AlertDialog
+ open={showClearConfirm}
+ onOpenChange={(open, details) => {
+ if (!open && clearAllMutation.isPending) {
+ details.cancel()
+ return
+ }
+ setShowClearConfirm(open)
+ }}
+ >
+ <ClearAllAnnotationsConfirmContent
+ isPending={clearAllMutation.isPending}
+ onConfirm={() => clearAllMutation.mutate({ params: { app_id: appId } })}
/>
- )}
+ </AlertDialog>
</div>
)
}
diff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsx
index f09485d32e0..148e57122ec 100644
--- a/web/app/components/app/annotation/index.tsx
+++ b/web/app/components/app/annotation/index.tsx
@@ -146,6 +146,7 @@ const Annotation: FC<Props> = (props) => {
setSelectedIds([])
} catch (e: any) {
toast.error(e.message || t(($) => $['api.actionFailed'], { ns: 'common' }))
+ throw e
}
}
@@ -253,8 +254,12 @@ const Annotation: FC<Props> = (props) => {
<LoadingPlaceholder className="h-full" />
) : total > 0 ? (
<List
+ appId={appDetail.id}
list={list}
- onRemove={handleRemove}
+ onRemoved={() => {
+ fetchList()
+ setControlUpdateList(Date.now())
+ }}
onView={handleView}
selectedIds={selectedIds}
onSelectedIdsChange={setSelectedIds}
diff --git a/web/app/components/app/annotation/list.tsx b/web/app/components/app/annotation/list.tsx
index 955bf449278..e3310f22e1f 100644
--- a/web/app/components/app/annotation/list.tsx
+++ b/web/app/components/app/annotation/list.tsx
@@ -1,38 +1,54 @@
'use client'
+import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import type { AnnotationItem } from './type'
+import { AlertDialog, AlertDialogTrigger } from '@langgenius/dify-ui/alert-dialog'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import { CheckboxGroup } from '@langgenius/dify-ui/checkbox-group'
import { IconButton } from '@langgenius/dify-ui/icon-button'
+import { useMutation } from '@tanstack/react-query'
import * as React from 'react'
import { useTranslation } from 'react-i18next'
import useTimestamp from '@/hooks/use-timestamp'
+import { consoleQuery } from '@/service/console'
import BatchAction from './batch-action'
-import RemoveAnnotationConfirmModal from './remove-annotation-confirm-modal'
+import { RemoveAnnotationConfirmContent } from './remove-annotation-confirm-modal'
type Props = Readonly<{
+ appId: string
list: AnnotationItem[]
onView: (item: AnnotationItem) => void
- onRemove: (id: string) => void
+ onRemoved: () => void
selectedIds: string[]
onSelectedIdsChange: (selectedIds: string[]) => void
onBatchDelete: () => Promise<void>
}>
type AnnotationTableRowProps = {
+ appId: string
item: AnnotationItem
formattedCreatedAt: string
onView: (item: AnnotationItem) => void
- onRemoveClick: (id: string) => void
+ onRemoved: () => void
}
function AnnotationTableRow({
+ appId,
item,
formattedCreatedAt,
onView,
- onRemoveClick,
+ onRemoved,
}: AnnotationTableRowProps) {
const { t } = useTranslation(['appDebug'])
const questionId = React.useId()
+ const removeConfirmActionsRef = React.useRef<AlertDialogActions>(null)
+ const removeMutation = useMutation(
+ consoleQuery.apps.byAppId.annotations.byAnnotationId.delete.mutationOptions({
+ onSuccess: () => {
+ removeConfirmActionsRef.current?.close()
+ onRemoved()
+ },
+ }),
+ )
return (
<tr
@@ -60,12 +76,29 @@ function AnnotationTableRow({
>
<span aria-hidden className="i-ri-edit-line size-4" />
</IconButton>
- <IconButton
- aria-label={t(($) => $['feature.annotation.remove'], { ns: 'appDebug' })}
- onClick={() => onRemoveClick(item.id)}
+ <AlertDialog
+ actionsRef={removeConfirmActionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && removeMutation.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
>
- <span aria-hidden className="i-ri-delete-bin-line size-4" />
- </IconButton>
+ <AlertDialogTrigger
+ render={
+ <IconButton
+ aria-label={t(($) => $['feature.annotation.remove'], { ns: 'appDebug' })}
+ >
+ <span aria-hidden className="i-ri-delete-bin-line size-4" />
+ </IconButton>
+ }
+ />
+ <RemoveAnnotationConfirmContent
+ isPending={removeMutation.isPending}
+ onRemove={() =>
+ removeMutation.mutate({ params: { app_id: appId, annotation_id: item.id } })
+ }
+ />
+ </AlertDialog>
</div>
</td>
</tr>
@@ -73,17 +106,16 @@ function AnnotationTableRow({
}
export function List({
+ appId,
list,
onView,
- onRemove,
+ onRemoved,
selectedIds,
onSelectedIdsChange,
onBatchDelete,
}: Props) {
const { t } = useTranslation(['appAnnotation', 'appLog', 'common'])
const { formatTime } = useTimestamp()
- const [currId, setCurrId] = React.useState<string | null>(null)
- const [showConfirmDelete, setShowConfirmDelete] = React.useState(false)
const annotationIds = list.map((item) => item.id)
return (
@@ -132,24 +164,14 @@ export function List({
item.created_at,
t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
)}
+ appId={appId}
onView={onView}
- onRemoveClick={(id) => {
- setCurrId(id)
- setShowConfirmDelete(true)
- }}
+ onRemoved={onRemoved}
/>
))}
</tbody>
</table>
</CheckboxGroup>
- <RemoveAnnotationConfirmModal
- isShow={showConfirmDelete}
- onHide={() => setShowConfirmDelete(false)}
- onRemove={() => {
- onRemove(currId as string)
- setShowConfirmDelete(false)
- }}
- />
</div>
{selectedIds.length > 0 && (
<BatchAction
diff --git a/web/app/components/app/annotation/remove-annotation-confirm-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/remove-annotation-confirm-modal/__tests__/index.spec.tsx
deleted file mode 100644
index 2279ef387ba..00000000000
--- a/web/app/components/app/annotation/remove-annotation-confirm-modal/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-import { fireEvent, render, screen } from '@testing-library/react'
-import * as React from 'react'
-import RemoveAnnotationConfirmModal from '../index'
-
-vi.mock('react-i18next', async () => {
- const { withSelectorKey } = await import('@/test/i18n-mock')
- return {
- useTranslation: () => ({
- t: withSelectorKey((key: string, options?: { ns?: string }) => {
- const translations: Record<string, string> = {
- 'feature.annotation.removeConfirm': 'Remove annotation?',
- 'operation.confirm': 'Confirm',
- 'operation.cancel': 'Cancel',
- }
- if (translations[key]) return translations[key]
- const prefix = options?.ns ? `${options.ns}.` : ''
- return `${prefix}${key}`
- }),
- }),
- }
-})
-
-beforeEach(() => {
- vi.clearAllMocks()
-})
-
-describe('RemoveAnnotationConfirmModal', () => {
- // Rendering behavior driven by isShow and translations
- describe('Rendering', () => {
- it('should display the confirm modal when visible', () => {
- // Arrange
- render(<RemoveAnnotationConfirmModal isShow onHide={vi.fn()} onRemove={vi.fn()} />)
-
- // Assert
- expect(screen.getByText('Remove annotation?')).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Cancel' })).toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'Confirm' })).toBeInTheDocument()
- })
-
- it('should not render modal content when hidden', () => {
- // Arrange
- render(<RemoveAnnotationConfirmModal isShow={false} onHide={vi.fn()} onRemove={vi.fn()} />)
-
- // Assert
- expect(screen.queryByText('Remove annotation?')).not.toBeInTheDocument()
- })
- })
-
- // User interactions with confirm and cancel buttons
- describe('Interactions', () => {
- it('should call onHide when cancel button is clicked', () => {
- const onHide = vi.fn()
- const onRemove = vi.fn()
- // Arrange
- render(<RemoveAnnotationConfirmModal isShow onHide={onHide} onRemove={onRemove} />)
-
- // Act
- fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
-
- // Assert
- expect(onHide).toHaveBeenCalledTimes(1)
- expect(onRemove).not.toHaveBeenCalled()
- })
-
- it('should call onRemove when confirm button is clicked', () => {
- const onHide = vi.fn()
- const onRemove = vi.fn()
- // Arrange
- render(<RemoveAnnotationConfirmModal isShow onHide={onHide} onRemove={onRemove} />)
-
- // Act
- fireEvent.click(screen.getByRole('button', { name: 'Confirm' }))
-
- // Assert
- expect(onRemove).toHaveBeenCalledTimes(1)
- expect(onHide).not.toHaveBeenCalled()
- })
- })
-})
diff --git a/web/app/components/app/annotation/remove-annotation-confirm-modal/index.tsx b/web/app/components/app/annotation/remove-annotation-confirm-modal/index.tsx
index b7f21b6414e..d9b7419850f 100644
--- a/web/app/components/app/annotation/remove-annotation-confirm-modal/index.tsx
+++ b/web/app/components/app/annotation/remove-annotation-confirm-modal/index.tsx
@@ -1,47 +1,40 @@
'use client'
-import type { FC } from 'react'
import {
- AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
AlertDialogFooter,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
-import * as React from 'react'
import { useTranslation } from 'react-i18next'
type Props = Readonly<{
- isShow: boolean
- onHide: () => void
+ isPending: boolean
onRemove: () => void
}>
-const RemoveAnnotationConfirmModal: FC<Props> = ({ isShow, onHide, onRemove }) => {
+export function RemoveAnnotationConfirmContent({ isPending, onRemove }: Props) {
const { t } = useTranslation(['appDebug', 'common'])
const title = t(($) => $['feature.annotation.removeConfirm'], { ns: 'appDebug' })
return (
- <AlertDialog open={isShow} onOpenChange={(open) => !open && onHide()}>
- <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"
- title={title}
- >
- {title}
- </AlertDialogTitle>
- </div>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton tone="destructive" onClick={onRemove}>
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ <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"
+ title={title}
+ >
+ {title}
+ </AlertDialogTitle>
+ </div>
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton tone="destructive" loading={isPending} onClick={onRemove}>
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
)
}
-export default React.memo(RemoveAnnotationConfirmModal)
diff --git a/web/app/components/header/account-setting/resource-access-token-page/__tests__/index.spec.tsx b/web/app/components/header/account-setting/resource-access-token-page/__tests__/index.spec.tsx
index 55f84e3b4e4..988965c4e9b 100644
--- a/web/app/components/header/account-setting/resource-access-token-page/__tests__/index.spec.tsx
+++ b/web/app/components/header/account-setting/resource-access-token-page/__tests__/index.spec.tsx
@@ -108,7 +108,8 @@ vi.mock('@/service/console', () => ({
relations: {
byRelationId: {
delete: {
- mutationOptions: () => ({
+ mutationOptions: (options?: object) => ({
+ ...options,
mutationFn: mocks.deleteResourceAccessTokenRelation,
}),
},
@@ -921,4 +922,32 @@ describe('ResourceAccessTokenPage', () => {
)
})
})
+
+ it('keeps the delete confirmation open until the request settles', async () => {
+ const user = userEvent.setup()
+ let settleDelete: () => void = () => {}
+ mocks.deleteResourceAccessTokenRelation.mockReturnValue(
+ new Promise<void>((resolve) => {
+ settleDelete = resolve
+ }),
+ )
+ renderWithQueryClient(<ResourceAccessTokenPage />)
+
+ await screen.findByText('Production clients')
+ await user.click(screen.getAllByRole('button', { name: 'common.operation.delete' })[0]!)
+ const dialog = screen.getByRole('alertdialog')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.delete' }))
+
+ await waitFor(() => {
+ expect(within(dialog).getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()
+ })
+ await user.keyboard('{Escape}')
+ expect(screen.getByRole('alertdialog')).toBeInTheDocument()
+
+ settleDelete()
+
+ await waitFor(() => {
+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()
+ })
+ })
})
diff --git a/web/app/components/header/account-setting/resource-access-token-page/delete-token-dialog.tsx b/web/app/components/header/account-setting/resource-access-token-page/delete-token-dialog.tsx
index c71a612a41e..437848b3df6 100644
--- a/web/app/components/header/account-setting/resource-access-token-page/delete-token-dialog.tsx
+++ b/web/app/components/header/account-setting/resource-access-token-page/delete-token-dialog.tsx
@@ -1,8 +1,6 @@
'use client'
-import type { ResourceAccessTokenRowResponse } from '@dify/contracts/api/console/resource-access-tokens/types.gen'
import {
- AlertDialog,
AlertDialogCancelButton,
AlertDialogConfirmButton,
AlertDialogContent,
@@ -10,61 +8,33 @@ import {
AlertDialogFooter,
AlertDialogTitle,
} from '@langgenius/dify-ui/alert-dialog'
-import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
-import { consoleQuery } from '@/service/console'
-import { useInvalidateResourceAccessTokens } from './use-invalidate-resource-access-tokens'
-export default function DeleteTokenDialog({
- row,
- onOpenChange,
+export function DeleteTokenDialogContent({
+ isPending,
+ onConfirm,
}: {
- row: ResourceAccessTokenRowResponse | null
- onOpenChange: (open: boolean) => void
+ isPending: boolean
+ onConfirm: () => void
}) {
const { t } = useTranslation(['common', 'accountSettings'])
- const invalidateResourceAccessTokens = useInvalidateResourceAccessTokens()
- const deleteMutation = useMutation(
- consoleQuery.resourceAccessTokens.byTokenId.relations.byRelationId.delete.mutationOptions(),
- )
-
- const confirmDelete = () => {
- if (!row) return
-
- deleteMutation.mutate(
- {
- params: {
- relation_id: row.relation_id,
- token_id: row.token_id,
- },
- },
- {
- onSuccess: () => {
- onOpenChange(false)
- void invalidateResourceAccessTokens()
- },
- },
- )
- }
return (
- <AlertDialog open={!!row} onOpenChange={onOpenChange}>
- <AlertDialogContent className="w-120 p-6 text-left" backdropProps={{ forceRender: true }}>
- <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">
- {t(($) => $['resourceAccessToken.deleteTitle'], { ns: 'accountSettings' })}
- </AlertDialogTitle>
- <AlertDialogDescription className="mt-2 system-sm-regular text-text-tertiary">
- {t(($) => $['resourceAccessToken.deleteDescription'], { ns: 'accountSettings' })}
- </AlertDialogDescription>
- <AlertDialogFooter className="mt-6 p-0">
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton disabled={deleteMutation.isPending} onClick={confirmDelete}>
- {t(($) => $['operation.delete'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
+ <AlertDialogContent className="w-120 p-6 text-left" backdropProps={{ forceRender: true }}>
+ <AlertDialogTitle className="title-2xl-semi-bold text-text-primary">
+ {t(($) => $['resourceAccessToken.deleteTitle'], { ns: 'accountSettings' })}
+ </AlertDialogTitle>
+ <AlertDialogDescription className="mt-2 system-sm-regular text-text-tertiary">
+ {t(($) => $['resourceAccessToken.deleteDescription'], { ns: 'accountSettings' })}
+ </AlertDialogDescription>
+ <AlertDialogFooter className="mt-6 p-0">
+ <AlertDialogCancelButton disabled={isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton loading={isPending} onClick={onConfirm}>
+ {t(($) => $['operation.delete'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
)
}
diff --git a/web/app/components/header/account-setting/resource-access-token-page/index.tsx b/web/app/components/header/account-setting/resource-access-token-page/index.tsx
index 5e0de8a2618..a90b6a868f8 100644
--- a/web/app/components/header/account-setting/resource-access-token-page/index.tsx
+++ b/web/app/components/header/account-setting/resource-access-token-page/index.tsx
@@ -1,6 +1,5 @@
'use client'
-import type { ResourceAccessTokenRowResponse } from '@dify/contracts/api/console/resource-access-tokens/types.gen'
import type { DialogState } from './types'
import { Button } from '@langgenius/dify-ui/button'
import { Pagination } from '@langgenius/dify-ui/pagination'
@@ -10,7 +9,6 @@ import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { SearchInput } from '@/app/components/base/search-input'
import { consoleQuery } from '@/service/console'
-import DeleteTokenDialog from './delete-token-dialog'
import ResourceAccessTokenDialog from './token-dialog'
import ResourceAccessTokenTable from './token-table'
@@ -22,7 +20,6 @@ export default function ResourceAccessTokenPage() {
const [searchText, setSearchText] = useState('')
const debouncedSearchText = useDebounce(searchText.trim(), { wait: 300 })
const [dialogState, setDialogState] = useState<DialogState | null>(null)
- const [deletingRow, setDeletingRow] = useState<ResourceAccessTokenRowResponse | null>(null)
const tokensQuery = useQuery(
consoleQuery.resourceAccessTokens.get.queryOptions({
placeholderData: keepPreviousData,
@@ -93,7 +90,6 @@ export default function ResourceAccessTokenPage() {
rows={rows}
isPending={tokensQuery.isPending}
onEdit={(row) => setDialogState({ mode: 'edit', row })}
- onDelete={setDeletingRow}
/>
)}
@@ -128,8 +124,6 @@ export default function ResourceAccessTokenPage() {
}}
/>
)}
-
- <DeleteTokenDialog row={deletingRow} onOpenChange={(open) => !open && setDeletingRow(null)} />
</div>
)
}
diff --git a/web/app/components/header/account-setting/resource-access-token-page/token-dialog.tsx b/web/app/components/header/account-setting/resource-access-token-page/token-dialog.tsx
index 237e3937a6f..2eaed6beb93 100644
--- a/web/app/components/header/account-setting/resource-access-token-page/token-dialog.tsx
+++ b/web/app/components/header/account-setting/resource-access-token-page/token-dialog.tsx
@@ -15,7 +15,6 @@ import { toast } from '@/app/notifications'
import { consoleQuery } from '@/service/console'
import { candidateKey } from './resource-key'
import ResourceSelector from './resource-selector'
-import { useInvalidateResourceAccessTokens } from './use-invalidate-resource-access-tokens'
export default function ResourceAccessTokenDialog({
open,
@@ -46,7 +45,6 @@ export default function ResourceAccessTokenDialog({
() => new Map(initialResources.map((resource) => [candidateKey(resource), resource])),
)
const [createdToken, setCreatedToken] = useState<string | null>(null)
- const invalidateResourceAccessTokens = useInvalidateResourceAccessTokens()
const createMutation = useMutation(consoleQuery.resourceAccessTokens.post.mutationOptions())
const updateMutation = useMutation(
consoleQuery.resourceAccessTokens.byTokenId.patch.mutationOptions(),
@@ -83,12 +81,7 @@ export default function ResourceAccessTokenDialog({
token_id: state.row.tokenId,
},
},
- {
- onSuccess: () => {
- void invalidateResourceAccessTokens()
- onSaved()
- },
- },
+ { onSuccess: onSaved },
)
return
}
@@ -103,7 +96,6 @@ export default function ResourceAccessTokenDialog({
{
onSuccess: (result) => {
toast.success(t(($) => $['resourceAccessToken.created'], { ns: 'accountSettings' }))
- void invalidateResourceAccessTokens()
setCreatedToken(result.token)
},
},
diff --git a/web/app/components/header/account-setting/resource-access-token-page/token-table-row.tsx b/web/app/components/header/account-setting/resource-access-token-page/token-table-row.tsx
index 0da96f29895..a23989c610d 100644
--- a/web/app/components/header/account-setting/resource-access-token-page/token-table-row.tsx
+++ b/web/app/components/header/account-setting/resource-access-token-page/token-table-row.tsx
@@ -1,12 +1,18 @@
'use client'
import type { ResourceAccessTokenRowResponse } from '@dify/contracts/api/console/resource-access-tokens/types.gen'
+import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
import type { TFunction } from 'i18next'
import type { TokenTableRow } from './types'
+import { AlertDialog, AlertDialogTrigger } from '@langgenius/dify-ui/alert-dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Infotip, InfotipContent, InfotipTrigger } from '@langgenius/dify-ui/infotip'
+import { useMutation } from '@tanstack/react-query'
+import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
import useTimestamp from '@/hooks/use-timestamp'
+import { consoleQuery } from '@/service/console'
+import { DeleteTokenDialogContent } from './delete-token-dialog'
const getResourceSummary = (
relations: ResourceAccessTokenRowResponse[],
@@ -44,14 +50,18 @@ const getResourceSummary = (
export default function ResourceAccessTokenRow({
row,
onEdit,
- onDelete,
}: {
row: TokenTableRow
onEdit: (row: TokenTableRow) => void
- onDelete: (row: ResourceAccessTokenRowResponse) => void
}) {
const { t } = useTranslation(['common', 'accountSettings', 'time'])
const { formatTime } = useTimestamp()
+ const deleteDialogActionsRef = useRef<AlertDialogActions>(null)
+ const deleteMutation = useMutation(
+ consoleQuery.resourceAccessTokens.byTokenId.relations.byRelationId.delete.mutationOptions({
+ onSuccess: () => deleteDialogActionsRef.current?.close(),
+ }),
+ )
const editRow = row.relations[0]
const resourceSummary = getResourceSummary(row.relations, t)
@@ -135,15 +145,37 @@ export default function ResourceAccessTokenRow({
>
<span aria-hidden className="i-ri-edit-line size-4" />
</IconButton>
- <IconButton
- size="sm"
- variant="ghost"
- tone="destructive"
- aria-label={t(($) => $['operation.delete'], { ns: 'common' })}
- onClick={() => onDelete(editRow)}
+ <AlertDialog
+ actionsRef={deleteDialogActionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && deleteMutation.isPending && details.reason !== 'imperative-action')
+ details.cancel()
+ }}
>
- <span aria-hidden className="i-ri-delete-bin-line size-4" />
- </IconButton>
+ <AlertDialogTrigger
+ render={
+ <IconButton
+ size="sm"
+ variant="ghost"
+ tone="destructive"
+ aria-label={t(($) => $['operation.delete'], { ns: 'common' })}
+ >
+ <span aria-hidden className="i-ri-delete-bin-line size-4" />
+ </IconButton>
+ }
+ />
+ <DeleteTokenDialogContent
+ isPending={deleteMutation.isPending}
+ onConfirm={() =>
+ deleteMutation.mutate({
+ params: {
+ relation_id: editRow.relation_id,
+ token_id: editRow.token_id,
+ },
+ })
+ }
+ />
+ </AlertDialog>
</div>
</td>
</tr>
diff --git a/web/app/components/header/account-setting/resource-access-token-page/token-table.tsx b/web/app/components/header/account-setting/resource-access-token-page/token-table.tsx
index d706f0a923b..be7e41a8adc 100644
--- a/web/app/components/header/account-setting/resource-access-token-page/token-table.tsx
+++ b/web/app/components/header/account-setting/resource-access-token-page/token-table.tsx
@@ -34,12 +34,10 @@ export default function ResourceAccessTokenTable({
rows,
isPending,
onEdit,
- onDelete,
}: {
rows: ResourceAccessTokenRowResponse[] | undefined
isPending: boolean
onEdit: (row: TokenTableRow) => void
- onDelete: (row: ResourceAccessTokenRowResponse) => void
}) {
const { t } = useTranslation(['accountSettings'])
const tokenRows = useMemo(() => getTokenRows(rows ?? []), [rows])
@@ -92,12 +90,7 @@ export default function ResourceAccessTokenTable({
)}
{!isPending &&
tokenRows.map((row) => (
- <ResourceAccessTokenRow
- key={row.tokenId}
- row={row}
- onEdit={onEdit}
- onDelete={onDelete}
- />
+ <ResourceAccessTokenRow key={row.tokenId} row={row} onEdit={onEdit} />
))}
{!isPending && tokenRows.length === 0 && (
<tr>
diff --git a/web/app/components/header/account-setting/resource-access-token-page/use-invalidate-resource-access-tokens.ts b/web/app/components/header/account-setting/resource-access-token-page/use-invalidate-resource-access-tokens.ts
deleted file mode 100644
index 6516ecbb7e0..00000000000
--- a/web/app/components/header/account-setting/resource-access-token-page/use-invalidate-resource-access-tokens.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-'use client'
-
-import { useQueryClient } from '@tanstack/react-query'
-import { consoleQuery } from '@/service/console'
-
-export function useInvalidateResourceAccessTokens() {
- const queryClient = useQueryClient()
-
- return () =>
- queryClient.invalidateQueries({
- queryKey: consoleQuery.resourceAccessTokens.get.key(),
- })
-}
diff --git a/web/service/annotation.ts b/web/service/annotation.ts
index 5bc29719a2a..fe7a8dcb7e7 100644
--- a/web/service/annotation.ts
+++ b/web/service/annotation.ts
@@ -103,7 +103,3 @@ export const fetchHitHistoryList = (
) => {
return get(`apps/${appId}/annotations/${annotationId}/hit-histories`, { params })
}
-
-export const clearAllAnnotations = (appId: string): Promise<any> => {
- return del(`apps/${appId}/annotations`)
-}
diff --git a/web/service/console/client.spec.ts b/web/service/console/client.spec.ts
index c19415355ea..636bb6f6771 100644
--- a/web/service/console/client.spec.ts
+++ b/web/service/console/client.spec.ts
@@ -2254,3 +2254,65 @@ describe('workspace skill deletion cache', () => {
}
})
})
+
+describe('consoleQuery resourceAccessTokens mutation defaults', () => {
+ const createdToken = { data: [], token: 'token' }
+ const tokenList = { data: [], has_more: false, limit: 20, page: 1, total: 0 }
+
+ it('should refresh the token list after a token is created, updated, or deleted', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const context = createMutationContext(queryClient)
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue()
+ const tokens = consoleQuery.resourceAccessTokens
+
+ await tokens.post
+ .mutationOptions()
+ .onSettled?.(
+ createdToken,
+ null,
+ { body: { name: 'Token', resources: [] } },
+ undefined,
+ context,
+ )
+ await tokens.byTokenId.patch
+ .mutationOptions()
+ .onSettled?.(
+ tokenList,
+ null,
+ { params: { token_id: 'token-1' }, body: { name: 'Token', resources: [] } },
+ undefined,
+ context,
+ )
+ await tokens.byTokenId.relations.byRelationId.delete
+ .mutationOptions()
+ .onSettled?.(
+ undefined,
+ null,
+ { params: { token_id: 'token-1', relation_id: 'relation-1' } },
+ undefined,
+ context,
+ )
+
+ expect(invalidateQueries).toHaveBeenCalledTimes(3)
+ expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: tokens.get.key() })
+ })
+
+ it('should leave the token list alone when the mutation fails', async () => {
+ const consoleQuery = await loadConsoleQuery()
+ const queryClient = new QueryClient()
+ const invalidateQueries = vi.spyOn(queryClient, 'invalidateQueries').mockResolvedValue()
+
+ await consoleQuery.resourceAccessTokens.byTokenId.relations.byRelationId.delete
+ .mutationOptions()
+ .onSettled?.(
+ undefined,
+ new Error('failed'),
+ { params: { token_id: 'token-1', relation_id: 'relation-1' } },
+ undefined,
+ createMutationContext(queryClient),
+ )
+
+ expect(invalidateQueries).not.toHaveBeenCalled()
+ })
+})
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index 083d507245d..2cd57de4050 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -1067,6 +1067,44 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
},
},
+ resourceAccessTokens: {
+ post: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.resourceAccessTokens.get.key(),
+ })
+ },
+ },
+ },
+ byTokenId: {
+ patch: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.resourceAccessTokens.get.key(),
+ })
+ },
+ },
+ },
+ relations: {
+ byRelationId: {
+ delete: {
+ mutationOptions: {
+ onSettled: (_data, error, _variables, _result, context) => {
+ if (error) return
+ void context.client.invalidateQueries({
+ queryKey: consoleQuery.resourceAccessTokens.get.key(),
+ })
+ },
+ },
+ },
+ },
+ },
+ },
+ },
tags: {
post: {
mutationOptions: {