Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
fix(web): preserve annotation drafts with a positioned dialog (#44810)
yyh1df903c036df
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex 6d05a9e0bc8..91591e9713c 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -173,28 +173,6 @@"count": 5}},- "web/app/components/app/annotation/add-annotation-modal/edit-item/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "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/add-annotation-modal/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 2- }- },"web/app/components/app/annotation/batch-action.tsx": {"better-tailwindcss/enforce-logical-properties": {"count": 2@@ -259,15 +237,7 @@"count": 2}},- "web/app/components/app/annotation/header-opts/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 1- }- },"web/app/components/app/annotation/index.tsx": {- "better-tailwindcss/enforce-logical-properties": {- "count": 5- },"eslint-react/set-state-in-effect": {"count": 1},diff --git a/web/app/components/app/annotation/__tests__/index.spec.tsx b/web/app/components/app/annotation/__tests__/index.spec.tsxindex cef6973f21c..38de20ec831 100644--- a/web/app/components/app/annotation/__tests__/index.spec.tsx+++ b/web/app/components/app/annotation/__tests__/index.spec.tsx@@ -13,11 +13,16 @@ import {createModelCatalogFixture,seedModelProviderQueries,} from '@/test/console/model-provider'-import { createConsoleQueryClient, renderWithConsoleQuery } from '@/test/console/query-data'+import {+ createConsoleQueryClient,+ renderWithConsoleQuery,+ seedFeatures,+} from '@/test/console/query-data'import { createAppDetailFixture } from '@/test/fixtures/app'import Annotation from '../index'const api = vi.hoisted(() => ({+ features: vi.fn<typeof consoleClient.features.get>(),list: vi.fn<typeof consoleClient.apps.byAppId.annotations.get>(),add: vi.fn<typeof consoleClient.apps.byAppId.annotations.post>(),remove: vi.fn<typeof consoleClient.apps.byAppId.annotations.byAnnotationId.delete>(),@@ -36,7 +41,9 @@ vi.mock('@/service/console', async (importOriginal) => {return {...actual,consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'features.get': () => api.features(),'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.delete': (input) => api.batchRemove(input),}),@@ -115,6 +122,7 @@ function setup(quota = { size: 0, limit: 10 }) {features: { annotation_quota_limit: quota },},)+ api.features.mockResolvedValue(seedFeatures(queryClient, { annotation_quota_limit: quota }))return userEvent.setup()}diff --git a/web/app/components/app/annotation/add-annotation-modal/__tests__/index.browser.spec.tsx b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.browser.spec.tsxnew file mode 100644index 00000000000..2fc4557ac29--- /dev/null+++ b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.browser.spec.tsx@@ -0,0 +1,84 @@+import type { consoleClient } from '@/service/console'+import { QueryClient } from '@tanstack/react-query'+import { userEvent } from 'vite-plus/test/browser'+import { render } from 'vitest-browser-react'+import { seedSystemFeatures } from '@/test/console/query-data'+import { QueryClientTestProvider } from '@/test/console/query-provider'+import AddAnnotationDialog from '../index'++const api = vi.hoisted(() => ({+ add: vi.fn<typeof consoleClient.apps.byAppId.annotations.post>(),+}))++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('@/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.post': (input) => api.add(input),+ }),+ }+})++it('resets a continuous-entry form without losing its preference or skipping native required validation', async () => {+ api.add.mockResolvedValue({ id: 'annotation-id' })+ const client = new QueryClient({+ defaultOptions: { queries: { staleTime: Infinity, retry: false } },+ })+ seedSystemFeatures(client, { deployment_edition: 'COMMUNITY' })+ const screen = await render(+ <QueryClientTestProvider queryClient={client}>+ <AddAnnotationDialog appId="app-id" onAdded={() => {}} />+ </QueryClientTestProvider>,+ )+ const trigger = screen.getByRole('button', { name: 'appAnnotation.table.header.addAnnotation' })+ await trigger.click()+ const dialog = screen.getByRole('dialog', { name: 'appAnnotation.addModal.title' })+ const question = dialog.getByRole('textbox', { name: 'appAnnotation.addModal.queryName' })+ const answer = dialog.getByRole('textbox', { name: 'appAnnotation.addModal.answerName' })+ const next = dialog.getByRole('checkbox', { name: 'appAnnotation.addModal.createNext' })+ const submit = dialog.getByRole('button', { name: 'common.operation.add' })++ await question.fill('First question')+ await answer.fill('First answer')+ await next.click()+ await submit.click()+ await expect.element(question).toHaveValue('')+ await expect.element(answer).toHaveValue('')+ await expect.element(question).toHaveFocus()+ await expect.element(next).toBeChecked()++ // Exercise native reset, externally associated submit, and browser constraint validation together.+ await submit.click()+ await expect.element(question).toHaveFocus()+ await expect.element(question).toHaveAttribute('aria-invalid', 'true')+ await expect.element(dialog.getByText('appAnnotation.errorMessage.queryRequired')).toBeVisible()+ await expect.element(dialog.getByText('appAnnotation.errorMessage.answerRequired')).toBeVisible()+ expect(api.add).toHaveBeenCalledOnce()++ await question.fill('Second question')+ await answer.fill('Second answer')+ await next.click()+ await submit.click()+ await expect.element(dialog).not.toBeInTheDocument()+ await expect.element(trigger).toHaveFocus()+ expect(api.add).toHaveBeenLastCalledWith({+ params: { app_id: 'app-id' },+ body: { question: 'Second question', answer: 'Second answer' },+ })+ await userEvent.keyboard('{Enter}')+ await expect.element(question).toHaveValue('')+ await expect.element(answer).toHaveValue('')+ await expect.element(next).not.toBeChecked()+ await expect+ .element(dialog.getByText('appAnnotation.errorMessage.queryRequired'))+ .not.toBeInTheDocument()+ client.clear()+})diff --git a/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsxindex eeff05ab881..6ac20167eee 100644--- a/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx+++ b/web/app/components/app/annotation/add-annotation-modal/__tests__/index.spec.tsx@@ -1,136 +1,186 @@-import type { ReactElement } from 'react'+import type { consoleClient } from '@/service/console'+import { zGetFeaturesResponse } from '@dify/contracts/api/console/features/zod.gen'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'-import * as React from 'react'-import { renderWithConsoleQuery } from '@/test/console/query-data'-import AddAnnotationModal from '../index'+import { renderWithConsoleQuery, seedFeatures } from '@/test/console/query-data'+import { createDeferred } from '@/test/deferred'+import AddAnnotationDialog from '../index'-const mockToastNotify = vi.fn()-vi.mock('@/app/notifications', () => ({- default: {- notify: vi.fn((args) => mockToastNotify(args)),- },- toast: {- success: (message: string) => mockToastNotify({ type: 'success', message }),- error: (message: string) => mockToastNotify({ type: 'error', message }),- warning: (message: string) => mockToastNotify({ type: 'warning', message }),- info: (message: string) => mockToastNotify({ type: 'info', message }),- },+const api = vi.hoisted(() => ({+ add: vi.fn<typeof consoleClient.apps.byAppId.annotations.post>(),+ features: vi.fn<typeof consoleClient.features.get>(),}))+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.post': (input) => api.add(input),+ 'features.get': () => api.features(),+ }),+ }+})+vi.mock('@/app/components/billing/annotation-full', () => ({- default: () => <div data-testid="annotation-full" />,+ default: () => <p>Annotation quota full</p>,}))-let annotationQuota = { size: 0, limit: 10 }--function render(ui: ReactElement) {- return renderWithConsoleQuery(ui, {- systemFeatures: { deployment_edition: 'CLOUD' },- features: { annotation_quota_limit: annotationQuota },+const question = () => screen.getByRole('textbox', { name: 'appAnnotation.addModal.queryName' })+const answer = () => screen.getByRole('textbox', { name: 'appAnnotation.addModal.answerName' })+const submit = () => screen.getByRole('button', { name: 'common.operation.add' })+const next = () => screen.getByRole('checkbox', { name: 'appAnnotation.addModal.createNext' })+const trigger = () =>+ screen.getByRole('button', { name: 'appAnnotation.table.header.addAnnotation' })++async function setup(quota = { size: 0, limit: 10 }, cloud = true) {+ const user = userEvent.setup()+ const onAdded = vi.fn()+ const view = renderWithConsoleQuery(<AddAnnotationDialog appId="app-id" onAdded={onAdded} />, {+ systemFeatures: { deployment_edition: cloud ? 'CLOUD' : 'COMMUNITY' },+ features: { annotation_quota_limit: quota },})+ const features = seedFeatures(view.queryClient, { annotation_quota_limit: quota })+ api.features.mockResolvedValue(features)+ await user.click(trigger())+ return { user, onAdded, features }}-describe('AddAnnotationModal', () => {- const baseProps = {- isShow: true,- onHide: vi.fn(),- onAdd: vi.fn(),- }-- beforeEach(() => {- vi.clearAllMocks()- annotationQuota = { size: 0, limit: 10 }- })-- const fill = async (- user: ReturnType<typeof userEvent.setup>,- field: 'query' | 'answer',- value: string,- ) => {- await user.type(- screen.getByPlaceholderText(`appAnnotation.addModal.${field}Placeholder`),- value,- )- }-- it('should show annotation full notice and disable submit when quota exceeded', () => {- annotationQuota = { size: 10, limit: 10 }- render(<AddAnnotationModal {...baseProps} />)-- expect(screen.getByTestId('annotation-full')).toBeInTheDocument()- expect(screen.getByRole('button', { name: 'common.operation.add' })).toBeDisabled()- })-- it('should reset fields after saving when create next enabled', async () => {- const user = userEvent.setup()- const onAdd = vi.fn().mockResolvedValue(undefined)- render(<AddAnnotationModal {...baseProps} onAdd={onAdd} />)-- await fill(user, 'query', 'Question value')- await fill(user, 'answer', 'Answer value')- await user.click(screen.getByText('appAnnotation.addModal.createNext'))-- await user.click(screen.getByRole('button', { name: 'common.operation.add' }))-- expect(onAdd).toHaveBeenCalledWith({ question: 'Question value', answer: 'Answer value' })- expect(baseProps.onHide).not.toHaveBeenCalled()- await waitFor(() => {- expect(screen.getByPlaceholderText('appAnnotation.addModal.queryPlaceholder')).toHaveValue('')- expect(screen.getByPlaceholderText('appAnnotation.addModal.answerPlaceholder')).toHaveValue(- '',- )- })- })-- it('should show toast when validation fails for missing question', async () => {- const user = userEvent.setup()- render(<AddAnnotationModal {...baseProps} />)+async function fill(user: ReturnType<typeof userEvent.setup>) {+ await user.type(question(), 'Question value')+ await user.type(answer(), 'Answer value')+}- await user.click(screen.getByRole('button', { name: 'common.operation.add' }))- expect(baseProps.onAdd).not.toHaveBeenCalled()- expect(mockToastNotify).toHaveBeenCalledWith(- expect.objectContaining({- type: 'error',- message: 'appAnnotation.errorMessage.queryRequired',- }),- )- })+beforeEach(() => {+ vi.resetAllMocks()+ api.add.mockResolvedValue({ id: 'annotation-id' })+})- it('should show toast when validation fails for missing answer', async () => {- const user = userEvent.setup()- render(<AddAnnotationModal {...baseProps} />)- await fill(user, 'query', 'Filled question')- await user.click(screen.getByRole('button', { name: 'common.operation.add' }))+it('validates required fields inline before sending a request', async () => {+ const { user } = await setup()+ await user.click(submit())+ expect(api.add).not.toHaveBeenCalled()+ expect(await screen.findByText('appAnnotation.errorMessage.queryRequired')).toBeVisible()+ expect(screen.getByText('appAnnotation.errorMessage.answerRequired')).toBeVisible()+ expect(question()).toHaveAttribute('aria-invalid', 'true')+ await user.type(question(), 'Question')+ await user.click(submit())+ expect(api.add).not.toHaveBeenCalled()+ expect(screen.getByText('appAnnotation.errorMessage.answerRequired')).toBeVisible()+})- expect(baseProps.onAdd).not.toHaveBeenCalled()- expect(mockToastNotify).toHaveBeenCalledWith(- expect.objectContaining({- type: 'error',- message: 'appAnnotation.errorMessage.answerRequired',- }),- )+it('creates an annotation, refreshes its owner, and closes on success', async () => {+ const { user, onAdded } = await setup()+ await fill(user)+ await user.click(submit())+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ expect(api.add).toHaveBeenCalledExactlyOnceWith({+ params: { app_id: 'app-id' },+ body: { question: 'Question value', answer: 'Answer value' },})+ expect(onAdded).toHaveBeenCalledOnce()+ expect(api.features).toHaveBeenCalled()+})- it('should close modal when save completes and create next unchecked', async () => {- const user = userEvent.setup()- const onAdd = vi.fn().mockResolvedValue(undefined)- render(<AddAnnotationModal {...baseProps} onAdd={onAdd} />)-- await fill(user, 'query', 'Q')- await fill(user, 'answer', 'A')+it.each([false, true])(+ 'preserves a failed draft for retry with create next %s',+ async (createNext) => {+ api.add.mockRejectedValueOnce(new Error('Save failed'))+ const { user, onAdded } = await setup()+ await fill(user)+ if (createNext) await user.click(next())+ await user.click(submit())+ await waitFor(() => expect(submit()).not.toHaveAttribute('aria-disabled', 'true'))+ expect(await screen.findByRole('alert')).toHaveTextContent('common.api.actionFailed')+ expect(question()).toHaveValue('Question value')+ expect(answer()).toHaveValue('Answer value')+ expect(onAdded).not.toHaveBeenCalled()+ await user.click(submit())+ await waitFor(() => expect(onAdded).toHaveBeenCalledOnce())+ expect(api.add).toHaveBeenCalledTimes(2)+ if (createNext) {+ await waitFor(() => expect(question()).toHaveValue(''))+ expect(answer()).toHaveValue('')+ expect(next()).toBeChecked()+ } else {+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ }+ },+)++it('keeps the in-flight draft stable and prevents duplicate submission or dismissal', async () => {+ const request =+ createDeferred<Awaited<ReturnType<typeof consoleClient.apps.byAppId.annotations.post>>>()+ api.add.mockReturnValue(request.promise)+ const { user } = await setup()+ await fill(user)+ await user.click(submit())+ await waitFor(() => expect(submit()).toHaveAttribute('aria-disabled', 'true'))+ expect(question()).toHaveAttribute('readonly')+ expect(answer()).toHaveAttribute('readonly')+ expect(next()).toHaveAttribute('aria-disabled', 'true')+ expect(screen.getByRole('button', { name: 'common.operation.cancel' })).toBeDisabled()+ expect(screen.getByRole('button', { name: 'common.operation.close' })).toBeDisabled()+ await user.keyboard('{Escape}')+ await user.click(submit())+ expect(screen.getByRole('dialog')).toBeVisible()+ expect(api.add).toHaveBeenCalledOnce()+ request.resolve({ id: 'annotation-id' })+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+})- await user.click(screen.getByRole('button', { name: 'common.operation.add' }))+it('starts a fresh form after cancel and reopen', async () => {+ const { user } = await setup()+ await fill(user)+ await user.click(next())+ await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument())+ await user.click(trigger())+ expect(question()).toHaveValue('')+ expect(answer()).toHaveValue('')+ expect(next()).not.toBeChecked()+})- expect(onAdd).toHaveBeenCalledWith({ question: 'Q', answer: 'A' })- expect(baseProps.onHide).toHaveBeenCalled()- })+it('rechecks quota after creation before allowing the next annotation', async () => {+ const { user, features } = await setup({ size: 9, limit: 10 })+ await fill(user)+ await user.click(next())+ api.features.mockResolvedValue({ ...features, annotation_quota_limit: { size: 10, limit: 10 } })+ await user.click(submit())+ expect(await screen.findByText('Annotation quota full')).toBeVisible()+ expect(submit()).toBeDisabled()+ expect(api.add).toHaveBeenCalledOnce()+})- it('should allow cancel button to close the drawer', async () => {- const user = userEvent.setup()- render(<AddAnnotationModal {...baseProps} />)+it.each([+ { quota: { size: 10, limit: 10 }, cloud: true, disabled: true },+ { quota: { size: 10, limit: 0 }, cloud: true, disabled: false },+ { quota: { size: 10, limit: 10 }, cloud: false, disabled: false },+])('honors quota $quota.limit with cloud=$cloud', async ({ quota, cloud, disabled }) => {+ await setup(quota, cloud)+ if (disabled) expect(submit()).toBeDisabled()+ else expect(submit()).toBeEnabled()+})- await user.click(screen.getByRole('button', { name: 'common.operation.cancel' }))- expect(baseProps.onHide).toHaveBeenCalled()+it('blocks saving until quota loads and lets a failed quota request retry', async () => {+ const request = createDeferred<Awaited<ReturnType<typeof consoleClient.features.get>>>()+ api.features.mockReturnValueOnce(request.promise)+ const user = userEvent.setup()+ renderWithConsoleQuery(<AddAnnotationDialog appId="app-id" onAdded={vi.fn()} />, {+ systemFeatures: { deployment_edition: 'CLOUD' },})+ await user.click(trigger())+ expect(submit()).toBeDisabled()+ request.reject(new Error('Quota unavailable'))+ const retry = await screen.findByRole('button', { name: 'common.operation.retry' })+ expect(screen.getByRole('alert')).toHaveTextContent('common.api.actionFailed')+ expect(submit()).toBeDisabled()+ api.features.mockResolvedValue(+ zGetFeaturesResponse.parse({ annotation_quota_limit: { size: 0, limit: 10 } }),+ )+ await user.click(retry)+ await waitFor(() => expect(submit()).toBeEnabled())+ expect(screen.queryByRole('alert')).not.toBeInTheDocument()+ expect(api.add).not.toHaveBeenCalled()})diff --git a/web/app/components/app/annotation/add-annotation-modal/edit-item/index.tsx b/web/app/components/app/annotation/add-annotation-modal/edit-item/index.tsxdeleted file mode 100644index d18870af1f5..00000000000--- a/web/app/components/app/annotation/add-annotation-modal/edit-item/index.tsx+++ /dev/null@@ -1,53 +0,0 @@-'use client'-import type { FC } from 'react'-import { Textarea } from '@langgenius/dify-ui/textarea'-import * as React from 'react'-import { useTranslation } from 'react-i18next'-import robotAvatar from '../../assets/robot-avatar.svg'--export const EditItemType = {- Query: 'query',- Answer: 'answer',-} as const--export type EditItemType = (typeof EditItemType)[keyof typeof EditItemType]-type Props = Readonly<{- type: EditItemType- content: string- onChange: (content: string) => void-}>--const EditItem: FC<Props> = ({ type, content, onChange }) => {- const { t } = useTranslation(['appAnnotation'])- 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(($) => $['addModal.queryName'], { ns: 'appAnnotation' })- : t(($) => $['addModal.answerName'], { ns: 'appAnnotation' })- const placeholder =- type === EditItemType.Query- ? t(($) => $['addModal.queryPlaceholder'], { ns: 'appAnnotation' })- : t(($) => $['addModal.answerPlaceholder'], { ns: 'appAnnotation' })-- 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>- <Textarea- aria-label={name}- value={content}- onValueChange={(value) => onChange(value)}- placeholder={placeholder}- autoFocus- />- </div>- </div>- )-}-export default React.memo(EditItem)diff --git a/web/app/components/app/annotation/add-annotation-modal/index.tsx b/web/app/components/app/annotation/add-annotation-modal/index.tsxindex 19fbfe28a31..3b9dbaa67f2 100644--- a/web/app/components/app/annotation/add-annotation-modal/index.tsx+++ b/web/app/components/app/annotation/add-annotation-modal/index.tsx@@ -1,164 +1,213 @@'use client'-import type { FC } from 'react'-import type { AnnotationItemBasic } from '../type'++import type { CreateAnnotationPayload } from '@dify/contracts/api/console/apps/types.gen'import { Button } from '@langgenius/dify-ui/button'import { Checkbox } from '@langgenius/dify-ui/checkbox'import {- Drawer,- DrawerBackdrop,- DrawerClose,- DrawerContent,- DrawerPopup,- DrawerPortal,- DrawerTitle,- DrawerViewport,-} from '@langgenius/dify-ui/drawer'-import { IconButton } from '@langgenius/dify-ui/icon-button'-import { useQuery } from '@tanstack/react-query'+ Dialog,+ DialogBackdrop,+ DialogBody,+ DialogClose,+ DialogFooter,+ DialogHeader,+ DialogHeaderCloseButton,+ DialogPopup,+ 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'+import { Textarea } from '@langgenius/dify-ui/textarea'+import { useMutation, useQuery } from '@tanstack/react-query'import { useAtomValue } from 'jotai'-import * as React from 'react'-import { useState } from 'react'+import { useId, useRef, useState } from 'react'import { useTranslation } from 'react-i18next'import AnnotationFull from '@/app/components/billing/annotation-full'-import { toast } from '@/app/notifications'import { deploymentEditionAtom } from '@/features/system-features/state'import { consoleQuery } from '@/service/console'-import EditItem, { EditItemType } from './edit-item'+import robotAvatar from '../assets/robot-avatar.svg'-type Props = Readonly<{- isShow: boolean- onHide: () => void- onAdd: (payload: AnnotationItemBasic) => void-}>+type Props = {+ appId: string+ onAdded: () => void+}-const AddAnnotationModal: FC<Props> = ({ isShow, onHide, onAdd }) => {+type FormProps = {+ isPending: boolean+ isError: boolean+ onSave: (body: CreateAnnotationPayload, onSuccess: () => void) => void+ onClose: () => void+}++function AddAnnotationForm({ isPending, isError, onSave, onClose }: FormProps) {const { t } = useTranslation(['appAnnotation', 'common'])const deploymentEdition = useAtomValue(deploymentEditionAtom)- const { data: annotationQuota } = useQuery(+ const quota = useQuery(consoleQuery.features.get.queryOptions({enabled: deploymentEdition === 'CLOUD',select: (data) => data.annotation_quota_limit,}),)- const isAnnotationQuotaUnavailable =- deploymentEdition === 'CLOUD' && annotationQuota === undefined+ const quotaUnavailable = deploymentEdition === 'CLOUD' && quota.data === undefined// A limit of 0 means unlimited.- const isAnnotationFull =+ const quotaFull =deploymentEdition === 'CLOUD' &&- annotationQuota !== undefined &&- annotationQuota.limit > 0 &&- annotationQuota.size >= annotationQuota.limit- const [question, setQuestion] = useState('')- const [answer, setAnswer] = useState('')- const [isCreateNext, setIsCreateNext] = useState(false)- const [isSaving, setIsSaving] = useState(false)-- const isValid = (payload: AnnotationItemBasic) => {- if (!payload.question) return t(($) => $['errorMessage.queryRequired'], { ns: 'appAnnotation' })-- if (!payload.answer) return t(($) => $['errorMessage.answerRequired'], { ns: 'appAnnotation' })-- return true- }-- const handleSave = async () => {- if (isAnnotationQuotaUnavailable || isAnnotationFull) return- const payload = {- question,- answer,- }- if (isValid(payload) !== true) {- toast.error(isValid(payload) as string)- return- }-- setIsSaving(true)- try {- await onAdd(payload)- } catch {}- setIsSaving(false)-- if (isCreateNext) {- setQuestion('')- setAnswer('')- } else {- onHide()- }- }- if (!isShow) return null+ quota.data !== undefined &&+ quota.data.limit > 0 &&+ quota.data.size >= quota.data.limit+ const formId = useId()+ const formRef = useRef<HTMLFormElement>(null)+ const questionRef = useRef<HTMLTextAreaElement>(null)+ const [createNext, setCreateNext] = useState(false)return (- <div>- <Drawer- open- modal- disablePointerDismissal- swipeDirection="right"- onOpenChange={(open) => {- if (!open) onHide()+ <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"+ >+ <DialogHeader>+ <DialogTitle>{t(($) => $['addModal.title'], { ns: 'appAnnotation' })}</DialogTitle>+ <DialogHeaderCloseButton+ aria-label={t(($) => $['operation.close'], { ns: 'common' })}+ disabled={isPending}+ />+ </DialogHeader>+ <Form<CreateAnnotationPayload>+ id={formId}+ ref={formRef}+ className="contents"+ onFormSubmit={(values) => {+ if (isPending || quotaUnavailable || quotaFull) return+ onSave(values, () => {+ if (createNext) {+ formRef.current?.reset()+ questionRef.current?.focus()+ } else {+ onClose()+ }+ })}}>- <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(($) => $['addModal.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={question} onChange={setQuestion} />- <EditItem type={EditItemType.Answer} content={answer} onChange={setAnswer} />- </div>- </div>- <div className="shrink-0">- {isAnnotationFull && (- <div className="mt-6 mb-4 px-6">- <AnnotationFull />- </div>- )}- <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">- <label className="flex cursor-pointer items-center space-x-2">- <Checkbox checked={isCreateNext} onCheckedChange={setIsCreateNext} />- <span>{t(($) => $['addModal.createNext'], { ns: 'appAnnotation' })}</span>- </label>- <div className="mt-2 flex space-x-2">- <Button className="h-7 text-xs" onClick={onHide}>- {t(($) => $['operation.cancel'], { ns: 'common' })}- </Button>- <Button- className="h-7 text-xs"- variant="primary"- onClick={handleSave}- loading={isSaving}- disabled={isAnnotationQuotaUnavailable || isAnnotationFull}- >- {t(($) => $['operation.add'], { ns: 'common' })}- </Button>- </div>- </div>- </div>- </DrawerContent>- </DrawerPopup>- </DrawerViewport>- </DrawerPortal>- </Drawer>- </div>+ <DialogBody>+ <div className="space-y-6">+ <Field name="question">+ <FieldLabel className="flex items-center gap-2">+ <span aria-hidden className="i-custom-public-avatar-user size-6 shrink-0" />+ {t(($) => $['addModal.queryName'], { ns: 'appAnnotation' })}+ </FieldLabel>+ <Textarea+ ref={questionRef}+ defaultValue=""+ required+ readOnly={isPending}+ placeholder={t(($) => $['addModal.queryPlaceholder'], { ns: 'appAnnotation' })}+ />+ <FieldError match="valueMissing">+ {t(($) => $['errorMessage.queryRequired'], { ns: 'appAnnotation' })}+ </FieldError>+ </Field>+ <Field name="answer">+ <FieldLabel className="flex items-center gap-2">+ <img aria-hidden src={robotAvatar.src} alt="" width={24} height={24} />+ {t(($) => $['addModal.answerName'], { ns: 'appAnnotation' })}+ </FieldLabel>+ <Textarea+ defaultValue=""+ required+ readOnly={isPending}+ placeholder={t(($) => $['addModal.answerPlaceholder'], { ns: 'appAnnotation' })}+ />+ <FieldError match="valueMissing">+ {t(($) => $['errorMessage.answerRequired'], { ns: 'appAnnotation' })}+ </FieldError>+ </Field>+ {isError && (+ <p role="alert" className="system-sm-regular text-text-destructive">+ {t(($) => $['api.actionFailed'], { ns: 'common' })}+ </p>+ )}+ {quotaFull && <AnnotationFull />}+ {quotaUnavailable && quota.isError && (+ <div role="alert" className="space-y-2">+ <p className="system-sm-regular text-text-destructive">+ {t(($) => $['api.actionFailed'], { ns: 'common' })}+ </p>+ <Button loading={quota.isFetching} onClick={() => quota.refetch()}>+ {t(($) => $['operation.retry'], { ns: 'common' })}+ </Button>+ </div>+ )}+ </div>+ </DialogBody>+ </Form>+ <DialogFooter>+ <Field className="me-auto" disabled={isPending}>+ <FieldLabel className="flex items-center gap-2">+ <Checkbox checked={createNext} onCheckedChange={setCreateNext} />+ {t(($) => $['addModal.createNext'], { ns: 'appAnnotation' })}+ </FieldLabel>+ </Field>+ <DialogClose disabled={isPending} render={<Button />}>+ {t(($) => $['operation.cancel'], { ns: 'common' })}+ </DialogClose>+ <Button+ type="submit"+ form={formId}+ variant="primary"+ loading={isPending}+ disabled={quotaUnavailable || quotaFull}+ >+ {t(($) => $['operation.add'], { ns: 'common' })}+ </Button>+ </DialogFooter>+ </DialogPopup>+ )+}++export default function AddAnnotationDialog({ appId, onAdded }: Props) {+ const { t } = useTranslation(['appAnnotation'])+ const [open, setOpen] = useState(false)+ const creation = useMutation(+ consoleQuery.apps.byAppId.annotations.post.mutationOptions({+ context: { silent: true },+ onSuccess: onAdded,+ }),+ )++ return (+ <Dialog+ open={open}+ disablePointerDismissal+ onOpenChange={(nextOpen, details) => {+ if (!nextOpen && creation.isPending) {+ details.cancel()+ return+ }+ setOpen(nextOpen)+ }}+ onOpenChangeComplete={(nextOpen) => {+ if (!nextOpen) creation.reset()+ }}+ >+ <DialogTrigger render={<Button variant="primary" />}>+ <span aria-hidden className="i-ri-add-line size-4" />+ {t(($) => $['table.header.addAnnotation'], { ns: 'appAnnotation' })}+ </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>+ </DialogPortal>+ </Dialog>)}-export default React.memo(AddAnnotationModal)diff --git a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsxindex 32f05c63675..7a22cb46825 100644--- a/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx+++ b/web/app/components/app/annotation/header-opts/__tests__/index.spec.tsx@@ -1,8 +1,8 @@import type { Window } from 'happy-dom'import type { ComponentProps } from 'react'import type { Mock } from 'vite-plus/test'-import type { AnnotationItemBasic } from '../../type'import type { Locale } from '@/i18n'+import type { consoleClient } from '@/service/console'import { screen, waitFor } from '@testing-library/react'import userEvent from '@testing-library/user-event'import { useLocale } from '#i18n'@@ -25,16 +25,25 @@ vi.mock('react-papaparse', () => ({jsonToCSV: (data: unknown) => mockJsonToCSV(data),}))-const { mockedFetchAnnotations } = vi.hoisted(() => ({+const { mockedFetchAnnotations, addAnnotation } = vi.hoisted(() => ({+ addAnnotation: vi.fn<typeof consoleClient.apps.byAppId.annotations.post>(),mockedFetchAnnotations: vi.fn(),}))-vi.mock('@/service/console', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/service/console')>()),- consoleClient: {- apps: { byAppId: { annotations: { export: { get: mockedFetchAnnotations } } } },- },-}))+vi.mock('@/service/console', async (importOriginal) => {+ const actual = await importOriginal<typeof import('@/service/console')>()+ const { withConsoleResponses, withConsoleClientResponses } =+ await import('@/test/console/service-responses')+ return {+ ...actual,+ consoleQuery: withConsoleResponses(actual.consoleQuery, {+ 'apps.byAppId.annotations.post': (input) => addAnnotation(input),+ }),+ consoleClient: withConsoleClientResponses(actual.consoleClient, {+ 'apps.byAppId.annotations.export.get': (input) => mockedFetchAnnotations(input),+ }),+ }+})const { mockedRequest } = vi.hoisted(() => ({mockedRequest:@@ -65,7 +74,6 @@ const renderComponent = (const defaultProps: HeaderOptionsProps = {appId: 'test-app-id',- onAdd: vi.fn(),onAdded: vi.fn(),controlUpdateList: 0,...props,@@ -109,7 +117,7 @@ const clickOperationAction = async (await clickMenuItem(user, item)}-const mockAnnotations: AnnotationItemBasic[] = [+const mockAnnotations = [{question: 'Question 1',answer: 'Answer 1',@@ -219,11 +227,12 @@ describe('HeaderOptions', () => {expect(mockJsonToCSV).not.toHaveBeenCalled()})- it('should open the add annotation modal and forward the onAdd callback', async () => {+ it('creates an annotation through the dialog and refreshes the parent and export data', async () => {mockedFetchAnnotations.mockResolvedValue({ data: mockAnnotations })const user = userEvent.setup()- const onAdd = vi.fn().mockResolvedValue(undefined)- renderComponent({ onAdd })+ const onAdded = vi.fn()+ addAnnotation.mockResolvedValue({ id: 'annotation-id' })+ renderComponent({ onAdded })await waitFor(() => expect(mockedFetchAnnotations).toHaveBeenCalled())@@ -240,10 +249,12 @@ describe('HeaderOptions', () => {await user.click(screen.getByRole('button', { name: 'common.operation.add' }))await waitFor(() => {- expect(onAdd).toHaveBeenCalledWith({- question: 'Integration question',- answer: 'Integration answer',+ expect(addAnnotation).toHaveBeenCalledWith({+ params: { app_id: 'test-app-id' },+ body: { question: 'Integration question', answer: 'Integration answer' },})+ expect(onAdded).toHaveBeenCalledOnce()+ expect(mockedFetchAnnotations).toHaveBeenCalledTimes(2)})})@@ -371,9 +382,7 @@ describe('HeaderOptions', () => {await waitFor(() => expect(mockedFetchAnnotations).toHaveBeenCalledTimes(1))- view.rerender(- <HeaderOptions appId="test-app-id" onAdd={vi.fn()} onAdded={vi.fn()} controlUpdateList={1} />,- )+ view.rerender(<HeaderOptions appId="test-app-id" onAdded={vi.fn()} controlUpdateList={1} />)await waitFor(() => expect(mockedFetchAnnotations).toHaveBeenCalledTimes(2))})diff --git a/web/app/components/app/annotation/header-opts/index.tsx b/web/app/components/app/annotation/header-opts/index.tsxindex af8fa9951e6..571bd2432bd 100644--- a/web/app/components/app/annotation/header-opts/index.tsx+++ b/web/app/components/app/annotation/header-opts/index.tsx@@ -1,9 +1,7 @@'use client'import type { Annotation } from '@dify/contracts/api/console/apps/types.gen'import type { FC } from 'react'-import type { AnnotationItemBasic } from '../type'import { AlertDialog } from '@langgenius/dify-ui/alert-dialog'-import { Button } from '@langgenius/dify-ui/button'import {Menu,MenuContent,@@ -12,7 +10,7 @@ import {MenuSubmenuTrigger,MenuTrigger,} from '@langgenius/dify-ui/menu'-import { useMutation } from '@tanstack/react-query'+import { noop, useMutation } from '@tanstack/react-query'import * as React from 'react'import { useEffect, useState } from 'react'import { useTranslation } from 'react-i18next'@@ -21,7 +19,7 @@ import { useLocale } from '#i18n'import { LanguagesSupported } from '@/i18n/language'import { consoleClient, consoleQuery } from '@/service/console'import { downloadBlob } from '@/utils/download'-import AddAnnotationModal from '../add-annotation-modal'+import AddAnnotationDialog from '../add-annotation-modal'import BatchAddModal from '../batch-add-annotation-modal'import { ClearAllAnnotationsConfirmContent } from '../clear-all-annotations-confirm-modal'@@ -30,7 +28,6 @@ const CSV_HEADER_QA_CN = ['问题', '答案']type Props = Readonly<{appId: string- onAdd: (payload: AnnotationItemBasic) => voidonAdded: () => voidcontrolUpdateList: number}>@@ -127,7 +124,7 @@ const OperationsMenu: FC<OperationsMenuProps> = ({)}-const HeaderOptions: FC<Props> = ({ appId, onAdd, onAdded, controlUpdateList }) => {+const HeaderOptions: FC<Props> = ({ appId, onAdded, controlUpdateList }) => {const { t } = useTranslation(['appAnnotation', 'common'])const locale = useLocale()const [list, setList] = useState<Annotation[]>([])@@ -165,18 +162,20 @@ const HeaderOptions: FC<Props> = ({ appId, onAdd, onAdded, controlUpdateList })const handleExportJsonl = React.useCallback(() => {downloadAnnotationJsonl(list, locale)}, [list, locale])- const [showAddModal, setShowAddModal] = React.useState(false)return (<div className="flex space-x-2">- <Button variant="primary" onClick={() => setShowAddModal(true)}>- <span aria-hidden className="i-ri-add-line size-4" />- <div>{t(($) => $['table.header.addAnnotation'], { ns: 'appAnnotation' })}</div>- </Button>+ <AddAnnotationDialog+ appId={appId}+ onAdded={() => {+ onAdded()+ void fetchList().catch(noop)+ }}+ /><Menu modal={false}><MenuTriggeraria-label={t(($) => $['operation.more'], { ns: 'common' })}- className="mr-0 box-border inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg p-0 text-components-button-secondary-text shadow-xs backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover data-popup-open:border-components-button-secondary-border-hover data-popup-open:bg-components-button-secondary-bg-hover"+ className="me-0 box-border inline-flex h-8 w-8 shrink-0 items-center justify-center rounded-lg border-[0.5px] border-components-button-secondary-border bg-components-button-secondary-bg p-0 text-components-button-secondary-text shadow-xs backdrop-blur-[5px] hover:border-components-button-secondary-border-hover hover:bg-components-button-secondary-bg-hover data-popup-open:border-components-button-secondary-border-hover data-popup-open:bg-components-button-secondary-bg-hover"><span aria-hidden className="i-ri-more-fill size-4" /></MenuTrigger>@@ -189,14 +188,6 @@ const HeaderOptions: FC<Props> = ({ appId, onAdd, onAdded, controlUpdateList })/></MenuContent></Menu>- {showAddModal && (- <AddAnnotationModal- isShow={showAddModal}- onHide={() => setShowAddModal(false)}- onAdd={onAdd}- />- )}-{showBulkImportModal && (<BatchAddModalappId={appId}diff --git a/web/app/components/app/annotation/index.tsx b/web/app/components/app/annotation/index.tsxindex 521ea18bf2d..0954762042b 100644--- a/web/app/components/app/annotation/index.tsx+++ b/web/app/components/app/annotation/index.tsx@@ -3,14 +3,13 @@import type { Annotation, AppDetailWithSite } from '@dify/contracts/api/console/apps/types.gen'import type { FC } from 'react'import type { QueryParam } from './filter'-import type { AnnotationItemBasic } from './type'import type { AnnotationReplyConfig } from '@/models/debug'import { cn } from '@langgenius/dify-ui/cn'import { IconButton } from '@langgenius/dify-ui/icon-button'import { Pagination } from '@langgenius/dify-ui/pagination'import { Switch } from '@langgenius/dify-ui/switch'import { RiEqualizer2Line } from '@remixicon/react'-import { useQuery } from '@tanstack/react-query'+import { noop, useQuery } from '@tanstack/react-query'import { useDebounce } from 'ahooks'import { useAtomValue } from 'jotai'import * as React from 'react'@@ -115,15 +114,6 @@ const Annotation: FC<Props> = (props) => {fetchList(currPage + 1)}, [currPage, limit, debouncedQueryParams])- const handleAdd = async (payload: AnnotationItemBasic) => {- await consoleClient.apps.byAppId.annotations.post({- params: { app_id: appDetail.id },- body: payload,- })- fetchList()- setControlUpdateList(Date.now())- }-const handleRemove = async (id: string) => {await consoleClient.apps.byAppId.annotations.byAnnotationId.delete({params: { app_id: appDetail.id, annotation_id: id },@@ -181,8 +171,8 @@ const Annotation: FC<Props> = (props) => {<><divclassName={cn(- !annotationConfig?.enabled && 'pr-2',- 'flex h-7 items-center space-x-1 rounded-lg border border-components-panel-border bg-components-panel-bg-blur pl-2',+ !annotationConfig?.enabled && 'pe-2',+ 'flex h-7 items-center space-x-1 rounded-lg border border-components-panel-border bg-components-panel-bg-blur ps-2',)}><span@@ -219,8 +209,8 @@ const Annotation: FC<Props> = (props) => {}}></Switch>{annotationConfig?.enabled && (- <div className="flex items-center pr-1 pl-1.5">- <div className="mr-1 h-3.5 w-px shrink-0 bg-divider-subtle"></div>+ <div className="flex items-center ps-1.5 pe-1">+ <div className="me-1 h-3.5 w-px shrink-0 bg-divider-subtle"></div><IconButtonaria-label={t(($) => $['initSetup.configTitle'], {ns: 'appAnnotation',@@ -242,9 +232,8 @@ const Annotation: FC<Props> = (props) => {<HeaderOptsappId={appDetail.id}controlUpdateList={controlUpdateList}- onAdd={handleAdd}onAdded={() => {- fetchList()+ void fetchList().catch(noop)}}/></div>diff --git a/web/app/components/app/annotation/type.ts b/web/app/components/app/annotation/type.tsindex fb6cf3b201b..455d2ea6124 100644--- a/web/app/components/app/annotation/type.ts+++ b/web/app/components/app/annotation/type.ts@@ -1,9 +1,3 @@-export type AnnotationItemBasic = {- message_id?: string- question: string- answer: string-}-export type EmbeddingModelConfig = {embedding_provider_name: stringembedding_model_name: stringdiff --git a/web/service/console/query-policies.ts b/web/service/console/query-policies.tsindex 3f4abaabe2b..4890b96f9a6 100644--- a/web/service/console/query-policies.ts+++ b/web/service/console/query-policies.ts@@ -977,6 +977,23 @@ export function createConsoleQuery(consoleClient: ConsoleClient) {},},byAppId: {+ annotations: {+ post: {+ 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() }),+ ])+ },+ },+ },+ },traceRuns: {bySourceKind: {bySourceId: {