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.

fix(web): preserve annotation editor drafts and dialog sessions (#44825)

yyh7cd11ab7ab60
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.json
index 91591e9713c..339bc8ffcdd 100644
--- a/oxlint-suppressions.json
+++ b/oxlint-suppressions.json
@@ -203,30 +203,10 @@
}
},
"web/app/components/app/annotation/edit-annotation-modal/edit-item/index.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 6
- },
- "eslint-react/set-state-in-effect": {
- "count": 1
- },
- "jsx-a11y/click-events-have-key-events": {
- "count": 1
- },
- "jsx-a11y/no-autofocus": {
- "count": 1
- },
- "jsx-a11y/no-static-element-interactions": {
- "count": 1
- },
"react/only-export-components": {
"count": 1
}
},
- "web/app/components/app/annotation/edit-annotation-modal/index.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 3
- }
- },
"web/app/components/app/annotation/empty-element.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 1
@@ -245,19 +225,6 @@
"count": 1
}
},
- "web/app/components/app/annotation/list.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 20
- }
- },
- "web/app/components/app/annotation/view-annotation-modal/index.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 27
- },
- "eslint-react/set-state-in-effect": {
- "count": 5
- }
- },
"web/app/components/app/app-access-control/access-control-dialog.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 1
@@ -774,11 +741,6 @@
"count": 1
}
},
- "web/app/components/app/log/conversation-detail.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 2
- }
- },
"web/app/components/app/log/empty-element.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 1
@@ -1119,11 +1081,6 @@
"count": 3
}
},
- "web/app/components/base/chat/chat/answer/operation.tsx": {
- "better-tailwindcss/enforce-logical-properties": {
- "count": 5
- }
- },
"web/app/components/base/chat/chat/answer/suggested-questions.tsx": {
"better-tailwindcss/enforce-logical-properties": {
"count": 2
diff --git a/web/app/components/app/annotation/__tests__/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsx
index 38de20ec831..5f435ce20c0 100644
--- a/web/app/components/app/annotation/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/index.spec.tsx
@@ -45,6 +45,7 @@ vi.mock('@/service/console', async (importOriginal) => {
'apps.byAppId.annotations.count.get': () => ({ count: 0 }),
'apps.byAppId.annotations.post': (input) => api.add(input),
'apps.byAppId.annotations.byAnnotationId.delete': (input) => api.remove(input),
+ 'apps.byAppId.annotations.byAnnotationId.post': (input) => api.edit(input),
'apps.byAppId.annotations.delete': (input) => api.batchRemove(input),
}),
consoleClient: withConsoleClientResponses(actual.consoleClient, {
@@ -243,7 +244,7 @@ it('keeps a failed batch deletion open for retry and clears the selection after
})
})
-it('saves edits from the detail drawer and shows them when reopened', async () => {
+it('saves edits from the detail dialog and shows them when reopened', async () => {
annotations = [item]
const user = setup()
await user.click(await screen.findByRole('button', { name: 'appDebug.feature.annotation.edit' }))
@@ -251,6 +252,9 @@ it('saves edits from the detail drawer and shows them when reopened', async () =
name: 'appAnnotation.viewModal.annotatedResponse',
})
await user.click(within(dialog).getAllByRole('button', { name: 'common.operation.edit' })[0]!)
+ await user.clear(
+ within(dialog).getByRole('textbox', { name: 'appAnnotation.editModal.yourQuery' }),
+ )
await user.type(
within(dialog).getByRole('textbox', { name: 'appAnnotation.editModal.yourQuery' }),
'Edited question',
@@ -274,7 +278,7 @@ it('saves edits from the detail drawer and shows them when reopened', async () =
).toBeVisible()
})
-it('removes an annotation through its detail drawer and closes it', async () => {
+it('removes an annotation through its detail dialog and closes it', async () => {
annotations = [item]
const user = setup()
await user.click(await screen.findByRole('button', { name: 'appDebug.feature.annotation.edit' }))
@@ -370,3 +374,37 @@ it('enables replies with the selected model and saves the score to the returned
body: { score_threshold: 0.51 },
})
})
+
+it('keeps the editor and drafts mounted through repeated refreshes of empty filtered results', async () => {
+ annotations = [item]
+ api.edit.mockImplementation(async ({ body }) => {
+ annotations = []
+ return { ...item, question: body.question, answer: body.answer }
+ })
+ const user = setup()
+ await user.click(await screen.findByRole('button', { name: 'Question 1' }))
+ const dialog = screen.getByRole('dialog', { name: 'appAnnotation.viewModal.annotatedResponse' })
+ const querySection = within(dialog).getByRole('region', {
+ name: 'appAnnotation.editModal.queryName',
+ })
+ const answerSection = within(dialog).getByRole('region', {
+ name: 'appAnnotation.editModal.answerName',
+ })
+ await user.click(within(querySection).getByRole('button', { name: 'common.operation.edit' }))
+ await user.clear(within(querySection).getByRole('textbox'))
+ await user.type(within(querySection).getByRole('textbox'), 'No longer matches the filter')
+ await user.click(within(querySection).getByRole('button', { name: 'common.operation.save' }))
+ await waitFor(() => expect(within(querySection).queryByRole('textbox')).not.toBeInTheDocument())
+ await user.click(within(querySection).getByRole('button', { name: 'common.operation.edit' }))
+ await user.type(within(querySection).getByRole('textbox'), ' unsaved question draft')
+ await user.click(within(answerSection).getByRole('button', { name: 'common.operation.edit' }))
+ await user.clear(within(answerSection).getByRole('textbox'))
+ await user.type(within(answerSection).getByRole('textbox'), 'Second saved field')
+ await user.click(within(answerSection).getByRole('button', { name: 'common.operation.save' }))
+ await waitFor(() => expect(within(answerSection).queryByRole('textbox')).not.toBeInTheDocument())
+ expect(dialog).toBeVisible()
+ expect(within(querySection).getByRole('textbox')).toHaveValue(
+ 'No longer matches the filter unsaved question draft',
+ )
+ expect(api.edit).toHaveBeenCalledTimes(2)
+})
diff --git a/web/app/components/app/annotation/__tests__/list.spec.tsx b/web/app/components/app/annotation/__tests__/list.spec.tsx
index 1a7faace1f0..02bdd86786b 100644
--- a/web/app/components/app/annotation/__tests__/list.spec.tsx
+++ b/web/app/components/app/annotation/__tests__/list.spec.tsx
@@ -36,16 +36,16 @@ describe('List', () => {
vi.clearAllMocks()
})
- it('should render annotation rows and call onView when clicking a row', async () => {
+ it('should render annotation rows and call onEdited when clicking a row', async () => {
const user = userEvent.setup()
const item = createAnnotation()
- const onView = vi.fn()
+ const onEdited = vi.fn()
render(
<List
appId="app-1"
list={[item]}
- onView={onView}
+ onEdited={onEdited}
onRemoved={vi.fn()}
selectedIds={[]}
onSelectedIdsChange={vi.fn()}
@@ -55,7 +55,9 @@ describe('List', () => {
await user.click(screen.getByText(item.question!))
- expect(onView).toHaveBeenCalledWith(item)
+ expect(
+ screen.getByRole('dialog', { name: 'appAnnotation.viewModal.annotatedResponse' }),
+ ).toBeInTheDocument()
expect(mockFormatTime).toHaveBeenCalledWith(item.created_at, 'appLog.dateTimeFormat')
})
@@ -65,7 +67,7 @@ describe('List', () => {
createAnnotation({ id: 'a', question: 'A' }),
createAnnotation({ id: 'b', question: 'B' }),
]
- const onView = vi.fn()
+ const onEdited = vi.fn()
const onSelectedIdsChange = vi.fn()
function ControlledList() {
const [selectedIds, setSelectedIds] = React.useState<string[]>([])
@@ -73,7 +75,7 @@ describe('List', () => {
<List
appId="app-1"
list={list}
- onView={onView}
+ onEdited={onEdited}
onRemoved={vi.fn()}
selectedIds={selectedIds}
onSelectedIdsChange={(next) => {
@@ -93,7 +95,7 @@ describe('List', () => {
expect(onSelectedIdsChange).toHaveBeenLastCalledWith(['a', 'b'])
await user.click(screen.getByRole('checkbox', { name: 'common.operation.selectAll' }))
expect(onSelectedIdsChange).toHaveBeenLastCalledWith([])
- expect(onView).not.toHaveBeenCalled()
+ expect(onEdited).not.toHaveBeenCalled()
})
it('should confirm before removing an annotation and expose batch actions', async () => {
@@ -105,7 +107,7 @@ describe('List', () => {
<List
appId="app-1"
list={[item]}
- onView={vi.fn()}
+ onEdited={vi.fn()}
onRemoved={onRemoved}
selectedIds={[item.id]}
onSelectedIdsChange={vi.fn()}
@@ -144,7 +146,7 @@ describe('List', () => {
<List
appId="app-1"
list={[item]}
- onView={vi.fn()}
+ onEdited={vi.fn()}
onRemoved={vi.fn()}
selectedIds={[]}
onSelectedIdsChange={vi.fn()}
diff --git a/web/app/components/app/annotation/add-annotation-modal/index.tsx b/web/app/components/app/annotation/add-annotation-modal/index.tsx
index 3b9dbaa67f2..ed244650ea3 100644
--- a/web/app/components/app/annotation/add-annotation-modal/index.tsx
+++ b/web/app/components/app/annotation/add-annotation-modal/index.tsx
@@ -1,6 +1,7 @@
'use client'
import type { CreateAnnotationPayload } from '@dify/contracts/api/console/apps/types.gen'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
import { Button } from '@langgenius/dify-ui/button'
import { Checkbox } from '@langgenius/dify-ui/checkbox'
import {
@@ -15,7 +16,6 @@ import {
DialogPortal,
DialogTitle,
DialogTrigger,
- DialogViewport,
} from '@langgenius/dify-ui/dialog'
import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Form } from '@langgenius/dify-ui/form'
@@ -29,19 +29,24 @@ import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleQuery } from '@/service/console'
import robotAvatar from '../assets/robot-avatar.svg'
-type Props = {
+type AddAnnotationDialogProps = {
appId: string
onAdded: () => void
}
-type FormProps = {
+type AddAnnotationDialogPopupProps = {
isPending: boolean
isError: boolean
onSave: (body: CreateAnnotationPayload, onSuccess: () => void) => void
onClose: () => void
}
-function AddAnnotationForm({ isPending, isError, onSave, onClose }: FormProps) {
+function AddAnnotationDialogPopup({
+ isPending,
+ isError,
+ onSave,
+ onClose,
+}: AddAnnotationDialogPopupProps) {
const { t } = useTranslation(['appAnnotation', 'common'])
const deploymentEdition = useAtomValue(deploymentEditionAtom)
const quota = useQuery(
@@ -65,7 +70,7 @@ function AddAnnotationForm({ isPending, isError, onSave, onClose }: FormProps) {
return (
<DialogPopup
initialFocus={questionRef}
- className="absolute inset-e-2 top-16 bottom-3 flex min-h-0 w-120 max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg text-text-primary shadow-xl"
+ className="fixed inset-e-2 top-16 bottom-3 flex min-h-0 w-120 max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg text-text-primary shadow-xl"
>
<DialogHeader>
<DialogTitle>{t(($) => $['addModal.title'], { ns: 'appAnnotation' })}</DialogTitle>
@@ -166,9 +171,9 @@ function AddAnnotationForm({ isPending, isError, onSave, onClose }: FormProps) {
)
}
-export default function AddAnnotationDialog({ appId, onAdded }: Props) {
+export default function AddAnnotationDialog({ appId, onAdded }: AddAnnotationDialogProps) {
const { t } = useTranslation(['appAnnotation'])
- const [open, setOpen] = useState(false)
+ const actionsRef = useRef<DialogActions>(null)
const creation = useMutation(
consoleQuery.apps.byAppId.annotations.post.mutationOptions({
context: { silent: true },
@@ -178,14 +183,12 @@ export default function AddAnnotationDialog({ appId, onAdded }: Props) {
return (
<Dialog
- open={open}
+ actionsRef={actionsRef}
disablePointerDismissal
onOpenChange={(nextOpen, details) => {
- if (!nextOpen && creation.isPending) {
+ if (!nextOpen && creation.isPending && details.reason !== 'imperative-action') {
details.cancel()
- return
}
- setOpen(nextOpen)
}}
onOpenChangeComplete={(nextOpen) => {
if (!nextOpen) creation.reset()
@@ -197,16 +200,14 @@ export default function AddAnnotationDialog({ appId, onAdded }: Props) {
</DialogTrigger>
<DialogPortal>
<DialogBackdrop />
- <DialogViewport>
- <AddAnnotationForm
- isPending={creation.isPending}
- isError={creation.isError}
- onSave={(body, onSuccess) => {
- creation.mutate({ params: { app_id: appId }, body }, { onSuccess })
- }}
- onClose={() => setOpen(false)}
- />
- </DialogViewport>
+ <AddAnnotationDialogPopup
+ isPending={creation.isPending}
+ isError={creation.isError}
+ onSave={(body, onSuccess) => {
+ creation.mutate({ params: { app_id: appId }, body }, { onSuccess })
+ }}
+ onClose={() => actionsRef.current?.close()}
+ />
</DialogPortal>
</Dialog>
)
diff --git a/web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx
index 1544e848b14..27cc78a37ae 100644
--- a/web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/edit-annotation-modal/__tests__/index.spec.tsx
@@ -1,227 +1,235 @@
-import { render, screen, waitFor } from '@testing-library/react'
+import type { consoleClient } from '@/service/console'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import { toast } from '@/app/notifications'
-import EditAnnotationModal from '../index'
-
-const { mockEditAnnotation } = vi.hoisted(() => ({
- mockEditAnnotation: vi.fn(),
-}))
-
-vi.mock('@/service/console', () => ({
- consoleClient: {
- apps: { byAppId: { annotations: { byAnnotationId: { post: mockEditAnnotation } } } },
- },
-}))
-
-vi.mock('@/hooks/use-timestamp', () => ({
- default: () => ({
- formatTime: () => '2023-12-01 10:30:00',
- }),
-}))
-
-vi.mock('@/app/components/billing/annotation-full', () => ({
- default: () => <div data-testid="annotation-full" />,
+import { consoleQuery } from '@/service/console'
+import { renderWithConsoleQuery, seedFeatures } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { List } from '../../list'
+import EditAnnotationDialog from '../index'
+
+const api = vi.hoisted(() => ({
+ edit: vi.fn<typeof consoleClient.apps.byAppId.annotations.byAnnotationId.post>(),
+ remove: vi.fn<typeof consoleClient.apps.byAppId.annotations.byAnnotationId.delete>(),
}))
-
-const toastSuccessSpy = vi.spyOn(toast, 'success').mockReturnValue('toast-success')
-const toastErrorSpy = vi.spyOn(toast, 'error').mockReturnValue('toast-error')
-
-describe('EditAnnotationModal', () => {
- const defaultProps = {
- isShow: true,
- onHide: vi.fn(),
- appId: 'test-app-id',
- annotationId: 'test-annotation-id',
- query: 'Test query',
- answer: 'Test answer',
- onEdited: vi.fn(),
-
- onRemove: vi.fn(),
+vi.mock('@/hooks/use-timestamp', () => ({ default: () => ({ formatTime: () => 'Created time' }) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.annotations.byAnnotationId.post': (input) => api.edit(input),
+ 'apps.byAppId.annotations.byAnnotationId.delete': (input) => api.remove(input),
+ }),
}
+})
- beforeEach(() => {
- vi.clearAllMocks()
- mockEditAnnotation.mockResolvedValue({})
- })
-
- afterAll(() => {
- toastSuccessSpy.mockRestore()
- toastErrorSpy.mockRestore()
- })
-
- describe('Rendering', () => {
- it('should not render modal when isShow is false', () => {
- const props = { ...defaultProps, isShow: false }
-
- render(<EditAnnotationModal {...props} />)
-
- expect(screen.queryByText('appAnnotation.editModal.title')).not.toBeInTheDocument()
- })
- })
-
- describe('API Calls', () => {
- it('should call editAnnotation when updating existing annotation', async () => {
- const mockOnEdited = vi.fn()
- const props = {
- ...defaultProps,
- annotationId: 'test-annotation-id',
- onEdited: mockOnEdited,
- }
- const user = userEvent.setup()
-
- render(<EditAnnotationModal {...props} />)
-
- const editLinks = screen.getAllByText(/common\.operation\.edit/i)
- await user.click(editLinks[0]!)
-
- const textarea = screen.getByRole('textbox')
- await user.clear(textarea)
- await user.type(textarea, 'Modified query')
-
- const saveButton = screen.getByRole('button', { name: 'common.operation.save' })
- await user.click(saveButton)
+beforeEach(() => {
+ api.edit.mockResolvedValue(undefined)
+ api.remove.mockResolvedValue(undefined)
+})
- expect(mockEditAnnotation).toHaveBeenCalledWith({
- params: { app_id: 'test-app-id', annotation_id: 'test-annotation-id' },
- body: { question: 'Modified query', answer: 'Test answer' },
- })
- await waitFor(() =>
- expect(mockOnEdited).toHaveBeenCalledWith('Modified query', 'Test answer'),
- )
- expect(toastSuccessSpy).toHaveBeenCalledWith('common.api.actionSuccess')
+async function setup(source: 'chat' | 'list', onlyEditResponse = false) {
+ const onEdited = vi.fn()
+ const onRemoved = vi.fn()
+ const view = renderWithConsoleQuery(
+ source === 'chat' ? (
+ <div>
+ <button>Copy answer</button>
+ <EditAnnotationDialog
+ appId="app-id"
+ annotationId="annotation-id"
+ question="Original question"
+ answer="Original answer"
+ onEdited={onEdited}
+ onRemoved={onRemoved}
+ onlyEditResponse={onlyEditResponse}
+ />
+ </div>
+ ) : (
+ <List
+ appId="app-id"
+ list={[
+ {
+ id: 'annotation-id',
+ question: 'Original question',
+ answer: 'Original answer',
+ created_at: 1700000000,
+ hit_count: 0,
+ },
+ ]}
+ onEdited={onEdited}
+ onRemoved={onRemoved}
+ selectedIds={[]}
+ onSelectedIdsChange={vi.fn()}
+ onBatchDelete={vi.fn()}
+ />
+ ),
+ )
+ const user = userEvent.setup()
+ const trigger = screen.getByRole('button', { name: 'appDebug.feature.annotation.edit' })
+ await user.click(trigger)
+ const dialog = screen.getByRole('dialog')
+ return { ...view, user, dialog, trigger, onEdited, onRemoved }
+}
+
+async function editField(
+ user: ReturnType<typeof userEvent.setup>,
+ name: 'queryName' | 'answerName',
+ value: string,
+) {
+ const section = screen.getByRole('region', { name: `appAnnotation.editModal.${name}` })
+ await user.click(within(section).getByRole('button', { name: 'common.operation.edit' }))
+ const input = within(section).getByRole('textbox')
+ await user.clear(input)
+ if (value) await user.type(input, value)
+ return {
+ input,
+ section,
+ save: within(section).getByRole('button', { name: 'common.operation.save' }),
+ }
+}
+
+describe.each(['chat', 'list'] as const)('%s annotation editor', (source) => {
+ it('retains failed drafts, blocks dismissal and duplicate saves while pending, and retries', async () => {
+ const pending = createDeferred<undefined>()
+ api.edit.mockReturnValueOnce(pending.promise)
+ const { user, dialog, onEdited } = await setup(source)
+ const { input, save } = await editField(user, 'answerName', 'Corrected answer')
+ await user.click(save)
+ expect(input).toHaveAttribute('readonly')
+ expect(within(dialog).getByRole('button', { name: 'common.operation.close' })).toBeDisabled()
+ await user.keyboard('{Escape}')
+ await user.click(save)
+ expect(api.edit).toHaveBeenCalledTimes(1)
+ expect(dialog).toBeInTheDocument()
+ pending.reject(new Error('Offline'))
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.api.actionFailed')
+ expect(input).toHaveValue('Corrected answer')
+ expect(onEdited).not.toHaveBeenCalled()
+ await user.click(save)
+ await waitFor(() => expect(screen.queryByRole('textbox')).not.toBeInTheDocument())
+ expect(onEdited).toHaveBeenCalledOnce()
+ expect(api.edit).toHaveBeenLastCalledWith({
+ params: { app_id: 'app-id', annotation_id: 'annotation-id' },
+ body: { question: 'Original question', answer: 'Corrected answer' },
})
})
- describe('State Management', () => {
- it('should call onRemove when removal is confirmed', async () => {
- const mockOnRemove = vi.fn()
- const props = {
- ...defaultProps,
- annotationId: 'test-annotation-id',
- onRemove: mockOnRemove,
- }
- const user = userEvent.setup()
-
- render(<EditAnnotationModal {...props} />)
-
- await user.click(screen.getByText('appAnnotation.editModal.removeThisCache'))
-
- const confirmButton = screen.getByRole('button', { name: 'common.operation.confirm' })
- expect(mockOnRemove).not.toHaveBeenCalled()
- await user.click(confirmButton)
-
- expect(mockOnRemove).toHaveBeenCalled()
+ it('uses the last successful values when editing the other field and restoring an edit', async () => {
+ const { user } = await setup(source)
+ const question = await editField(user, 'queryName', 'Saved question')
+ await user.click(question.save)
+ await waitFor(() =>
+ expect(within(question.section).queryByRole('textbox')).not.toBeInTheDocument(),
+ )
+ const answer = await editField(user, 'answerName', 'Saved answer')
+ await user.click(answer.save)
+ await waitFor(() =>
+ expect(within(answer.section).queryByRole('textbox')).not.toBeInTheDocument(),
+ )
+ expect(api.edit).toHaveBeenLastCalledWith({
+ params: { app_id: 'app-id', annotation_id: 'annotation-id' },
+ body: { question: 'Saved question', answer: 'Saved answer' },
})
-
- it('should hide confirm modal when removal is cancelled', async () => {
- const props = {
- ...defaultProps,
- annotationId: 'test-annotation-id',
- }
- const user = userEvent.setup()
-
- render(<EditAnnotationModal {...props} />)
- await user.click(screen.getByText('appAnnotation.editModal.removeThisCache'))
- expect(screen.getByText('appDebug.feature.annotation.removeConfirm'))!.toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- expect(props.onRemove).not.toHaveBeenCalled()
- expect(props.onHide).not.toHaveBeenCalled()
-
- await waitFor(() => {
- expect(
- screen.queryByText('appDebug.feature.annotation.removeConfirm'),
- ).not.toBeInTheDocument()
- })
+ await user.click(
+ within(question.section).getByRole('button', { name: 'common.operation.delete' }),
+ )
+ await waitFor(() =>
+ expect(within(question.section).queryByText('Saved question')).not.toBeInTheDocument(),
+ )
+ expect(api.edit).toHaveBeenLastCalledWith({
+ params: { app_id: 'app-id', annotation_id: 'annotation-id' },
+ body: { question: 'Original question', answer: 'Saved answer' },
})
})
- describe('Edge Cases', () => {
- it('edits only the answer when the question is read-only', async () => {
- const user = userEvent.setup()
-
- const props = {
- ...defaultProps,
- onlyEditResponse: true,
- }
-
- render(<EditAnnotationModal {...props} />)
-
- const editLinks = screen.queryAllByText(/common\.operation\.edit/i)
- expect(editLinks).toHaveLength(1)
- await user.click(editLinks[0]!)
- await user.clear(screen.getByRole('textbox'))
- await user.type(screen.getByRole('textbox'), 'Updated answer')
- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(mockEditAnnotation).toHaveBeenCalledWith(
- expect.objectContaining({ body: { question: 'Test query', answer: 'Updated answer' } }),
- )
- })
+ it('validates empty edits, cancels drafts, and starts a clean session after closing', async () => {
+ const { user, trigger, dialog } = await setup(source)
+ const { section, save } = await editField(user, 'answerName', '')
+ await user.click(save)
+ expect(
+ await within(section).findByText('appAnnotation.errorMessage.answerRequired'),
+ ).toBeVisible()
+ expect(api.edit).not.toHaveBeenCalled()
+ await user.click(within(section).getByRole('button', { name: 'common.operation.cancel' }))
+ expect(within(section).getByRole('button', { name: 'common.operation.edit' })).toHaveFocus()
+ await editField(user, 'answerName', 'Discarded draft')
+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(trigger)
+ const reopened = screen.getByRole('region', { name: 'appAnnotation.editModal.answerName' })
+ await user.click(within(reopened).getByRole('button', { name: 'common.operation.edit' }))
+ expect(within(reopened).getByRole('textbox')).toHaveValue('Original answer')
})
- describe('Error Handling', () => {
- it('should show error toast and skip callbacks when editAnnotation fails', async () => {
- const mockOnEdited = vi.fn()
- const props = {
- ...defaultProps,
- annotationId: 'test-annotation-id',
- onEdited: mockOnEdited,
- }
- const user = userEvent.setup()
-
- mockEditAnnotation.mockRejectedValueOnce(new Error('API Error'))
-
- render(<EditAnnotationModal {...props} />)
-
- const editLinks = screen.getAllByText(/common\.operation\.edit/i)
- await user.click(editLinks[0]!)
-
- const textarea = screen.getByRole('textbox')
- await user.clear(textarea)
- await user.type(textarea, 'Modified query')
-
- const saveButton = screen.getByRole('button', { name: 'common.operation.save' })
- await user.click(saveButton)
-
- await waitFor(() => {
- expect(toastErrorSpy).toHaveBeenCalledWith('API Error')
- })
- expect(mockOnEdited).not.toHaveBeenCalled()
-
- expect(screen.getByRole('textbox'))!.toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'common.operation.save' }))!.toBeInTheDocument()
+ it('waits for deletion, keeps both dialogs on failure, and notifies only after success', async () => {
+ const pending = createDeferred<void>()
+ api.remove.mockReturnValueOnce(pending.promise)
+ const { user, onRemoved } = await setup(source)
+ await user.click(
+ screen.getByRole('button', { name: 'appAnnotation.editModal.removeThisCache' }),
+ )
+ const confirmation = screen.getByRole('alertdialog')
+ const confirm = within(confirmation).getByRole('button', { name: 'common.operation.confirm' })
+ await user.click(confirm)
+ await user.keyboard('{Escape}')
+ await user.click(confirm)
+ expect(api.remove).toHaveBeenCalledOnce()
+ expect(onRemoved).not.toHaveBeenCalled()
+ pending.reject(new Error('Offline'))
+ expect(await within(confirmation).findByRole('alert')).toBeVisible()
+ expect(confirmation).toBeInTheDocument()
+ await user.click(confirm)
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(onRemoved).toHaveBeenCalledOnce()
+ expect(api.remove).toHaveBeenLastCalledWith({
+ params: { app_id: 'app-id', annotation_id: 'annotation-id' },
})
+ })
+})
- it('should show fallback error message when editAnnotation error is not an Error instance', async () => {
- const mockOnEdited = vi.fn()
- const props = {
- ...defaultProps,
- annotationId: 'test-annotation-id',
- onEdited: mockOnEdited,
- }
- const user = userEvent.setup()
-
- mockEditAnnotation.mockRejectedValueOnce('oops')
-
- render(<EditAnnotationModal {...props} />)
-
- const editLinks = screen.getAllByText(/common\.operation\.edit/i)
- await user.click(editLinks[0]!)
-
- const textarea = screen.getByRole('textbox')
- await user.clear(textarea)
- await user.type(textarea, 'Modified query')
-
- const saveButton = screen.getByRole('button', { name: 'common.operation.save' })
- await user.click(saveButton)
-
- await waitFor(() => {
- expect(toastErrorSpy).toHaveBeenCalledWith('common.api.actionFailed')
- })
- expect(mockOnEdited).not.toHaveBeenCalled()
+it('keeps the question read-only for a response-only editor', async () => {
+ await setup('chat', true)
+ expect(
+ within(screen.getByRole('region', { name: 'appAnnotation.editModal.queryName' })).queryByRole(
+ 'button',
+ ),
+ ).not.toBeInTheDocument()
+ expect(
+ within(screen.getByRole('region', { name: 'appAnnotation.editModal.answerName' })).getByRole(
+ 'button',
+ { name: 'common.operation.edit' },
+ ),
+ ).toBeVisible()
+})
- expect(screen.getByRole('textbox'))!.toBeInTheDocument()
- expect(screen.getByRole('button', { name: 'common.operation.save' }))!.toBeInTheDocument()
- })
- })
+it('refreshes annotation queries after edits and refreshes quota only when deletion changes the count', async () => {
+ const { user, queryClient } = await setup('chat')
+ const featuresKey = consoleQuery.features.get.key()
+ const countKey = consoleQuery.apps.byAppId.annotations.count.get.queryOptions({
+ input: { params: { app_id: 'app-id' } },
+ }).queryKey
+ seedFeatures(queryClient, { annotation_quota_limit: { size: 1, limit: 10 } })
+ queryClient.setQueryData(countKey, { count: 1 })
+ const answer = await editField(user, 'answerName', 'Changed answer')
+ await user.click(answer.save)
+ await waitFor(() => expect(within(answer.section).queryByRole('textbox')).not.toBeInTheDocument())
+ expect(queryClient.getQueryState(countKey)?.isInvalidated).toBe(true)
+ expect(queryClient.getQueriesData({ queryKey: featuresKey })).not.toHaveLength(0)
+ expect(
+ queryClient
+ .getQueryCache()
+ .findAll({ queryKey: featuresKey })
+ .some((query) => query.state.isInvalidated),
+ ).toBe(false)
+ await user.click(screen.getByRole('button', { name: 'appAnnotation.editModal.removeThisCache' }))
+ await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ expect(
+ queryClient
+ .getQueryCache()
+ .findAll({ queryKey: featuresKey })
+ .every((query) => query.state.isInvalidated),
+ ).toBe(true)
})
diff --git a/web/app/components/app/annotation/edit-annotation-modal/annotation-editor.tsx b/web/app/components/app/annotation/edit-annotation-modal/annotation-editor.tsx
new file mode 100644
index 00000000000..b1db6778d0f
--- /dev/null
+++ b/web/app/components/app/annotation/edit-annotation-modal/annotation-editor.tsx
@@ -0,0 +1,60 @@
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import EditItem, { EditItemType } from './edit-item'
+
+export type AnnotationEditorProps = {
+ question: string
+ answer: string
+ onlyEditResponse?: boolean
+ isPending: boolean
+ isError: boolean
+ onSave: (body: { question: string; answer: string }, onSuccess: () => void) => void
+}
+
+export function AnnotationEditor({
+ question,
+ answer,
+ onlyEditResponse,
+ isPending,
+ isError,
+ onSave,
+}: AnnotationEditorProps) {
+ const { t } = useTranslation(['common'])
+ const [saved, setSaved] = useState({ question, answer })
+ return (
+ <div className="space-y-6">
+ <EditItem
+ type={EditItemType.Query}
+ content={question}
+ savedContent={saved.question}
+ readonly={onlyEditResponse}
+ isPending={isPending}
+ onSave={(question, onSuccess) => {
+ const body = { ...saved, question }
+ onSave(body, () => {
+ setSaved(body)
+ onSuccess()
+ })
+ }}
+ />
+ <EditItem
+ type={EditItemType.Answer}
+ content={answer}
+ savedContent={saved.answer}
+ isPending={isPending}
+ onSave={(answer, onSuccess) => {
+ const body = { ...saved, answer }
+ onSave(body, () => {
+ setSaved(body)
+ onSuccess()
+ })
+ }}
+ />
+ {isError && (
+ <p role="alert" className="system-sm-regular text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ )}
+ </div>
+ )
+}
diff --git a/web/app/components/app/annotation/edit-annotation-modal/edit-item/__tests__/index.spec.tsx b/web/app/components/app/annotation/edit-annotation-modal/edit-item/__tests__/index.spec.tsx
deleted file mode 100644
index ad1151463f1..00000000000
--- a/web/app/components/app/annotation/edit-annotation-modal/edit-item/__tests__/index.spec.tsx
+++ /dev/null
@@ -1,69 +0,0 @@
-import { render, screen } from '@testing-library/react'
-import userEvent from '@testing-library/user-event'
-import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'
-import EditItem, { EditItemType } from '../index'
-
-const defaultProps = {
- type: EditItemType.Query,
- content: 'Original content',
- onSave: vi.fn(),
-}
-
-const startEditing = async (user: ReturnType<typeof userEvent.setup>) => {
- await user.click(screen.getByText('common.operation.edit'))
- return screen.getByRole('textbox')
-}
-
-describe('EditItem', () => {
- beforeEach(() => vi.clearAllMocks())
-
- it('does not offer editing in readonly mode', () => {
- render(<EditItem {...defaultProps} readonly />)
-
- expect(screen.queryByText('common.operation.edit')).not.toBeInTheDocument()
- })
-
- it('cancels editing without saving', async () => {
- const user = userEvent.setup()
- const onSave = vi.fn()
- render(<EditItem {...defaultProps} onSave={onSave} />)
-
- const textbox = await startEditing(user)
- await user.clear(textbox)
- await user.type(textbox, 'Discarded draft')
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
-
- expect(screen.queryByRole('textbox')).not.toBeInTheDocument()
- expect(screen.getByText('Original content')).toBeInTheDocument()
- expect(onSave).not.toHaveBeenCalled()
- })
-
- it('can restore the original content after saving an edit', async () => {
- const user = userEvent.setup()
- const onSave = vi.fn().mockResolvedValue(undefined)
- render(<EditItem {...defaultProps} onSave={onSave} />)
-
- const textbox = await startEditing(user)
- await user.clear(textbox)
- await user.type(textbox, 'Updated content')
- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- await user.click(await screen.findByText('common.operation.delete'))
-
- expect(onSave).toHaveBeenNthCalledWith(1, 'Updated content')
- expect(onSave).toHaveBeenNthCalledWith(2, 'Original content')
- })
-
- it('keeps editing available when saving fails', async () => {
- const user = userEvent.setup()
- const onSave = vi.fn().mockRejectedValue(new Error('Save failed'))
- render(<EditItem {...defaultProps} onSave={onSave} />)
-
- const textbox = await startEditing(user)
- await user.type(textbox, 'Updated content')
- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
-
- expect(onSave).toHaveBeenCalledWith('Updated content')
- expect(screen.getByRole('textbox')).toHaveValue('Updated content')
- expect(screen.getByRole('button', { name: 'common.operation.save' })).toBeInTheDocument()
- })
-})
diff --git a/web/app/components/app/annotation/edit-annotation-modal/edit-item/index.tsx b/web/app/components/app/annotation/edit-annotation-modal/edit-item/index.tsx
index eaf6602ce22..de03e9e8db3 100644
--- a/web/app/components/app/annotation/edit-annotation-modal/edit-item/index.tsx
+++ b/web/app/components/app/annotation/edit-annotation-modal/edit-item/index.tsx
@@ -1,158 +1,152 @@
'use client'
-import type { FC } from 'react'
import { Button } from '@langgenius/dify-ui/button'
import { cn } from '@langgenius/dify-ui/cn'
+import { Field, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
+import { Form } from '@langgenius/dify-ui/form'
import { Textarea } from '@langgenius/dify-ui/textarea'
-import * as React from 'react'
-import { useEffect, useState } from 'react'
+import { useLayoutEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import robotAvatar from '../../assets/robot-avatar.svg'
-export const EditItemType = {
- Query: 'query',
- Answer: 'answer',
-} as const
-
+export const EditItemType = { Query: 'query', Answer: 'answer' } as const
export type EditItemType = (typeof EditItemType)[keyof typeof EditItemType]
-type Props = Readonly<{
+
+type EditItemProps = {
type: EditItemType
content: string
+ savedContent: string
readonly?: boolean
- onSave: (content: string) => Promise<void>
-}>
+ isPending: boolean
+ onSave: (content: string, onSuccess: () => void) => void
+}
-export const EditTitle: FC<{ className?: string; title: string }> = ({ className, title }) => (
- <div className={cn(className, 'flex h-4.5 items-center system-xs-medium text-text-tertiary')}>
- <span aria-hidden className="mr-1 i-ri-edit-fill size-3.5" />
- <div>{title}</div>
- <div
- className="ml-2 h-px grow"
- style={{
- background: 'linear-gradient(90deg, rgba(0, 0, 0, 0.05) -1.65%, rgba(0, 0, 0, 0.00) 100%)',
- }}
- ></div>
- </div>
-)
-const EditItem: FC<Props> = ({ type, readonly, content, onSave }) => {
- const { t } = useTranslation(['appAnnotation', 'common'])
- const [newContent, setNewContent] = useState('')
- const showNewContent = newContent && newContent !== content
- const avatar =
- type === EditItemType.Query ? (
- <span aria-hidden className="i-custom-public-avatar-user size-6" />
- ) : (
- <img aria-hidden src={robotAvatar.src} alt="" width={24} height={24} className="size-6" />
- )
- const name =
- type === EditItemType.Query
- ? t(($) => $['editModal.queryName'], { ns: 'appAnnotation' })
- : t(($) => $['editModal.answerName'], { ns: 'appAnnotation' })
- const editTitle =
- type === EditItemType.Query
- ? t(($) => $['editModal.yourQuery'], { ns: 'appAnnotation' })
- : t(($) => $['editModal.yourAnswer'], { ns: 'appAnnotation' })
- const placeholder =
- type === EditItemType.Query
- ? t(($) => $['editModal.queryPlaceholder'], { ns: 'appAnnotation' })
- : t(($) => $['editModal.answerPlaceholder'], { ns: 'appAnnotation' })
- const [isEdit, setIsEdit] = useState(false)
+type EditTitleProps = { className?: string; title: string }
- // Reset newContent when content prop changes
- useEffect(() => {
- setNewContent('')
- }, [content])
+export function EditTitle({ className, title }: EditTitleProps) {
+ return (
+ <div className={cn(className, 'flex h-4.5 items-center system-xs-medium text-text-tertiary')}>
+ <span aria-hidden className="me-1 i-ri-edit-fill size-3.5" />
+ <span>{title}</span>
+ <div className="ms-2 h-px grow bg-linear-to-r from-divider-subtle to-transparent" />
+ </div>
+ )
+}
- const handleSave = async () => {
- try {
- await onSave(newContent)
- setIsEdit(false)
- } catch {
- // Keep edit mode open when save fails
- // Error notification is handled by the parent component
- }
- }
+function focusEditor(element: HTMLTextAreaElement | null) {
+ element?.focus()
+}
- const handleCancel = () => {
- setNewContent('')
+export default function EditItem({
+ type,
+ readonly,
+ content,
+ savedContent,
+ isPending,
+ onSave,
+}: EditItemProps) {
+ const { t } = useTranslation(['appAnnotation', 'common'])
+ const [isEdit, setIsEdit] = useState(false)
+ const editButtonRef = useRef<HTMLButtonElement>(null)
+ const restoreEditFocus = useRef(false)
+ useLayoutEffect(() => {
+ if (restoreEditFocus.current && !isEdit && !isPending) {
+ editButtonRef.current?.focus()
+ restoreEditFocus.current = false
+ }
+ }, [isEdit, isPending])
+ const isQuestion = type === EditItemType.Query
+ const name = isQuestion
+ ? t(($) => $['editModal.queryName'], { ns: 'appAnnotation' })
+ : t(($) => $['editModal.answerName'], { ns: 'appAnnotation' })
+ const editTitle = isQuestion
+ ? t(($) => $['editModal.yourQuery'], { ns: 'appAnnotation' })
+ : t(($) => $['editModal.yourAnswer'], { ns: 'appAnnotation' })
+ const finishEditing = () => {
+ restoreEditFocus.current = true
setIsEdit(false)
}
return (
- <div className="flex" onClick={(e) => e.stopPropagation()}>
- <div className="mr-3 shrink-0">{avatar}</div>
- <div className="grow">
- <div className="mb-1 system-xs-semibold text-text-primary">{name}</div>
- <div className="system-sm-regular text-text-primary">{content}</div>
- {!isEdit ? (
- <div>
- {showNewContent && (
- <div className="mt-3">
- <EditTitle title={editTitle} />
- <div className="mt-1 system-sm-regular text-text-primary">{newContent}</div>
- </div>
- )}
- <div className="mt-2 flex items-center">
- {!readonly && (
- <button
- type="button"
- className="flex cursor-pointer items-center space-x-1 system-xs-medium text-text-accent"
- onClick={() => {
- setIsEdit(true)
- }}
- >
- <span aria-hidden className="mr-1 i-ri-edit-line size-3.5" />
- <span>{t(($) => $['operation.edit'], { ns: 'common' })}</span>
- </button>
- )}
-
- {showNewContent && (
- <div className="ml-2 flex items-center system-xs-medium text-text-tertiary">
- <div className="mr-2">·</div>
- <button
- type="button"
- className="flex cursor-pointer items-center space-x-1"
- onClick={async () => {
- try {
- await onSave(content)
- // Only update UI state after successful delete
- setNewContent(content)
- } catch {
- // Delete action failed - error is already handled by parent
- // UI state remains unchanged, user can retry
- }
- }}
- >
- <span className="size-3.5">
- <span aria-hidden className="i-ri-delete-bin-line size-3.5" />
- </span>
- <span>{t(($) => $['operation.delete'], { ns: 'common' })}</span>
- </button>
- </div>
- )}
- </div>
- </div>
+ <section aria-label={name} className="min-w-0 space-y-2">
+ <div className="flex items-center gap-2 system-sm-semibold text-text-primary">
+ {isQuestion ? (
+ <span aria-hidden className="i-custom-public-avatar-user size-6 shrink-0" />
) : (
- <div className="mt-3">
- <EditTitle title={editTitle} />
+ <img aria-hidden src={robotAvatar.src} alt="" width={24} height={24} />
+ )}
+ {name}
+ </div>
+ <p className="system-sm-regular wrap-break-word whitespace-pre-wrap text-text-primary">
+ {content}
+ </p>
+ {!isEdit && savedContent !== content && (
+ <div className="space-y-1">
+ <EditTitle title={editTitle} />
+ <p className="system-sm-regular wrap-break-word whitespace-pre-wrap text-text-primary">
+ {savedContent}
+ </p>
+ </div>
+ )}
+ {!readonly && (
+ <div className="flex gap-2">
+ <Button
+ ref={editButtonRef}
+ size="small"
+ variant="ghost"
+ disabled={isPending}
+ aria-expanded={isEdit}
+ onClick={() => setIsEdit(true)}
+ >
+ <span aria-hidden className="i-ri-edit-line size-3.5" />
+ {t(($) => $['operation.edit'], { ns: 'common' })}
+ </Button>
+ {!isEdit && savedContent !== content && (
+ <Button
+ size="small"
+ variant="ghost"
+ disabled={isPending}
+ onClick={() => onSave(content, finishEditing)}
+ >
+ {t(($) => $['operation.delete'], { ns: 'common' })}
+ </Button>
+ )}
+ </div>
+ )}
+ {isEdit && (
+ <Form<{ content: string }>
+ onFormSubmit={({ content }) => {
+ if (!isPending) onSave(content, finishEditing)
+ }}
+ >
+ <Field name="content">
+ <FieldLabel>{editTitle}</FieldLabel>
<Textarea
- aria-label={editTitle}
- value={newContent}
- onValueChange={(value) => setNewContent(value)}
- placeholder={placeholder}
- autoFocus
+ ref={focusEditor}
+ defaultValue={savedContent}
+ required
+ readOnly={isPending}
+ placeholder={
+ isQuestion
+ ? t(($) => $['editModal.queryPlaceholder'], { ns: 'appAnnotation' })
+ : t(($) => $['editModal.answerPlaceholder'], { ns: 'appAnnotation' })
+ }
/>
- <div className="mt-2 flex space-x-2">
- <Button size="small" variant="primary" onClick={handleSave}>
- {t(($) => $['operation.save'], { ns: 'common' })}
- </Button>
- <Button size="small" onClick={handleCancel}>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </Button>
- </div>
+ <FieldError match="valueMissing">
+ {isQuestion
+ ? t(($) => $['errorMessage.queryRequired'], { ns: 'appAnnotation' })
+ : t(($) => $['errorMessage.answerRequired'], { ns: 'appAnnotation' })}
+ </FieldError>
+ </Field>
+ <div className="mt-2 flex gap-2">
+ <Button type="submit" size="small" variant="primary" loading={isPending}>
+ {t(($) => $['operation.save'], { ns: 'common' })}
+ </Button>
+ <Button size="small" disabled={isPending} onClick={finishEditing}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </Button>
</div>
- )}
- </div>
- </div>
+ </Form>
+ )}
+ </section>
)
}
-export default React.memo(EditItem)
diff --git a/web/app/components/app/annotation/edit-annotation-modal/index.tsx b/web/app/components/app/annotation/edit-annotation-modal/index.tsx
index 1045799af10..1c8405b32b3 100644
--- a/web/app/components/app/annotation/edit-annotation-modal/index.tsx
+++ b/web/app/components/app/annotation/edit-annotation-modal/index.tsx
@@ -1,186 +1,157 @@
'use client'
-import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
-import type { FC } from 'react'
-import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from '@langgenius/dify-ui/alert-dialog'
+
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
import {
- Drawer,
- DrawerBackdrop,
- DrawerClose,
- DrawerContent,
- DrawerPopup,
- DrawerPortal,
- DrawerTitle,
- DrawerViewport,
-} from '@langgenius/dify-ui/drawer'
+ Dialog,
+ DialogBackdrop,
+ DialogBody,
+ DialogFooter,
+ DialogHeader,
+ DialogHeaderCloseButton,
+ DialogPopup,
+ DialogPortal,
+ DialogTitle,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
-import * as React from 'react'
+import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
+import { useMutation } from '@tanstack/react-query'
import { useRef } from 'react'
import { useTranslation } from 'react-i18next'
-import { toast } from '@/app/notifications'
import useTimestamp from '@/hooks/use-timestamp'
-import { consoleClient } from '@/service/console'
-import EditItem, { EditItemType } from './edit-item'
+import { consoleQuery } from '@/service/console'
+import { AnnotationEditor } from './annotation-editor'
+import { RemoveAnnotationDialog } from './remove-annotation-dialog'
-type Props = Readonly<{
- isShow: boolean
- onHide: () => void
+export type EditAnnotationDialogProps = {
appId: string
annotationId: string
- query: string
+ question: string
answer: string
- onEdited: (editedQuery: string, editedAnswer: string) => void
createdAt?: number
- onRemove: () => void
onlyEditResponse?: boolean
-}>
+ onEdited: (question: string, answer: string) => void
+ onRemoved: () => void
+}
-const EditAnnotationModal: FC<Props> = ({
- isShow,
- onHide,
- query,
- answer,
- onEdited,
+export default function EditAnnotationDialog({
appId,
annotationId,
+ question,
+ answer,
createdAt,
- onRemove,
onlyEditResponse,
-}) => {
+ onEdited,
+ onRemoved,
+}: EditAnnotationDialogProps) {
const { t } = useTranslation(['appAnnotation', 'appDebug', 'appLog', 'common'])
const { formatTime } = useTimestamp()
- const handleSave = async (type: EditItemType, editedContent: string) => {
- let postQuery = query
- let postAnswer = answer
- if (type === EditItemType.Query) postQuery = editedContent
- else postAnswer = editedContent
- try {
- await consoleClient.apps.byAppId.annotations.byAnnotationId.post({
- params: { app_id: appId, annotation_id: annotationId },
- body: { question: postQuery, answer: postAnswer },
- })
- onEdited(postQuery, postAnswer)
-
- toast.success(t(($) => $['api.actionSuccess'], { ns: 'common' }) as string)
- } catch (error) {
- const fallbackMessage = t(($) => $['api.actionFailed'], { ns: 'common' }) as string
- const message = error instanceof Error && error.message ? error.message : fallbackMessage
- toast.error(message)
- // Re-throw to preserve edit mode behavior for UI components
- throw error
- }
- }
- const removeActionsRef = useRef<AlertDialogActions>(null)
- if (!isShow) return null
-
+ const actionsRef = useRef<DialogActions>(null)
+ const removed = useRef(false)
+ const triggerRef = useRef<HTMLButtonElement>(null)
+ const update = useMutation(
+ consoleQuery.apps.byAppId.annotations.byAnnotationId.post.mutationOptions({
+ context: { silent: true },
+ }),
+ )
return (
- <div>
- <Drawer
- open
- modal
- disablePointerDismissal
- swipeDirection="right"
- onOpenChange={(open) => {
- if (!open) onHide()
- }}
- >
- <DrawerPortal>
- <DrawerBackdrop />
- <DrawerViewport>
- <DrawerPopup className="data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-120 data-[swipe-direction=right]:max-w-[calc(100vw-1rem)] data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border-r-[0.5px] data-[swipe-direction=right]:border-divider-subtle">
- <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">
- <div className="shrink-0 border-b border-divider-subtle py-4">
- <div className="flex h-6 items-center justify-between pr-5 pl-6">
- <DrawerTitle className="min-w-0 truncate system-xl-semibold text-text-primary">
- {t(($) => $['editModal.title'], { ns: 'appAnnotation' })}
- </DrawerTitle>
- <DrawerClose
- render={
- <IconButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- size="md"
- >
- <span aria-hidden="true" className="i-ri-close-line size-4" />
- </IconButton>
- }
- />
- </div>
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto">
- <div className="space-y-6 p-6 pb-4">
- <EditItem
- type={EditItemType.Query}
- content={query}
- readonly={onlyEditResponse}
- onSave={(editedContent) => handleSave(EditItemType.Query, editedContent)}
- />
- <EditItem
- type={EditItemType.Answer}
- content={answer}
- onSave={(editedContent) => handleSave(EditItemType.Answer, editedContent)}
- />
- </div>
- </div>
- <div className="shrink-0">
- <div className="flex h-16 items-center justify-between rounded-b-xl border-t border-divider-subtle bg-background-section-burn px-4 system-sm-medium text-text-tertiary">
- <AlertDialog actionsRef={removeActionsRef}>
- <AlertDialogTrigger className="flex cursor-pointer items-center space-x-2 pl-3">
- <span
- aria-hidden
- className="i-custom-vender-line-communication-message-check-remove h-6 w-6"
- />
- <span>
- {t(($) => $['editModal.removeThisCache'], { ns: 'appAnnotation' })}
- </span>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['feature.annotation.removeConfirm'], { ns: 'appDebug' })}
- </AlertDialogTitle>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- onClick={() => {
- onRemove()
- removeActionsRef.current?.close()
- onHide()
- }}
- >
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- {!!createdAt && (
- <div>
- {t(($) => $['editModal.createdAt'], { ns: 'appAnnotation' })}
- &nbsp;
- {formatTime(
- createdAt,
- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
- )}
- </div>
- )}
- </div>
- </div>
- </DrawerContent>
- </DrawerPopup>
- </DrawerViewport>
- </DrawerPortal>
- </Drawer>
- </div>
+ <Dialog
+ actionsRef={actionsRef}
+ disablePointerDismissal
+ onOpenChange={(open, details) => {
+ if (open) removed.current = false
+ if (!open && update.isPending && details.reason !== 'imperative-action') details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) {
+ update.reset()
+ if (removed.current) onRemoved()
+ }
+ }}
+ >
+ <Tooltip>
+ <DialogTrigger
+ ref={triggerRef}
+ render={
+ <TooltipTrigger
+ render={
+ <IconButton aria-label={t(($) => $['feature.annotation.edit'], { ns: 'appDebug' })}>
+ <span aria-hidden className="i-ri-edit-line size-4" />
+ </IconButton>
+ }
+ />
+ }
+ >
+ <span aria-hidden className="i-ri-edit-line size-4" />
+ </DialogTrigger>
+ <TooltipContent>
+ {t(($) => $['feature.annotation.edit'], { ns: 'appDebug' })}
+ </TooltipContent>
+ </Tooltip>
+ <DialogPortal>
+ <DialogBackdrop />
+ <DialogPopup
+ finalFocus={() => {
+ if (!removed.current) return true
+ return (
+ Array.from(
+ triggerRef.current?.parentElement?.querySelectorAll<HTMLButtonElement>(
+ 'button:not([disabled])',
+ ) ?? [],
+ ).find((button) => button !== triggerRef.current) ?? true
+ )
+ }}
+ className="fixed inset-e-2 top-16 bottom-3 flex min-h-0 w-120 max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg text-text-primary shadow-xl"
+ >
+ <DialogHeader>
+ <DialogTitle>{t(($) => $['editModal.title'], { ns: 'appAnnotation' })}</DialogTitle>
+ <DialogHeaderCloseButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ disabled={update.isPending}
+ />
+ </DialogHeader>
+ <DialogBody>
+ <AnnotationEditor
+ question={question}
+ answer={answer}
+ onlyEditResponse={onlyEditResponse}
+ isPending={update.isPending}
+ isError={update.isError}
+ onSave={(body, onSuccess) =>
+ update.mutate(
+ { params: { app_id: appId, annotation_id: annotationId }, body },
+ {
+ onSuccess: () => {
+ onEdited(body.question, body.answer)
+ onSuccess()
+ },
+ },
+ )
+ }
+ />
+ </DialogBody>
+ <DialogFooter>
+ <RemoveAnnotationDialog
+ appId={appId}
+ annotationId={annotationId}
+ disabled={update.isPending}
+ onRemoved={() => {
+ removed.current = true
+ actionsRef.current?.close()
+ }}
+ />
+ {createdAt != null && (
+ <span className="ms-auto system-xs-regular text-text-tertiary">
+ {t(($) => $['editModal.createdAt'], { ns: 'appAnnotation' })}{' '}
+ {formatTime(
+ createdAt,
+ t(($) => $.dateTimeFormat, { ns: 'appLog' }),
+ )}
+ </span>
+ )}
+ </DialogFooter>
+ </DialogPopup>
+ </DialogPortal>
+ </Dialog>
)
}
-export default React.memo(EditAnnotationModal)
diff --git a/web/app/components/app/annotation/edit-annotation-modal/remove-annotation-dialog.tsx b/web/app/components/app/annotation/edit-annotation-modal/remove-annotation-dialog.tsx
new file mode 100644
index 00000000000..7526db041f7
--- /dev/null
+++ b/web/app/components/app/annotation/edit-annotation-modal/remove-annotation-dialog.tsx
@@ -0,0 +1,90 @@
+import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
+import {
+ AlertDialog,
+ AlertDialogBody,
+ AlertDialogCancelButton,
+ AlertDialogConfirmButton,
+ AlertDialogContent,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ AlertDialogTrigger,
+} from '@langgenius/dify-ui/alert-dialog'
+import { Button } from '@langgenius/dify-ui/button'
+import { useMutation } from '@tanstack/react-query'
+import { useRef } from 'react'
+import { useTranslation } from 'react-i18next'
+import { consoleQuery } from '@/service/console'
+
+type RemoveAnnotationDialogProps = {
+ appId: string
+ annotationId: string
+ disabled: boolean
+ onRemoved: () => void
+}
+
+export function RemoveAnnotationDialog({
+ appId,
+ annotationId,
+ disabled,
+ onRemoved,
+}: RemoveAnnotationDialogProps) {
+ const { t } = useTranslation(['appAnnotation', 'appDebug', 'common'])
+ const actionsRef = useRef<AlertDialogActions>(null)
+ const removal = useMutation(
+ consoleQuery.apps.byAppId.annotations.byAnnotationId.delete.mutationOptions({
+ context: { silent: true },
+ onSuccess: () => {
+ actionsRef.current?.close()
+ onRemoved()
+ },
+ }),
+ )
+ return (
+ <AlertDialog
+ actionsRef={actionsRef}
+ onOpenChange={(open, details) => {
+ if (!open && removal.isPending && details.reason !== 'imperative-action') details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) removal.reset()
+ }}
+ >
+ <AlertDialogTrigger disabled={disabled} render={<Button variant="ghost" />}>
+ <span
+ aria-hidden
+ className="i-custom-vender-line-communication-message-check-remove size-5"
+ />
+ {t(($) => $['editModal.removeThisCache'], { ns: 'appAnnotation' })}
+ </AlertDialogTrigger>
+ <AlertDialogContent backdropProps={{ forceRender: true }}>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {t(($) => $['feature.annotation.removeConfirm'], { ns: 'appDebug' })}
+ </AlertDialogTitle>
+ </AlertDialogHeader>
+ {removal.isError && (
+ <AlertDialogBody>
+ <p role="alert" className="text-text-destructive">
+ {t(($) => $['api.actionFailed'], { ns: 'common' })}
+ </p>
+ </AlertDialogBody>
+ )}
+ <AlertDialogFooter>
+ <AlertDialogCancelButton disabled={removal.isPending}>
+ {t(($) => $['operation.cancel'], { ns: 'common' })}
+ </AlertDialogCancelButton>
+ <AlertDialogConfirmButton
+ loading={removal.isPending}
+ onClick={() => {
+ if (!removal.isPending)
+ removal.mutate({ params: { app_id: appId, annotation_id: annotationId } })
+ }}
+ >
+ {t(($) => $['operation.confirm'], { ns: 'common' })}
+ </AlertDialogConfirmButton>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ )
+}
diff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsx
index 0954762042b..2374af565a4 100644
--- a/web/app/components/app/annotation/index.tsx
+++ b/web/app/components/app/annotation/index.tsx
@@ -1,7 +1,6 @@
'use client'
import type { Annotation, AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'
-import type { FC } from 'react'
import type { QueryParam } from './filter'
import type { AnnotationReplyConfig } from '@/models/debug'
import { cn } from '@langgenius/dify-ui/cn'
@@ -16,7 +15,6 @@ import * as React from 'react'
import { useEffect, useState } from 'react'
import { useTranslation } from 'react-i18next'
import ConfigParamModal from '@/app/components/base/features/new-feature-panel/annotation-reply/config-param-modal'
-import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import AnnotationFullModal from '@/app/components/billing/annotation-full/modal'
import { toast } from '@/app/notifications'
import { APP_PAGE_LIMIT } from '@/config'
@@ -26,19 +24,16 @@ import { updateAnnotationStatus } from '@/service/annotation'
import { consoleClient, consoleQuery } from '@/service/console'
import { sleep } from '@/utils'
import PageTitle from '../log-annotation/page-title'
-import EmptyElement from './empty-element'
import Filter from './filter'
import HeaderOpts from './header-opts'
import { List } from './list'
import { AnnotationEnableStatus, JobStatus } from './type'
-import ViewAnnotationModal from './view-annotation-modal'
-type Props = Readonly<{
+type AnnotationProps = {
appDetail: AppDetailWithSite
-}>
+}
-const Annotation: FC<Props> = (props) => {
- const { appDetail } = props
+function Annotation({ appDetail }: AnnotationProps) {
const { t } = useTranslation(['appAnnotation', 'common'])
const docLink = useDocLink()
const [isShowEdit, setIsShowEdit] = useState(false)
@@ -69,8 +64,6 @@ const Annotation: FC<Props> = (props) => {
const totalPages = total ? Math.max(Math.ceil(total / limit), 1) : 1
const [isLoading, setIsLoading] = useState(false)
const [controlUpdateList, setControlUpdateList] = useState(() => Date.now())
- const [currItem, setCurrItem] = useState<Annotation | null>(null)
- const [isShowViewModal, setIsShowViewModal] = useState(false)
const [selectedIds, setSelectedIds] = useState<string[]>([])
const debouncedQueryParams = useDebounce(queryParams, { wait: 500 })
@@ -114,14 +107,6 @@ const Annotation: FC<Props> = (props) => {
fetchList(currPage + 1)
}, [currPage, limit, debouncedQueryParams])
- const handleRemove = async (id: string) => {
- await consoleClient.apps.byAppId.annotations.byAnnotationId.delete({
- params: { app_id: appDetail.id, annotation_id: id },
- })
- fetchList()
- setControlUpdateList(Date.now())
- }
-
const handleBatchDelete = async () => {
try {
await consoleClient.apps.byAppId.annotations.delete({
@@ -137,21 +122,6 @@ const Annotation: FC<Props> = (props) => {
}
}
- const handleView = (item: Annotation) => {
- setCurrItem(item)
- setIsShowViewModal(true)
- }
-
- const handleSave = async (question: string, answer: string) => {
- if (!currItem) return
- await consoleClient.apps.byAppId.annotations.byAnnotationId.post({
- params: { app_id: appDetail.id, annotation_id: currItem.id },
- body: { question, answer },
- })
- fetchList()
- setControlUpdateList(Date.now())
- }
-
useEffect(() => {
if (!isShowEdit) setControlRefreshSwitch(Date.now())
}, [isShowEdit])
@@ -238,26 +208,22 @@ const Annotation: FC<Props> = (props) => {
/>
</div>
</Filter>
- {isLoading ? (
- <LoadingPlaceholder className="h-full" />
- ) : total > 0 ? (
- <List
- appId={appDetail.id}
- list={list}
- onRemoved={() => {
- fetchList()
- setControlUpdateList(Date.now())
- }}
- onView={handleView}
- selectedIds={selectedIds}
- onSelectedIdsChange={setSelectedIds}
- onBatchDelete={handleBatchDelete}
- />
- ) : (
- <div className="flex h-full grow items-center justify-center">
- <EmptyElement />
- </div>
- )}
+ <List
+ isLoading={isLoading}
+ appId={appDetail.id}
+ list={list}
+ onRemoved={() => {
+ void fetchList().catch(noop)
+ setControlUpdateList(Date.now())
+ }}
+ onEdited={() => {
+ void fetchList(currPage + 1).catch(noop)
+ setControlUpdateList(Date.now())
+ }}
+ selectedIds={selectedIds}
+ onSelectedIdsChange={setSelectedIds}
+ onBatchDelete={handleBatchDelete}
+ />
{/* Show Pagination only if the total is more than the limit */}
{total && total > APP_PAGE_LIMIT ? (
<Pagination
@@ -281,18 +247,6 @@ const Annotation: FC<Props> = (props) => {
/>
) : null}
- {isShowViewModal && (
- <ViewAnnotationModal
- appId={appDetail.id}
- isShow={isShowViewModal}
- onHide={() => setIsShowViewModal(false)}
- onRemove={async () => {
- await handleRemove((currItem as Annotation)?.id)
- }}
- item={currItem as Annotation}
- onSave={handleSave}
- />
- )}
{isShowEdit && (
<ConfigParamModal
appId={appDetail.id}
diff --git a/web/app/components/app/annotation/list.tsx b/web/app/components/app/annotation/list.tsx
index ba32bd0549b..c120bca85dc 100644
--- a/web/app/components/app/annotation/list.tsx
+++ b/web/app/components/app/annotation/list.tsx
@@ -1,33 +1,33 @@
'use client'
import type { Annotation } from '@dify/contracts/api/console/apps/types.gen'
import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
+import type { DialogActions } from '@langgenius/dify-ui/dialog'
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 {
+ Dialog,
+ DialogBackdrop,
+ DialogPopup,
+ DialogPortal,
+ DialogTrigger,
+} from '@langgenius/dify-ui/dialog'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { useMutation } from '@tanstack/react-query'
-import * as React from 'react'
+import { useId, useRef } from 'react'
import { useTranslation } from 'react-i18next'
+import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleQuery } from '@/service/console'
import BatchAction from './batch-action'
+import EmptyElement from './empty-element'
import { RemoveAnnotationConfirmContent } from './remove-annotation-confirm-modal'
-
-type Props = Readonly<{
- appId: string
- list: Annotation[]
- onView: (item: Annotation) => void
- onRemoved: () => void
- selectedIds: string[]
- onSelectedIdsChange: (selectedIds: string[]) => void
- onBatchDelete: () => Promise<void>
-}>
+import AnnotationDetails from './view-annotation-modal'
type AnnotationTableRowProps = {
appId: string
item: Annotation
formattedCreatedAt: string
- onView: (item: Annotation) => void
onRemoved: () => void
}
@@ -35,12 +35,12 @@ function AnnotationTableRow({
appId,
item,
formattedCreatedAt,
- onView,
onRemoved,
}: AnnotationTableRowProps) {
const { t } = useTranslation(['appDebug'])
- const questionId = React.useId()
- const removeConfirmActionsRef = React.useRef<AlertDialogActions>(null)
+ const questionId = useId()
+ const editTriggerRef = useRef<HTMLButtonElement>(null)
+ const removeConfirmActionsRef = useRef<AlertDialogActions>(null)
const removeMutation = useMutation(
consoleQuery.apps.byAppId.annotations.byAnnotationId.delete.mutationOptions({
onSuccess: () => {
@@ -53,29 +53,39 @@ function AnnotationTableRow({
return (
<tr
className="cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover"
- onClick={() => onView(item)}
+ onClick={(event) => {
+ if (!(event.target as HTMLElement).closest('button, input, [role="checkbox"]'))
+ editTriggerRef.current?.click()
+ }}
>
<td className="w-12 px-2 align-middle" onClick={(e) => e.stopPropagation()}>
<div className="flex items-center">
<Checkbox className="shrink-0" value={item.id} aria-labelledby={questionId} />
</div>
</td>
- <td className="max-w-62.5 truncate p-3 pr-2" title={item.question ?? undefined}>
- <span id={questionId}>{item.question}</span>
+ <td className="max-w-62.5 truncate p-3 pe-2" title={item.question ?? undefined}>
+ <DialogTrigger payload={item} id={questionId} className="max-w-full truncate text-start">
+ {item.question}
+ </DialogTrigger>
</td>
- <td className="max-w-62.5 truncate p-3 pr-2" title={item.answer ?? undefined}>
+ <td className="max-w-62.5 truncate p-3 pe-2" title={item.answer ?? undefined}>
{item.answer}
</td>
- <td className="p-3 pr-2">{formattedCreatedAt}</td>
- <td className="p-3 pr-2">{item.hit_count}</td>
- <td className="w-24 p-3 pr-2" onClick={(e) => e.stopPropagation()}>
+ <td className="p-3 pe-2">{formattedCreatedAt}</td>
+ <td className="p-3 pe-2">{item.hit_count}</td>
+ <td className="w-24 p-3 pe-2" onClick={(e) => e.stopPropagation()}>
<div className="flex space-x-1 text-text-tertiary">
- <IconButton
- aria-label={t(($) => $['feature.annotation.edit'], { ns: 'appDebug' })}
- onClick={() => onView(item)}
+ <DialogTrigger
+ payload={item}
+ ref={editTriggerRef}
+ render={
+ <IconButton aria-label={t(($) => $['feature.annotation.edit'], { ns: 'appDebug' })}>
+ <span aria-hidden className="i-ri-edit-line size-4" />
+ </IconButton>
+ }
>
<span aria-hidden className="i-ri-edit-line size-4" />
- </IconButton>
+ </DialogTrigger>
<AlertDialog
actionsRef={removeConfirmActionsRef}
onOpenChange={(open, details) => {
@@ -105,86 +115,179 @@ function AnnotationTableRow({
)
}
+type AnnotationListProps = {
+ isLoading?: boolean
+ appId: string
+ list: Annotation[]
+ onEdited: () => void
+ onRemoved: () => void
+ selectedIds: string[]
+ onSelectedIdsChange: (selectedIds: string[]) => void
+ onBatchDelete: () => Promise<void>
+}
+
export function List({
+ isLoading = false,
appId,
list,
- onView,
+ onEdited,
onRemoved,
selectedIds,
onSelectedIdsChange,
onBatchDelete,
-}: Props) {
+}: AnnotationListProps) {
const { t } = useTranslation(['appAnnotation', 'appLog', 'common'])
const { formatTime } = useTimestamp()
const annotationIds = list.map((item) => item.id)
+ const actionsRef = useRef<DialogActions>(null)
+ const listRef = useRef<HTMLDivElement>(null)
+ const triggerRef = useRef<Element | null>(null)
+ const removed = useRef(false)
+ const removalFocus = useRef<HTMLElement | null>(null)
+ const update = useMutation(
+ consoleQuery.apps.byAppId.annotations.byAnnotationId.post.mutationOptions({
+ context: { silent: true },
+ onSuccess: onEdited,
+ }),
+ )
return (
- <>
- <div className="relative mt-2 grow overflow-x-auto">
- <CheckboxGroup
- value={selectedIds}
- onValueChange={onSelectedIdsChange}
- allValues={annotationIds}
- >
- <table className="w-full min-w-110 border-collapse border-0">
- <thead className="system-xs-medium-uppercase text-text-tertiary">
- <tr>
- <th className="w-12 rounded-l-lg bg-background-section-burn px-2 text-left align-middle font-[weight:inherit] whitespace-nowrap">
- <div className="flex items-center">
- <Checkbox
- className="shrink-0"
- parent
- aria-label={t(($) => $['operation.selectAll'], { ns: 'common' })}
- />
- </div>
- </th>
- <th className="w-5 bg-background-section-burn pr-1 pl-2 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['table.header.question'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['table.header.answer'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['table.header.createdAt'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['table.header.hits'], { ns: 'appAnnotation' })}
- </th>
- <th className="w-24 rounded-r-lg bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['table.header.actions'], { ns: 'appAnnotation' })}
- </th>
- </tr>
- </thead>
- <tbody className="system-sm-regular text-text-secondary">
- {list.map((item) => (
- <AnnotationTableRow
- key={item.id}
- item={item}
- formattedCreatedAt={
- item.created_at
- ? formatTime(
- item.created_at,
- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
- )
- : '-'
- }
+ <Dialog<Annotation>
+ actionsRef={actionsRef}
+ disablePointerDismissal
+ onOpenChange={(open, details) => {
+ if (open) {
+ removed.current = false
+ triggerRef.current = details.trigger ?? null
+ }
+ if (!open && update.isPending && details.reason !== 'imperative-action') details.cancel()
+ }}
+ onOpenChangeComplete={(open) => {
+ if (!open) {
+ update.reset()
+ if (removed.current) onRemoved()
+ }
+ }}
+ >
+ {({ payload }) => (
+ <>
+ <div
+ ref={listRef}
+ data-annotation-list
+ role="region"
+ aria-label={t(($) => $.title, { ns: 'appAnnotation' })}
+ tabIndex={-1}
+ className="relative mt-2 grow overflow-x-auto focus-visible:outline-2 focus-visible:outline-components-input-border-active"
+ >
+ {list.length === 0 && isLoading ? (
+ <LoadingPlaceholder className="h-full" />
+ ) : list.length === 0 ? (
+ <div className="flex h-full items-center justify-center">
+ <EmptyElement />
+ </div>
+ ) : (
+ <CheckboxGroup
+ value={selectedIds}
+ onValueChange={onSelectedIdsChange}
+ allValues={annotationIds}
+ >
+ <table className="w-full min-w-110 border-collapse border-0">
+ <thead className="system-xs-medium-uppercase text-text-tertiary">
+ <tr>
+ <th className="w-12 rounded-s-lg bg-background-section-burn px-2 text-start align-middle font-[weight:inherit] whitespace-nowrap">
+ <div className="flex items-center">
+ <Checkbox
+ className="shrink-0"
+ parent
+ aria-label={t(($) => $['operation.selectAll'], { ns: 'common' })}
+ />
+ </div>
+ </th>
+ <th className="w-5 bg-background-section-burn ps-2 pe-1 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['table.header.question'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['table.header.answer'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['table.header.createdAt'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['table.header.hits'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="w-24 rounded-e-lg bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['table.header.actions'], { ns: 'appAnnotation' })}
+ </th>
+ </tr>
+ </thead>
+ <tbody className="system-sm-regular text-text-secondary">
+ {list.map((item) => (
+ <AnnotationTableRow
+ key={item.id}
+ item={item}
+ formattedCreatedAt={
+ item.created_at
+ ? formatTime(
+ item.created_at,
+ t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
+ )
+ : '-'
+ }
+ appId={appId}
+ onRemoved={onRemoved}
+ />
+ ))}
+ </tbody>
+ </table>
+ </CheckboxGroup>
+ )}
+ </div>
+ {selectedIds.length > 0 && (
+ <BatchAction
+ className="absolute inset-s-0 bottom-20 z-20"
+ selectedIds={selectedIds}
+ onBatchDelete={onBatchDelete}
+ onSelectedIdsChange={onSelectedIdsChange}
+ />
+ )}
+ <DialogPortal>
+ <DialogBackdrop />
+ <DialogPopup
+ finalFocus={() => {
+ if (removed.current)
+ return removalFocus.current?.isConnected ? removalFocus.current : listRef.current
+ return triggerRef.current?.isConnected ? true : listRef.current
+ }}
+ className="fixed inset-e-2 top-16 bottom-3 flex min-h-0 w-200 max-w-[calc(100vw-1rem)] flex-col overflow-hidden rounded-2xl border-[0.5px] border-components-panel-border bg-components-panel-bg text-text-primary shadow-xl"
+ >
+ {payload && (
+ <AnnotationDetails
+ key={payload.id}
appId={appId}
- onView={onView}
- onRemoved={onRemoved}
+ item={payload}
+ isPending={update.isPending}
+ isError={update.isError}
+ onSave={(body, onSuccess) =>
+ update.mutate(
+ { params: { app_id: appId, annotation_id: payload.id }, body },
+ { onSuccess },
+ )
+ }
+ onRemoved={() => {
+ const row = triggerRef.current?.closest('tr')
+ removalFocus.current =
+ row?.nextElementSibling?.querySelector<HTMLButtonElement>('button') ??
+ row?.previousElementSibling?.querySelector<HTMLButtonElement>('button') ??
+ listRef.current
+ removed.current = true
+ actionsRef.current?.close()
+ }}
/>
- ))}
- </tbody>
- </table>
- </CheckboxGroup>
- </div>
- {selectedIds.length > 0 && (
- <BatchAction
- className="absolute bottom-20 left-0 z-20"
- selectedIds={selectedIds}
- onBatchDelete={onBatchDelete}
- onSelectedIdsChange={onSelectedIdsChange}
- />
+ )}
+ </DialogPopup>
+ </DialogPortal>
+ </>
)}
- </>
+ </Dialog>
)
}
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 762bfef9d77..e89b6d561a2 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
@@ -9,17 +9,20 @@ import {
} from '@langgenius/dify-ui/alert-dialog'
import { useTranslation } from 'react-i18next'
-type Props = Readonly<{
+type RemoveAnnotationConfirmContentProps = {
isPending: boolean
onRemove: () => void
-}>
+}
-export function RemoveAnnotationConfirmContent({ isPending, onRemove }: Props) {
+export function RemoveAnnotationConfirmContent({
+ isPending,
+ onRemove,
+}: RemoveAnnotationConfirmContentProps) {
const { t } = useTranslation(['appDebug', 'common'])
const title = t(($) => $['feature.annotation.removeConfirm'], { ns: 'appDebug' })
return (
- <AlertDialogContent>
+ <AlertDialogContent backdropProps={{ forceRender: true }}>
<AlertDialogHeader>
<AlertDialogTitle>{title}</AlertDialogTitle>
</AlertDialogHeader>
diff --git a/web/app/components/app/annotation/view-annotation-modal/__tests__/index.browser.spec.tsx b/web/app/components/app/annotation/view-annotation-modal/__tests__/index.browser.spec.tsx
new file mode 100644
index 00000000000..1aa07b4a93b
--- /dev/null
+++ b/web/app/components/app/annotation/view-annotation-modal/__tests__/index.browser.spec.tsx
@@ -0,0 +1,103 @@
+import type { Annotation } from '@dify/contracts/api/console/apps/types.gen'
+import { QueryClient } from '@tanstack/react-query'
+import { useState } from 'react'
+import { userEvent } from 'vite-plus/test/browser'
+import { render } from 'vitest-browser-react'
+import { QueryClientTestProvider } from '@/test/console/query-provider'
+import { List } from '../../list'
+
+vi.mock('react-i18next', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('react-i18next')>()
+ const { createReactI18nextMock } = await import('@/test/i18n-mock')
+ return { ...actual, ...createReactI18nextMock() }
+})
+vi.mock('@/hooks/use-timestamp', () => ({ default: () => ({ formatTime: () => 'Created time' }) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
+ return {
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.annotations.byAnnotationId.delete': () => undefined,
+ 'apps.byAppId.annotations.byAnnotationId.post': () => undefined,
+ }),
+ }
+})
+
+function AnnotationListFixture({ filterOnEdit = false }: { filterOnEdit?: boolean }) {
+ const [items, setItems] = useState<Annotation[]>([
+ { id: 'first', question: 'First question', answer: 'First answer' },
+ { id: 'second', question: 'Second question', answer: 'Second answer' },
+ ])
+ return (
+ <List
+ appId="app-id"
+ list={items}
+ onEdited={() => {
+ if (filterOnEdit) setItems([])
+ }}
+ onRemoved={() => setItems(items.slice(1))}
+ selectedIds={[]}
+ onSelectedIdsChange={() => {}}
+ onBatchDelete={async () => {}}
+ />
+ )
+}
+
+it('returns keyboard focus to the next annotation and then the empty list after nested deletion closes', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={client}>
+ <AnnotationListFixture />
+ </QueryClientTestProvider>,
+ )
+ await screen.getByRole('button', { name: 'First question' }).click()
+ await screen.getByRole('button', { name: 'appAnnotation.editModal.removeThisCache' }).click()
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: 'First question' }))
+ .not.toBeInTheDocument()
+ const next = screen.getByRole('button', { name: 'Second question' })
+ await expect.element(next).toHaveFocus()
+ await userEvent.keyboard('{Enter}')
+ await expect.element(screen.getByRole('dialog')).toBeVisible()
+ await screen.getByRole('button', { name: 'appAnnotation.editModal.removeThisCache' }).click()
+ await screen.getByRole('button', { name: 'common.operation.confirm' }).click()
+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: 'Second question' }))
+ .not.toBeInTheDocument()
+ await expect.element(screen.getByRole('region', { name: 'appAnnotation.title' })).toHaveFocus()
+ client.clear()
+})
+
+it('keeps a second-field draft when saving removes the row from filtered results and restores focus after the save commits', async () => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ const screen = await render(
+ <QueryClientTestProvider queryClient={client}>
+ <AnnotationListFixture filterOnEdit />
+ </QueryClientTestProvider>,
+ )
+ await screen.getByRole('button', { name: 'First question' }).click()
+ const question = screen.getByRole('region', { name: 'appAnnotation.editModal.queryName' })
+ const answer = screen.getByRole('region', { name: 'appAnnotation.editModal.answerName' })
+ await answer.getByRole('button', { name: 'common.operation.edit' }).click()
+ const answerInput = answer.getByRole('textbox')
+ await answerInput.fill('Unsaved second-field draft')
+ const editQuestion = question.getByRole('button', { name: 'common.operation.edit' })
+ await editQuestion.click()
+ await question.getByRole('textbox').fill('Changed question')
+ await question.getByRole('button', { name: 'common.operation.save' }).click()
+ await expect.element(question.getByRole('textbox')).not.toBeInTheDocument()
+ await expect.element(editQuestion).toHaveFocus()
+ await expect.element(answerInput).toHaveValue('Unsaved second-field draft')
+ await expect.element(screen.getByRole('dialog')).toBeVisible()
+ await screen.getByRole('button', { name: 'common.operation.close' }).click()
+ await expect.element(screen.getByRole('dialog')).not.toBeInTheDocument()
+ await expect
+ .element(screen.getByRole('button', { name: 'First question' }))
+ .not.toBeInTheDocument()
+ await expect.element(screen.getByRole('region', { name: 'appAnnotation.title' })).toHaveFocus()
+ client.clear()
+})
diff --git a/web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx
index fe138a1edcb..905cc6a69a9 100644
--- a/web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx
+++ b/web/app/components/app/annotation/view-annotation-modal/__tests__/index.spec.tsx
@@ -1,178 +1,138 @@
-import type { Annotation, AnnotationHitHistory } from '@dify/contracts/api/console/apps/types.gen'
-import { render, screen, waitFor, within } from '@testing-library/react'
+import type { consoleClient } from '@/service/console'
+import { screen, waitFor, within } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
-import * as React from 'react'
-import ViewAnnotationModal from '../index'
+import { renderWithConsoleQuery } from '@/test/console/query-data'
+import { createDeferred } from '@/test/deferred'
+import { List } from '../../list'
-const mockFormatTime = vi.fn(() => 'formatted-time')
-
-vi.mock('@/hooks/use-timestamp', () => ({
- default: () => ({
- formatTime: mockFormatTime,
- }),
-}))
-
-const { fetchHitHistoryListMock } = vi.hoisted(() => ({
- fetchHitHistoryListMock: vi.fn(),
-}))
-
-vi.mock('@/service/console', () => ({
- consoleClient: {
- apps: {
- byAppId: {
- annotations: { byAnnotationId: { hitHistories: { get: fetchHitHistoryListMock } } },
- },
- },
- },
+const api = vi.hoisted(() => ({
+ history: vi.fn<typeof consoleClient.apps.byAppId.annotations.byAnnotationId.hitHistories.get>(),
}))
-
-const createAnnotationItem = (overrides: Partial<Annotation> = {}): Annotation => ({
- id: overrides.id ?? 'annotation-id',
- question: overrides.question ?? 'question',
- answer: overrides.answer ?? 'answer',
- created_at: overrides.created_at ?? 1700000000,
- hit_count: overrides.hit_count ?? 0,
-})
-
-const createHitHistoryItem = (
- overrides: Partial<AnnotationHitHistory> = {},
-): AnnotationHitHistory => ({
- id: overrides.id ?? 'hit-id',
- question: overrides.question ?? 'query',
- match: overrides.match ?? 'match',
- response: overrides.response ?? 'response',
- source: overrides.source ?? 'source',
- score: overrides.score ?? 0.42,
- created_at: overrides.created_at ?? 1700000000,
-})
-
-const renderComponent = (props?: Partial<React.ComponentProps<typeof ViewAnnotationModal>>) => {
- const item = createAnnotationItem()
- const mergedProps: React.ComponentProps<typeof ViewAnnotationModal> = {
- appId: 'app-id',
- isShow: true,
- onHide: vi.fn(),
- item,
- onSave: vi.fn().mockResolvedValue(undefined),
- onRemove: vi.fn().mockResolvedValue(undefined),
- ...props,
- }
+vi.mock('@/hooks/use-timestamp', () => ({ default: () => ({ formatTime: () => 'Created time' }) }))
+vi.mock('@/service/console', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@/service/console')>()
+ const { withConsoleResponses } = await import('@/test/console/service-responses')
return {
- ...render(<ViewAnnotationModal {...mergedProps} />),
- props: mergedProps,
+ ...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.annotations.byAnnotationId.hitHistories.get': (input) => api.history(input),
+ }),
}
-}
-
-describe('ViewAnnotationModal', () => {
- beforeEach(() => {
- vi.clearAllMocks()
- fetchHitHistoryListMock.mockResolvedValue({ data: [], total: 0 })
- })
-
- it.each([
- { type: 'query', index: 0, label: 'yourQuery', question: 'updated', answer: 'answer' },
- { type: 'answer', index: 1, label: 'yourAnswer', question: 'question', answer: 'updated' },
- ])(
- 'saves the edited $type while retaining the other field',
- async ({ index, label, question, answer }) => {
- const user = userEvent.setup()
- const { props } = renderComponent()
- const panel = screen.getByRole('tabpanel', {
- name: 'appAnnotation.viewModal.annotatedResponse',
- })
- await user.click(within(panel).getAllByText('common.operation.edit')[index]!)
- await user.type(
- screen.getByRole('textbox', { name: `appAnnotation.editModal.${label}` }),
- 'updated',
- )
- await user.click(screen.getByRole('button', { name: 'common.operation.save' }))
- expect(props.onSave).toHaveBeenCalledWith(question, answer)
- },
+})
+const emptyHistory = { data: [], total: 0, page: 1, limit: 10, has_more: false }
+const items = ['a', 'b'].map((id) => ({
+ id,
+ question: `Question ${id}`,
+ answer: `Answer ${id}`,
+ hit_count: 0,
+}))
+function setup() {
+ const user = userEvent.setup()
+ const view = renderWithConsoleQuery(
+ <List
+ appId="app-id"
+ list={items}
+ onEdited={vi.fn()}
+ onRemoved={vi.fn()}
+ selectedIds={[]}
+ onSelectedIdsChange={vi.fn()}
+ onBatchDelete={vi.fn()}
+ />,
)
+ return { user, ...view }
+}
+beforeEach(() => {
+ api.history.mockResolvedValue(emptyHistory)
+})
- it('switches named panels with the keyboard while preserving the drawer name', async () => {
- const user = userEvent.setup()
- // Arrange
- const { props } = renderComponent()
-
- await waitFor(() => {
- expect(fetchHitHistoryListMock).toHaveBeenCalled()
- })
-
- // Act
- expect(
- screen.getByRole('dialog', { name: 'appAnnotation.viewModal.annotatedResponse' }),
- ).toBeInTheDocument()
- await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.annotatedResponse' }))
- await user.keyboard('{ArrowRight}{Enter}')
- expect(screen.getByRole('tab', { name: 'appAnnotation.viewModal.hitHistory' })).toHaveFocus()
- expect(
- screen.getByRole('tabpanel', { name: 'appAnnotation.viewModal.hitHistory' }),
- ).toBeInTheDocument()
- expect(screen.queryByText('common.operation.edit')).not.toBeInTheDocument()
- expect(
- screen.getByRole('dialog', { name: 'appAnnotation.viewModal.annotatedResponse' }),
- ).toBeInTheDocument()
-
- // Assert
- // Assert
- expect(await screen.findByText('appAnnotation.viewModal.noHitHistory'))!.toBeInTheDocument()
- expect(mockFormatTime).toHaveBeenCalledWith(props.item.created_at, 'appLog.dateTimeFormat')
- })
-
- it('should render hit history entries with their hit count when data exists', async () => {
- const user = userEvent.setup()
- const hits = [
- createHitHistoryItem({ question: 'user input' }),
- createHitHistoryItem({ id: 'hit-2', question: 'second' }),
- ]
- fetchHitHistoryListMock.mockResolvedValue({ data: hits, total: 15 })
-
- renderComponent()
-
- await user.click(await screen.findByText('appAnnotation.viewModal.hitHistory'))
-
- expect(await screen.findByText('user input'))!.toBeInTheDocument()
- expect(screen.getByText('15 appAnnotation.viewModal.hits'))!.toBeInTheDocument()
- expect(mockFormatTime).toHaveBeenCalledWith(hits[0]!.created_at, 'appLog.dateTimeFormat')
+it('loads history only when selected and preserves the annotation draft when switching tabs', async () => {
+ const { user } = setup()
+ await user.click(screen.getByRole('button', { name: 'Question a' }))
+ expect(api.history).not.toHaveBeenCalled()
+ const answer = screen.getByRole('region', { name: 'appAnnotation.editModal.answerName' })
+ await user.click(within(answer).getByRole('button', { name: 'common.operation.edit' }))
+ const textbox = within(answer).getByRole('textbox')
+ await user.clear(textbox)
+ await user.type(textbox, 'Unsaved answer')
+ await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.hitHistory' }))
+ expect(await screen.findByText('appAnnotation.viewModal.noHitHistory')).toBeVisible()
+ expect(api.history).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'app-id', annotation_id: 'a' },
+ query: { page: 1, limit: 10 },
})
+ await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.annotatedResponse' }))
+ expect(textbox).toHaveValue('Unsaved answer')
+})
- it('should confirm before removing the annotation and hide on success', async () => {
- const user = userEvent.setup()
- const { props } = renderComponent()
-
- await user.click(screen.getByText('appAnnotation.editModal.removeThisCache'))
- expect(
- await screen.findByText('appDebug.feature.annotation.removeConfirm'),
- )!.toBeInTheDocument()
-
- const confirmButton = await screen.findByRole('button', { name: 'common.operation.confirm' })
- expect(props.onRemove).not.toHaveBeenCalled()
- await user.click(confirmButton)
+it('reports history failures and retries without presenting them as an empty history', async () => {
+ api.history.mockRejectedValueOnce(new Error('Offline'))
+ const { user } = setup()
+ await user.click(screen.getByRole('button', { name: 'Question a' }))
+ await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.hitHistory' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('common.api.actionFailed')
+ expect(screen.queryByText('appAnnotation.viewModal.noHitHistory')).not.toBeInTheDocument()
+ await user.click(screen.getByRole('button', { name: 'common.operation.retry' }))
+ expect(await screen.findByText('appAnnotation.viewModal.noHitHistory')).toBeVisible()
+})
- await waitFor(() => {
- expect(props.onRemove).toHaveBeenCalledTimes(1)
- expect(props.onHide).toHaveBeenCalledTimes(1)
- })
+it('does not show a previous annotation response when its request completes late', async () => {
+ const pending =
+ createDeferred<
+ Awaited<
+ ReturnType<typeof consoleClient.apps.byAppId.annotations.byAnnotationId.hitHistories.get>
+ >
+ >()
+ api.history.mockReturnValueOnce(pending.promise)
+ const { user } = setup()
+ await user.click(screen.getByRole('button', { name: 'Question a' }))
+ await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.hitHistory' }))
+ await waitFor(() => expect(api.history).toHaveBeenCalledOnce())
+ await user.click(screen.getByRole('button', { name: 'common.operation.close' }))
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
+ await user.click(screen.getByRole('button', { name: 'Question b' }))
+ await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.hitHistory' }))
+ expect(await screen.findByText('appAnnotation.viewModal.noHitHistory')).toBeVisible()
+ pending.resolve({
+ ...emptyHistory,
+ total: 1,
+ data: [{ id: 'old', question: 'Old hit', score: 0 }],
})
+ await waitFor(() => expect(api.history).toHaveBeenCalledTimes(2))
+ expect(screen.queryByText('Old hit')).not.toBeInTheDocument()
+})
- it('should close the remove confirmation when cancelled', async () => {
- const user = userEvent.setup()
- const { props } = renderComponent()
-
- await user.click(screen.getByText('appAnnotation.editModal.removeThisCache'))
- expect(
- await screen.findByText('appDebug.feature.annotation.removeConfirm'),
- )!.toBeInTheDocument()
-
- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))
- expect(props.onRemove).not.toHaveBeenCalled()
- expect(props.onHide).not.toHaveBeenCalled()
-
- await waitFor(() => {
- expect(
- screen.queryByText('appDebug.feature.annotation.removeConfirm'),
- ).not.toBeInTheDocument()
- })
+it('renders zero scores and loads the requested history page without retaining the previous rows', async () => {
+ api.history.mockImplementation(async ({ query }) => ({
+ ...emptyHistory,
+ page: query?.page ?? 1,
+ total: 11,
+ has_more: query?.page === 1,
+ data:
+ query?.page === 2
+ ? [{ id: 'last-hit', question: 'Last hit', score: null }]
+ : Array.from({ length: 10 }, (_, index) => ({
+ id: `hit-${index}`,
+ question: `Hit ${index}`,
+ match: 'Matched question',
+ response: 'Annotated response',
+ source: 'web_app',
+ score: index / 10,
+ created_at: 1710000000,
+ })),
+ }))
+ const { user } = setup()
+ await user.click(screen.getByRole('button', { name: 'Question a' }))
+ await user.click(screen.getByRole('tab', { name: 'appAnnotation.viewModal.hitHistory' }))
+ const firstHit = await screen.findByRole('row', { name: /^Hit 0 / })
+ expect(within(firstHit).getByRole('cell', { name: '0.00' })).toBeVisible()
+ expect(within(firstHit).getByRole('cell', { name: 'Annotated response' })).toBeVisible()
+ expect(within(firstHit).getByRole('cell', { name: 'Created time' })).toBeVisible()
+ await user.click(screen.getByRole('button', { name: 'common.pagination.next' }))
+ const lastHit = await screen.findByRole('row', { name: /^Last hit / })
+ expect(within(lastHit).getAllByRole('cell', { name: '-' })).toHaveLength(2)
+ expect(screen.queryByRole('row', { name: /^Hit 0 / })).not.toBeInTheDocument()
+ expect(api.history).toHaveBeenLastCalledWith({
+ params: { app_id: 'app-id', annotation_id: 'a' },
+ query: { page: 2, limit: 10 },
})
})
diff --git a/web/app/components/app/annotation/view-annotation-modal/hit-history.tsx b/web/app/components/app/annotation/view-annotation-modal/hit-history.tsx
new file mode 100644
index 00000000000..db93e97400e
--- /dev/null
+++ b/web/app/components/app/annotation/view-annotation-modal/hit-history.tsx
@@ -0,0 +1,125 @@
+import { Button } from '@langgenius/dify-ui/button'
+import { cn } from '@langgenius/dify-ui/cn'
+import { Pagination } from '@langgenius/dify-ui/pagination'
+import { useQuery } from '@tanstack/react-query'
+import { useState } from 'react'
+import { useTranslation } from 'react-i18next'
+import { LoadingPlaceholder } from '@/app/components/base/loading-placeholder'
+import { APP_PAGE_LIMIT } from '@/config'
+import useTimestamp from '@/hooks/use-timestamp'
+import { consoleQuery } from '@/service/console'
+import HitHistoryNoData from './hit-history-no-data'
+
+type AnnotationHitHistoryProps = { appId: string; annotationId: string }
+
+export function AnnotationHitHistory({ appId, annotationId }: AnnotationHitHistoryProps) {
+ const { t } = useTranslation(['appAnnotation', 'appLog', 'common'])
+ const { formatTime } = useTimestamp()
+ const [page, setPage] = useState(1)
+ const history = useQuery(
+ consoleQuery.apps.byAppId.annotations.byAnnotationId.hitHistories.get.queryOptions({
+ input: {
+ params: { app_id: appId, annotation_id: annotationId },
+ query: { page, limit: APP_PAGE_LIMIT },
+ },
+ context: { silent: true },
+ }),
+ )
+ const { data } = history
+ if (!data) {
+ if (history.isError)
+ return (
+ <div role="alert" className="space-y-2">
+ <p>{t(($) => $['api.actionFailed'], { ns: 'common' })}</p>
+ <Button loading={history.isFetching} onClick={() => history.refetch()}>
+ {t(($) => $['operation.retry'], { ns: 'common' })}
+ </Button>
+ </div>
+ )
+ return <LoadingPlaceholder />
+ }
+ if (data.total === 0) return <HitHistoryNoData />
+ return (
+ <div>
+ <p className="mb-3 system-xs-medium text-text-tertiary">
+ {data.total}{' '}
+ {t(($) => $[`viewModal.hit${data.total > 1 ? 's' : ''}`], { ns: 'appAnnotation' })}
+ </p>
+ <table className={cn('w-full min-w-110 border-collapse border-0')}>
+ <thead className="system-xs-medium-uppercase text-text-tertiary">
+ <tr>
+ <th className="w-5 rounded-s-lg bg-background-section-burn ps-2 pe-1 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['hitHistoryTable.query'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['hitHistoryTable.match'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['hitHistoryTable.response'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['hitHistoryTable.source'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['hitHistoryTable.score'], { ns: 'appAnnotation' })}
+ </th>
+ <th className="w-40 rounded-e-lg bg-background-section-burn py-1.5 ps-3 text-start font-[weight:inherit] whitespace-nowrap">
+ {t(($) => $['hitHistoryTable.time'], { ns: 'appAnnotation' })}
+ </th>
+ </tr>
+ </thead>
+ <tbody className="system-sm-regular text-text-secondary">
+ {data.data.map((item) => (
+ <tr
+ key={item.id}
+ className="cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover"
+ >
+ <td
+ className="max-w-62.5 overflow-hidden p-3 pe-2 text-ellipsis whitespace-nowrap"
+ title={item.question ?? undefined}
+ >
+ {item.question}
+ </td>
+ <td
+ className="max-w-62.5 overflow-hidden p-3 pe-2 text-ellipsis whitespace-nowrap"
+ title={item.match ?? undefined}
+ >
+ {item.match}
+ </td>
+ <td
+ className="max-w-62.5 overflow-hidden p-3 pe-2 text-ellipsis whitespace-nowrap"
+ title={item.response ?? undefined}
+ >
+ {item.response}
+ </td>
+ <td className="p-3 pe-2">{item.source}</td>
+ <td className="p-3 pe-2">{item.score != null ? item.score.toFixed(2) : '-'}</td>
+ <td className="p-3 pe-2">
+ {item.created_at
+ ? formatTime(
+ item.created_at,
+ t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
+ )
+ : '-'}
+ </td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {data.total > APP_PAGE_LIMIT && (
+ <Pagination
+ page={page}
+ totalPages={Math.ceil(data.total / APP_PAGE_LIMIT)}
+ onPageChange={setPage}
+ labels={{
+ previous: t(($) => $['pagination.previous'], { ns: 'common' }),
+ next: t(($) => $['pagination.next'], { ns: 'common' }),
+ editPageNumber: (page, totalPages) =>
+ t(($) => $['pagination.editPageNumber'], { ns: 'common', page, totalPages }),
+ pageNumberInput: t(($) => $['pagination.pageNumber'], { ns: 'common' }),
+ }}
+ />
+ )}
+ </div>
+ )
+}
diff --git a/web/app/components/app/annotation/view-annotation-modal/index.tsx b/web/app/components/app/annotation/view-annotation-modal/index.tsx
index 4cd6d12abe6..ed248d5a551 100644
--- a/web/app/components/app/annotation/view-annotation-modal/index.tsx
+++ b/web/app/components/app/annotation/view-annotation-modal/index.tsx
@@ -1,325 +1,95 @@
'use client'
-import type { Annotation, AnnotationHitHistory } from '@dify/contracts/api/console/apps/types.gen'
-import type { AlertDialogActions } from '@langgenius/dify-ui/alert-dialog'
-import type { FC } from 'react'
+import type { Annotation } from '@dify/contracts/api/console/apps/types.gen'
+import type { AnnotationEditorProps } from '../edit-annotation-modal/annotation-editor'
import {
- AlertDialog,
- AlertDialogCancelButton,
- AlertDialogConfirmButton,
- AlertDialogContent,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from '@langgenius/dify-ui/alert-dialog'
-import { cn } from '@langgenius/dify-ui/cn'
-import {
- Drawer,
- DrawerBackdrop,
- DrawerClose,
- DrawerContent,
- DrawerPopup,
- DrawerPortal,
- DrawerTitle,
- DrawerViewport,
-} from '@langgenius/dify-ui/drawer'
-import { IconButton } from '@langgenius/dify-ui/icon-button'
-import { Pagination } from '@langgenius/dify-ui/pagination'
+ DialogBody,
+ DialogFooter,
+ DialogHeader,
+ DialogHeaderCloseButton,
+ DialogTitle,
+} from '@langgenius/dify-ui/dialog'
import { Tabs, TabsList, TabsPanel, TabsTab } from '@langgenius/dify-ui/tabs'
-import * as React from 'react'
-import { useEffect, useState } from 'react'
+import { useState } from 'react'
import { useTranslation } from 'react-i18next'
-import { APP_PAGE_LIMIT } from '@/config'
import useTimestamp from '@/hooks/use-timestamp'
-import { consoleClient } from '@/service/console'
-import EditItem, { EditItemType } from '../edit-annotation-modal/edit-item'
-import HitHistoryNoData from './hit-history-no-data'
+import { AnnotationEditor } from '../edit-annotation-modal/annotation-editor'
+import { RemoveAnnotationDialog } from '../edit-annotation-modal/remove-annotation-dialog'
+import { AnnotationHitHistory } from './hit-history'
-type Props = Readonly<{
+type AnnotationDetailsProps = {
appId: string
- isShow: boolean
- onHide: () => void
item: Annotation
- onSave: (editedQuery: string, editedAnswer: string) => Promise<void>
- onRemove: () => void
-}>
-
-const TabType = {
- annotation: 'annotation',
- hitHistory: 'hitHistory',
-} as const
-
-type TabType = (typeof TabType)[keyof typeof TabType]
+ isPending: boolean
+ isError: boolean
+ onSave: AnnotationEditorProps['onSave']
+ onRemoved: () => void
+}
-const ViewAnnotationModal: FC<Props> = ({ appId, isShow, onHide, item, onSave, onRemove }) => {
- const { id, created_at: createdAt } = item
- const question = item.question ?? ''
- const answer = item.answer ?? ''
- const [newQuestion, setNewQuery] = useState(question)
- const [newAnswer, setNewAnswer] = useState(answer)
- const { t } = useTranslation(['appAnnotation', 'appDebug', 'appLog', 'common'])
+export default function AnnotationDetails({
+ appId,
+ item,
+ isPending,
+ isError,
+ onSave,
+ onRemoved,
+}: AnnotationDetailsProps) {
+ const { t } = useTranslation(['appAnnotation', 'appLog', 'common'])
const { formatTime } = useTimestamp()
- const [currPage, setCurrPage] = React.useState<number>(0)
- const [total, setTotal] = useState(0)
- const totalPages = total ? Math.max(Math.ceil(total / APP_PAGE_LIMIT), 1) : 1
- const [hitHistoryList, setHitHistoryList] = useState<AnnotationHitHistory[]>([])
-
- // Update local state when item prop changes (e.g., when modal is reopened with updated data)
- useEffect(() => {
- setNewQuery(question)
- setNewAnswer(answer)
- setCurrPage(0)
- setTotal(0)
- setHitHistoryList([])
- }, [question, answer, id])
-
- const fetchHitHistory = async (page = 1) => {
- try {
- const { data, total } =
- await consoleClient.apps.byAppId.annotations.byAnnotationId.hitHistories.get({
- params: { app_id: appId, annotation_id: id },
- query: { page, limit: 10 },
- })
- setHitHistoryList(data)
- setTotal(total)
- } catch {}
- }
-
- useEffect(() => {
- fetchHitHistory(currPage + 1)
- }, [currPage])
-
- // Fetch hit history when item changes
- useEffect(() => {
- if (isShow && id) fetchHitHistory(1)
- }, [id, isShow])
-
- const [activeTab, setActiveTab] = useState<TabType>(TabType.annotation)
- const handleSave = async (type: EditItemType, editedContent: string) => {
- try {
- if (type === EditItemType.Query) {
- await onSave(editedContent, newAnswer)
- setNewQuery(editedContent)
- } else {
- await onSave(newQuestion, editedContent)
- setNewAnswer(editedContent)
- }
- } catch (error) {
- // If save fails, don't update local state
- console.error('Failed to save annotation:', error)
- }
- }
- const removeActionsRef = React.useRef<AlertDialogActions>(null)
-
- const annotationTab = (
+ const [tab, setTab] = useState('annotation')
+ return (
<>
- <EditItem
- type={EditItemType.Query}
- content={question}
- onSave={(editedContent) => handleSave(EditItemType.Query, editedContent)}
- />
- <EditItem
- type={EditItemType.Answer}
- content={answer}
- onSave={(editedContent) => handleSave(EditItemType.Answer, editedContent)}
- />
- </>
- )
-
- const hitHistoryTab =
- total === 0 ? (
- <HitHistoryNoData />
- ) : (
- <div>
- <table className={cn('w-full min-w-110 border-collapse border-0')}>
- <thead className="system-xs-medium-uppercase text-text-tertiary">
- <tr>
- <th className="w-5 rounded-l-lg bg-background-section-burn pr-1 pl-2 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['hitHistoryTable.query'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['hitHistoryTable.match'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['hitHistoryTable.response'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['hitHistoryTable.source'], { ns: 'appAnnotation' })}
- </th>
- <th className="bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['hitHistoryTable.score'], { ns: 'appAnnotation' })}
- </th>
- <th className="w-40 rounded-r-lg bg-background-section-burn py-1.5 pl-3 text-left font-[weight:inherit] whitespace-nowrap">
- {t(($) => $['hitHistoryTable.time'], { ns: 'appAnnotation' })}
- </th>
- </tr>
- </thead>
- <tbody className="system-sm-regular text-text-secondary">
- {hitHistoryList.map((item) => (
- <tr
- key={item.id}
- className="cursor-pointer border-b border-divider-subtle hover:bg-background-default-hover"
- >
- <td
- className="max-w-62.5 overflow-hidden p-3 pr-2 text-ellipsis whitespace-nowrap"
- title={item.question ?? undefined}
- >
- {item.question}
- </td>
- <td
- className="max-w-62.5 overflow-hidden p-3 pr-2 text-ellipsis whitespace-nowrap"
- title={item.match ?? undefined}
- >
- {item.match}
- </td>
- <td
- className="max-w-62.5 overflow-hidden p-3 pr-2 text-ellipsis whitespace-nowrap"
- title={item.response ?? undefined}
- >
- {item.response}
- </td>
- <td className="p-3 pr-2">{item.source}</td>
- <td className="p-3 pr-2">{item.score ? item.score.toFixed(2) : '-'}</td>
- <td className="p-3 pr-2">
- {item.created_at
- ? formatTime(
- item.created_at,
- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
- )
- : '-'}
- </td>
- </tr>
- ))}
- </tbody>
- </table>
- {total && total > APP_PAGE_LIMIT ? (
- <Pagination
- page={currPage + 1}
- totalPages={totalPages}
- onPageChange={(page) => setCurrPage(page - 1)}
- labels={{
- previous: t(($) => $['pagination.previous'], { ns: 'common' }),
- next: t(($) => $['pagination.next'], { ns: 'common' }),
- editPageNumber: (page, totalPages) =>
- t(($) => $['pagination.editPageNumber'], { ns: 'common', page, totalPages }),
- pageNumberInput: t(($) => $['pagination.pageNumber'], { ns: 'common' }),
- }}
+ <DialogHeader>
+ <DialogTitle>
+ {t(($) => $['viewModal.annotatedResponse'], { ns: 'appAnnotation' })}
+ </DialogTitle>
+ <DialogHeaderCloseButton
+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}
+ disabled={isPending}
+ />
+ </DialogHeader>
+ <Tabs value={tab} onValueChange={setTab} className="flex min-h-0 flex-1 flex-col">
+ <TabsList className="mx-6 shrink-0">
+ <TabsTab value="annotation">
+ {t(($) => $['viewModal.annotatedResponse'], { ns: 'appAnnotation' })}
+ </TabsTab>
+ <TabsTab value="history" disabled={isPending}>
+ {t(($) => $['viewModal.hitHistory'], { ns: 'appAnnotation' })}
+ </TabsTab>
+ </TabsList>
+ <DialogBody>
+ <TabsPanel value="annotation" keepMounted>
+ <AnnotationEditor
+ question={item.question ?? ''}
+ answer={item.answer ?? ''}
+ isPending={isPending}
+ isError={isError}
+ onSave={onSave}
+ />
+ </TabsPanel>
+ <TabsPanel value="history">
+ <AnnotationHitHistory appId={appId} annotationId={item.id} />
+ </TabsPanel>
+ </DialogBody>
+ </Tabs>
+ {tab === 'annotation' && (
+ <DialogFooter>
+ <RemoveAnnotationDialog
+ appId={appId}
+ annotationId={item.id}
+ disabled={isPending}
+ onRemoved={onRemoved}
/>
- ) : null}
- </div>
- )
- if (!isShow) return null
-
- return (
- <div>
- <Drawer
- open
- modal
- disablePointerDismissal
- swipeDirection="right"
- onOpenChange={(open) => {
- if (!open) onHide()
- }}
- >
- <DrawerPortal>
- <DrawerBackdrop />
- <DrawerViewport>
- <DrawerPopup className="data-[swipe-direction=right]:top-16 data-[swipe-direction=right]:right-2 data-[swipe-direction=right]:bottom-3 data-[swipe-direction=right]:h-auto data-[swipe-direction=right]:w-200 data-[swipe-direction=right]:max-w-[calc(100vw-1rem)] data-[swipe-direction=right]:rounded-xl data-[swipe-direction=right]:border-r-[0.5px] data-[swipe-direction=right]:border-divider-subtle">
- <DrawerContent className="flex min-h-0 flex-1 flex-col p-0 pb-0">
- <DrawerTitle className="sr-only">
- {t(($) => $['viewModal.annotatedResponse'], { ns: 'appAnnotation' })}
- </DrawerTitle>
- <Tabs
- value={activeTab}
- onValueChange={setActiveTab}
- className="flex min-h-0 flex-1 flex-col"
- >
- <div className="flex shrink-0 items-center justify-between gap-4 border-b border-divider-subtle pr-5 pl-6">
- <TabsList>
- <TabsTab value={TabType.annotation}>
- {t(($) => $['viewModal.annotatedResponse'], { ns: 'appAnnotation' })}
- </TabsTab>
- <TabsTab value={TabType.hitHistory}>
- {t(($) => $['viewModal.hitHistory'], { ns: 'appAnnotation' })}
- {hitHistoryList.length > 0 && (
- <span className="ml-1 system-xs-medium text-text-tertiary">
- {`${total} ${t(($) => $[`viewModal.hit${hitHistoryList.length > 1 ? 's' : ''}`], { ns: 'appAnnotation' })}`}
- </span>
- )}
- </TabsTab>
- </TabsList>
- <DrawerClose
- render={
- <IconButton
- aria-label={t(($) => $['operation.close'], { ns: 'common' })}
- size="md"
- >
- <span aria-hidden="true" className="i-ri-close-line size-4" />
- </IconButton>
- }
- />
- </div>
- <div className="min-h-0 flex-1 overflow-y-auto">
- <TabsPanel value={TabType.annotation} className="space-y-6 p-6 pb-4">
- {annotationTab}
- </TabsPanel>
- <TabsPanel value={TabType.hitHistory} className="p-6 pb-4">
- {hitHistoryTab}
- </TabsPanel>
- </div>
- </Tabs>
- {id && (
- <div className="flex h-16 shrink-0 items-center justify-between rounded-b-xl border-t border-divider-subtle bg-background-section-burn px-4 system-sm-medium text-text-tertiary">
- <AlertDialog actionsRef={removeActionsRef}>
- <AlertDialogTrigger className="flex cursor-pointer appearance-none items-center space-x-2 border-0 bg-transparent py-0 pr-0 pl-3 text-left">
- <span
- aria-hidden
- className="i-custom-vender-line-communication-message-check-remove h-6 w-6"
- />
- <span>
- {t(($) => $['editModal.removeThisCache'], { ns: 'appAnnotation' })}
- </span>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>
- {t(($) => $['feature.annotation.removeConfirm'], { ns: 'appDebug' })}
- </AlertDialogTitle>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancelButton>
- {t(($) => $['operation.cancel'], { ns: 'common' })}
- </AlertDialogCancelButton>
- <AlertDialogConfirmButton
- onClick={async () => {
- await onRemove()
- removeActionsRef.current?.close()
- onHide()
- }}
- >
- {t(($) => $['operation.confirm'], { ns: 'common' })}
- </AlertDialogConfirmButton>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- <div>
- {t(($) => $['editModal.createdAt'], { ns: 'appAnnotation' })}
- &nbsp;
- {createdAt
- ? formatTime(
- createdAt,
- t(($) => $.dateTimeFormat, { ns: 'appLog' }) as string,
- )
- : '-'}
- </div>
- </div>
- )}
- </DrawerContent>
- </DrawerPopup>
- </DrawerViewport>
- </DrawerPortal>
- </Drawer>
- </div>
+ <span className="ms-auto system-xs-regular text-text-tertiary">
+ {t(($) => $['editModal.createdAt'], { ns: 'appAnnotation' })}{' '}
+ {item.created_at != null
+ ? formatTime(
+ item.created_at,
+ t(($) => $.dateTimeFormat, { ns: 'appLog' }),
+ )
+ : '-'}
+ </span>
+ </DialogFooter>
+ )}
+ </>
)
}
-export default React.memo(ViewAnnotationModal)
diff --git a/web/app/components/app/log/__tests__/list.spec.tsx b/web/app/components/app/log/__tests__/list.spec.tsx
index 3e1c1d163c0..0d0ffd1a0ca 100644
--- a/web/app/components/app/log/__tests__/list.spec.tsx
+++ b/web/app/components/app/log/__tests__/list.spec.tsx
@@ -53,6 +53,8 @@ vi.mock('@/service/console', async (importOriginal) => {
return {
...actual,
consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.annotations.byAnnotationId.post': (input) => api.editAnnotation(input),
+ 'apps.byAppId.annotations.byAnnotationId.delete': (input) => api.removeAnnotation(input),
'apps.byAppId.traceRuns.bySourceKind.bySourceId.get': (input) => api.externalTrace(input),
'apps.byAppId.chatMessages.get': (input) => api.messages(input),
'apps.byAppId.chatConversations.byConversationId.get': (input) => api.chatDetail(input),
@@ -63,8 +65,6 @@ vi.mock('@/service/console', async (importOriginal) => {
'apps.byAppId.chatMessages.get': (input) => api.messages(input),
'apps.byAppId.feedbacks.post': (input) => api.feedback(input),
'apps.byAppId.annotations.post': (input) => api.addAnnotation(input),
- 'apps.byAppId.annotations.byAnnotationId.post': (input) => api.editAnnotation(input),
- 'apps.byAppId.annotations.byAnnotationId.delete': (input) => api.removeAnnotation(input),
'apps.byAppId.agent.logs.get': (input) => api.agentLog(input),
}),
}
@@ -408,10 +408,11 @@ it('adds, edits and removes an annotation from a conversation answer', async ()
await user.click(await screen.findByRole('button', { name: 'appDebug.feature.annotation.edit' }))
const editor = await screen.findByRole('dialog', { name: 'appAnnotation.editModal.title' })
await user.click(within(editor).getAllByRole('button', { name: 'common.operation.edit' })[1]!)
- await user.type(
- within(editor).getByRole('textbox', { name: 'appAnnotation.editModal.yourAnswer' }),
- 'Improved answer',
- )
+ const answerInput = within(editor).getByRole('textbox', {
+ name: 'appAnnotation.editModal.yourAnswer',
+ })
+ await user.clear(answerInput)
+ await user.type(answerInput, 'Improved answer')
await user.click(within(editor).getByRole('button', { name: 'common.operation.save' }))
await waitFor(() =>
expect(api.editAnnotation).toHaveBeenCalledExactlyOnceWith({
diff --git a/web/app/components/app/log/conversation-detail.tsx b/web/app/components/app/log/conversation-detail.tsx
index 777ca994cd4..27a0c4519c7 100644
--- a/web/app/components/app/log/conversation-detail.tsx
+++ b/web/app/components/app/log/conversation-detail.tsx
@@ -30,7 +30,6 @@ import ErrorBoundary from '@/app/components/base/error-boundary'
import MessageLogModal from '@/app/components/base/message-log-modal'
import PromptLogModal from '@/app/components/base/prompt-log-modal'
import { WorkflowContextProvider } from '@/app/components/workflow/context'
-import { toast } from '@/app/notifications'
import { userProfileQueryOptions } from '@/features/account-profile/client'
import useTimestamp from '@/hooks/use-timestamp'
import { consoleClient, consoleQuery } from '@/service/console'
@@ -120,27 +119,12 @@ function DetailPanel({ appDetail, detail, onFeedback, initialMessages }: IDetail
[allChatItems, threadChatItems],
)
const handleAnnotationRemoved = useCallback(
- async (index: number): Promise<boolean> => {
+ (index: number) => {
const itemIndex = getAllChatItemIndex(allChatItems, threadChatItems, index)
- const annotation = allChatItems[itemIndex]?.annotation
-
- try {
- if (!annotation?.id) throw new Error('Annotation not found')
-
- await consoleClient.apps.byAppId.annotations.byAnnotationId.delete({
- params: { app_id: appDetail.id, annotation_id: annotation.id },
- })
-
- setAllChatItems(applyAnnotationRemoved(allChatItems, itemIndex))
-
- toast.success(t(($) => $['actionMsg.modifiedSuccessfully'], { ns: 'common' }))
- return true
- } catch {
- toast.error(t(($) => $['actionMsg.modifiedUnsuccessfully'], { ns: 'common' }))
- return false
- }
+ if (itemIndex < 0) return
+ setAllChatItems(applyAnnotationRemoved(allChatItems, itemIndex))
},
- [allChatItems, appDetail.id, t, threadChatItems],
+ [allChatItems, threadChatItems],
)
const [isLoading, setIsLoading] = useState(false)
@@ -432,7 +416,7 @@ export function ConversationDetail({ appDetail, conversationId }: ConversationDe
return (
<div className="flex min-h-0 flex-1 flex-col rounded-xl border-[0.5px] border-components-panel-border">
- <div className="flex shrink-0 items-center gap-2 rounded-t-xl bg-components-panel-bg pt-3 pr-3 pb-2 pl-4">
+ <div className="flex shrink-0 items-center gap-2 rounded-t-xl bg-components-panel-bg ps-4 pe-3 pt-3 pb-2">
<div className="min-w-0">
<DialogTitle className="sr-only">
{isChatMode
diff --git a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
index 03e3106af41..c16fc14b2e0 100644
--- a/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
+++ b/web/app/components/base/chat/chat/answer/__tests__/operation.spec.tsx
@@ -14,26 +14,39 @@ import {
import { ChatContextProvider } from '../../context-provider'
import Operation from '../operation'
-const { mockAddAnnotation, mockEditAnnotation, mockGetAudioPlayer, mockPlayAudio } = vi.hoisted(
- () => {
- return {
- mockAddAnnotation:
- vi.fn<typeof import('@/service/console').consoleClient.apps.byAppId.annotations.post>(),
- mockEditAnnotation:
- vi.fn<
- typeof import('@/service/console').consoleClient.apps.byAppId.annotations.byAnnotationId.post
- >(),
- mockGetAudioPlayer: vi.fn(),
- mockPlayAudio: vi.fn(),
- }
- },
-)
+const {
+ mockAddAnnotation,
+ mockEditAnnotation,
+ mockRemoveAnnotation,
+ mockGetAudioPlayer,
+ mockPlayAudio,
+} = vi.hoisted(() => {
+ return {
+ mockAddAnnotation:
+ vi.fn<typeof import('@/service/console').consoleClient.apps.byAppId.annotations.post>(),
+ mockEditAnnotation:
+ vi.fn<
+ typeof import('@/service/console').consoleClient.apps.byAppId.annotations.byAnnotationId.post
+ >(),
+ mockRemoveAnnotation:
+ vi.fn<
+ typeof import('@/service/console').consoleClient.apps.byAppId.annotations.byAnnotationId.delete
+ >(),
+ mockGetAudioPlayer: vi.fn(),
+ mockPlayAudio: vi.fn(),
+ }
+})
vi.mock('@/service/console', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/service/console')>()
- const { withConsoleClientResponses } = await import('@/test/console/service-responses')
+ const { withConsoleClientResponses, withConsoleResponses } =
+ await import('@/test/console/service-responses')
return {
...actual,
+ consoleQuery: withConsoleResponses(actual.consoleQuery, {
+ 'apps.byAppId.annotations.byAnnotationId.post': (input) => mockEditAnnotation(input),
+ 'apps.byAppId.annotations.byAnnotationId.delete': (input) => mockRemoveAnnotation(input),
+ }),
consoleClient: withConsoleClientResponses(actual.consoleClient, {
'apps.byAppId.annotations.post': mockAddAnnotation,
'apps.byAppId.annotations.byAnnotationId.post': mockEditAnnotation,
@@ -126,6 +139,7 @@ describe('Operation', () => {
mockContextValue.onOpenLog = undefined
mockAddAnnotation.mockReset().mockResolvedValue({ id: 'ann-new' })
+ mockRemoveAnnotation.mockReset().mockResolvedValue(undefined)
mockEditAnnotation.mockReset().mockResolvedValue({ id: 'ann-1' })
mockGetAudioPlayer
.mockReset()
@@ -383,19 +397,22 @@ describe('Operation', () => {
const annotatedItem = { ...baseItem, annotation: { id: 'ann-1', authorName: 'Author' } }
- it('edits an annotation through the real drawer and forwards the saved answer', async () => {
+ it('edits an annotation through the real dialog and forwards the saved answer', async () => {
const user = userEvent.setup()
mockContextValue.config = makeChatConfig(annotationConfig)
renderOperation({ ...baseProps, item: annotatedItem })
await user.click(screen.getByRole('button', { name: 'appDebug.feature.annotation.edit' }))
const drawer = await screen.findByRole('dialog', { name: 'appAnnotation.editModal.title' })
await user.click(within(drawer).getAllByRole('button', { name: 'common.operation.edit' })[1]!)
+ await user.clear(
+ within(drawer).getByRole('textbox', { name: 'appAnnotation.editModal.yourAnswer' }),
+ )
await user.type(
within(drawer).getByRole('textbox', { name: 'appAnnotation.editModal.yourAnswer' }),
'Corrected answer',
)
await user.click(within(drawer).getByRole('button', { name: 'common.operation.save' }))
- expect(await screen.findByText('common.api.actionSuccess')).toBeInTheDocument()
+ await waitFor(() => expect(within(drawer).queryByRole('textbox')).not.toBeInTheDocument())
expect(mockEditAnnotation).toHaveBeenCalledExactlyOnceWith({
params: { app_id: 'test-app', annotation_id: 'ann-1' },
body: { question: 'What is this?', answer: 'Corrected answer' },
@@ -426,7 +443,12 @@ describe('Operation', () => {
expect(mockContextValue.onAnnotationRemoved).not.toHaveBeenCalled()
await user.click(remove)
await user.click(screen.getByRole('button', { name: 'common.operation.confirm' }))
- expect(mockContextValue.onAnnotationRemoved).toHaveBeenCalledExactlyOnceWith(0)
+ await waitFor(() =>
+ expect(mockContextValue.onAnnotationRemoved).toHaveBeenCalledExactlyOnceWith(0),
+ )
+ expect(mockRemoveAnnotation).toHaveBeenCalledExactlyOnceWith({
+ params: { app_id: 'test-app', annotation_id: 'ann-1' },
+ })
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())
})
diff --git a/web/app/components/base/chat/chat/answer/operation.tsx b/web/app/components/base/chat/chat/answer/operation.tsx
index 39fec6badef..f99d52497f2 100644
--- a/web/app/components/base/chat/chat/answer/operation.tsx
+++ b/web/app/components/base/chat/chat/answer/operation.tsx
@@ -21,7 +21,7 @@ import { Toggle } from '@langgenius/dify-ui/toggle'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
import { memo, useId, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
-import EditReplyModal from '@/app/components/app/annotation/edit-annotation-modal'
+import EditAnnotationDialog from '@/app/components/app/annotation/edit-annotation-modal'
import Log from '@/app/components/base/chat/chat/log'
import { CopyFeedback } from '@/app/components/base/copy-feedback'
import AnnotationCtrlButton from '@/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button'
@@ -166,7 +166,6 @@ function Operation({
showRegenerate,
readonly,
} = useChatContext()
- const [isShowReplyModal, setIsShowReplyModal] = useState(false)
// Submitting replaces the dialog trigger with the current rating button.
const feedbackRef = useRef<HTMLButtonElement>(null)
const feedbackActionsRef = useRef<DialogActions>(null)
@@ -292,8 +291,8 @@ function Operation({
<div
className={cn(
'absolute flex justify-end gap-1',
- hasWorkflowProcess && 'right-2 -bottom-4',
- !positionRight && 'right-2 -bottom-4',
+ hasWorkflowProcess && 'inset-e-2 -bottom-4',
+ !positionRight && 'inset-e-2 -bottom-4',
!hasWorkflowProcess && positionRight && 'top-2.25!',
)}
style={!hasWorkflowProcess && positionRight ? { left: contentWidth + 8 } : {}}
@@ -309,7 +308,7 @@ function Operation({
{shouldShowUserFeedbackBar && !humanInputFormDataList?.length && (
<div
className={cn(
- 'ml-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
+ 'ms-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
hasUserFeedback ? 'flex' : feedbackActionsClassName,
)}
>
@@ -368,7 +367,7 @@ function Operation({
{shouldShowAdminFeedbackBar && !humanInputFormDataList?.length && (
<div
className={cn(
- 'ml-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
+ 'ms-1 items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
hasAdminFeedback || hasUserFeedback ? 'flex' : feedbackActionsClassName,
)}
>
@@ -474,7 +473,7 @@ function Operation({
{!isOpeningStatement && (
<div
className={cn(
- 'ml-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
+ 'ms-1 hidden items-center gap-0.5 rounded-[10px] border-[0.5px] border-components-actionbar-border bg-components-actionbar-bg p-0.5 shadow-md backdrop-blur-xs',
answerActiveFlexClassName,
)}
data-testid="operation-actions"
@@ -492,37 +491,31 @@ function Operation({
<span aria-hidden="true" className="i-ri-reset-left-line size-4" />
</IconButton>
)}
- {shouldShowAnnotationAction && (
- <AnnotationCtrlButton
- appId={config?.appId || ''}
- messageId={id}
- cached={!!annotation?.id}
- query={question}
- answer={content}
- onAdded={(id, authorName) =>
- onAnnotationAdded?.(id, authorName, question, content, index)
- }
- onEdit={() => setIsShowReplyModal(true)}
- />
- )}
+ {shouldShowAnnotationAction &&
+ (annotation?.id ? (
+ <EditAnnotationDialog
+ appId={config?.appId || ''}
+ annotationId={annotation.id}
+ question={question}
+ answer={content}
+ createdAt={annotation.created_at}
+ onEdited={(question, answer) => onAnnotationEdited?.(question, answer, index)}
+ onRemoved={() => onAnnotationRemoved?.(index)}
+ />
+ ) : (
+ <AnnotationCtrlButton
+ appId={config?.appId || ''}
+ messageId={id}
+ query={question}
+ answer={content}
+ onAdded={(id, authorName) =>
+ onAnnotationAdded?.(id, authorName, question, content, index)
+ }
+ />
+ ))}
</div>
)}
</div>
- {canManageAnnotation && annotation?.id && isShowReplyModal && (
- <EditReplyModal
- isShow
- onHide={() => setIsShowReplyModal(false)}
- query={question}
- answer={content}
- onEdited={(editedQuery, editedAnswer) =>
- onAnnotationEdited?.(editedQuery, editedAnswer, index)
- }
- appId={config?.appId || ''}
- annotationId={annotation.id}
- createdAt={annotation?.created_at}
- onRemove={() => onAnnotationRemoved?.(index)}
- />
- )}
</>
)
}
diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx
index 76e29a3fcca..662ff2f6b59 100644
--- a/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx
+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/__tests__/annotation-ctrl-button.spec.tsx
@@ -51,36 +51,8 @@ describe('AnnotationCtrlButton', () => {
api.addAnnotation.mockResolvedValue({ id: 'annotation-1' })
})
- it('should call onEdit when edit button is clicked', async () => {
- const user = userEvent.setup()
- const onEdit = vi.fn()
- render(
- <AnnotationCtrlButton
- appId="test-app"
- cached={true}
- query="test query"
- answer="test answer"
- onAdded={vi.fn()}
- onEdit={onEdit}
- />,
- )
-
- await user.click(screen.getByRole('button', { name: 'appDebug.feature.annotation.edit' }))
-
- expect(onEdit).toHaveBeenCalled()
- })
-
it('should not render any button when not cached and no answer', () => {
- render(
- <AnnotationCtrlButton
- appId="test-app"
- cached={false}
- query="test query"
- answer=""
- onAdded={vi.fn()}
- onEdit={vi.fn()}
- />,
- )
+ render(<AnnotationCtrlButton appId="test-app" query="test query" answer="" onAdded={vi.fn()} />)
expect(screen.queryByRole('button')).not.toBeInTheDocument()
})
@@ -92,11 +64,9 @@ describe('AnnotationCtrlButton', () => {
<AnnotationCtrlButton
appId="test-app"
messageId="msg-1"
- cached={false}
query="test query"
answer="test answer"
onAdded={onAdded}
- onEdit={vi.fn()}
/>,
)
@@ -118,11 +88,9 @@ describe('AnnotationCtrlButton', () => {
render(
<AnnotationCtrlButton
appId="test-app"
- cached={false}
query="test query"
answer="test answer"
onAdded={vi.fn()}
- onEdit={vi.fn()}
/>,
)
diff --git a/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx b/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx
index 05f7e7c035d..ebfa27e46d8 100644
--- a/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx
+++ b/web/app/components/base/features/new-feature-panel/annotation-reply/annotation-ctrl-button.tsx
@@ -1,35 +1,29 @@
'use client'
-import type { FC } from 'react'
import { IconButton } from '@langgenius/dify-ui/icon-button'
import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'
-import { RiEditLine, RiFileEditLine } from '@remixicon/react'
+import { RiFileEditLine } from '@remixicon/react'
import { useQuery } from '@tanstack/react-query'
import { useAtomValue } from 'jotai'
-import * as React from 'react'
import { useTranslation } from 'react-i18next'
import { toast } from '@/app/notifications'
import { useModalContext } from '@/context/modal-context'
import { deploymentEditionAtom } from '@/features/system-features/state'
import { consoleClient, consoleQuery } from '@/service/console'
-type Props = Readonly<{
+type AnnotationCtrlButtonProps = {
appId: string
messageId?: string
- cached: boolean
query: string
answer: string
onAdded: (annotationId: string, authorName: string) => void
- onEdit: () => void
-}>
-const AnnotationCtrlButton: FC<Props> = ({
- cached,
+}
+export default function AnnotationCtrlButton({
query,
answer,
appId,
messageId,
onAdded,
- onEdit,
-}) => {
+}: AnnotationCtrlButtonProps) {
const { t } = useTranslation(['appDebug', 'common'])
const deploymentEdition = useAtomValue(deploymentEditionAtom)
const { data: annotationQuota } = useQuery(
@@ -63,24 +57,7 @@ const AnnotationCtrlButton: FC<Props> = ({
}
return (
<>
- {cached && (
- <Tooltip>
- <TooltipTrigger
- render={
- <IconButton
- aria-label={t(($) => $['feature.annotation.edit'], { ns: 'appDebug' })}
- onClick={onEdit}
- >
- <RiEditLine aria-hidden className="size-4" />
- </IconButton>
- }
- />
- <TooltipContent>
- {t(($) => $['feature.annotation.edit'], { ns: 'appDebug' })}
- </TooltipContent>
- </Tooltip>
- )}
- {!cached && answer && (
+ {answer && (
<Tooltip>
<TooltipTrigger
render={
@@ -101,4 +78,3 @@ const AnnotationCtrlButton: FC<Props> = ({
</>
)
}
-export default React.memo(AnnotationCtrlButton)
diff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.ts
index 4890b96f9a6..476184ddeff 100644
--- a/web/service/console/query-policies.ts
+++ b/web/service/console/query-policies.ts
@@ -978,6 +978,37 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {
},
byAppId: {
annotations: {
+ byAnnotationId: {
+ post: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.annotations.key({
+ input: { params: { app_id: variables.params.app_id } },
+ }),
+ })
+ },
+ },
+ },
+ delete: {
+ mutationOptions: {
+ onSettled: (_data, error, variables, _result, context) => {
+ if (error) return
+ return Promise.all([
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.apps.byAppId.annotations.key({
+ input: { params: { app_id: variables.params.app_id } },
+ }),
+ }),
+ context.client.invalidateQueries({
+ queryKey: consoleQuery.features.get.key(),
+ }),
+ ])
+ },
+ },
+ },
+ },
post: {
mutationOptions: {
onSettled: (_data, error, variables, _result, context) => {