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(dataset): disable chunk actions without edit permission (#42561)
Wu Tianwei78d338fe11f5
diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-detail.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-detail.spec.tsxindex 25b0f3f6771..44e5e5c5966 100644--- a/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-detail.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-detail.spec.tsx@@ -3,6 +3,11 @@ import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { ChunkingMode } from '@/models/datasets'import ChildSegmentDetail from '../child-segment-detail'+vi.mock('../../context', () => ({+ useDocumentContext: (selector: (state: { canEdit: boolean }) => unknown) =>+ selector({ canEdit: true }),+}))+// Mock segment list contextlet mockFullScreen = falseconst mockToggleFullScreen = vi.fn()diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-list.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-list.spec.tsxindex 44e4daac546..8c52aaaf0d4 100644--- a/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-list.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/__tests__/child-segment-list.spec.tsx@@ -6,8 +6,8 @@ import ChildSegmentList from '../child-segment-list'// Mock document contextlet mockParentMode = 'paragraph'vi.mock('../../context', () => ({- useDocumentContext: (selector: (state: { parentMode: string }) => unknown) => {- return selector({ parentMode: mockParentMode })+ useDocumentContext: (selector: (state: { parentMode: string; canEdit: boolean }) => unknown) => {+ return selector({ parentMode: mockParentMode, canEdit: true })},}))diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/permission-transitions.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/permission-transitions.spec.tsxnew file mode 100644index 00000000000..8991e15b3ab--- /dev/null+++ b/web/app/components/datasets/documents/detail/completed/__tests__/permission-transitions.spec.tsx@@ -0,0 +1,71 @@+import { screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, expect, it, vi } from 'vite-plus/test'+import { ChunkingMode } from '@/models/datasets'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { DocumentContext } from '../../context'+import { SegmentDetail } from '../segment-detail'++vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: (+ selector: (state: { dataset: { indexing_technique: string; runtime_mode: string } }) => unknown,+ ) => selector({ dataset: { indexing_technique: 'high_quality', runtime_mode: 'general' } }),+}))++vi.mock('../index', () => ({+ useSegmentListContext: (selector: (state: { fullScreen: boolean }) => unknown) =>+ selector({ fullScreen: false }),+}))++vi.mock('@/app/components/base/markdown', () => ({+ Markdown: ({ content }: { content: string }) => <div>{content}</div>,+}))++vi.mock('@/app/components/datasets/common/image-uploader/image-uploader-in-chunk', () => ({+ default: () => null,+}))++const onUpdate = vi.fn()+const content = ''+const signContent = ''++function detail(canEdit: boolean, docForm = ChunkingMode.text) {+ return (+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector contexts are not React 19 context components.+ <DocumentContext.Provider value={{ canEdit, docForm, parentMode: 'paragraph' }}>+ <SegmentDetail+ segInfo={{ id: 'segment-1', content, sign_content: signContent, word_count: 40 }}+ onUpdate={onUpdate}+ onCancel={vi.fn()}+ isEditMode+ docForm={docForm}+ />+ </DocumentContext.Provider>+ )+}++beforeEach(() => {+ vi.clearAllMocks()+})++it('preserves raw content for saving after permission changes from read-only to editable', async () => {+ const user = userEvent.setup()+ const { rerender } = render(detail(false))+ expect(screen.getByText(signContent)).toBeInTheDocument()+ rerender(detail(true))+ await user.click(await screen.findByRole('button', { name: /common.operation.save/ }))+ expect(onUpdate).toHaveBeenCalledWith('segment-1', content, '', [], [], '', false)+})++it('closes the regeneration confirmation when edit permission is revoked', async () => {+ const user = userEvent.setup()+ const { rerender } = render(detail(true, ChunkingMode.parentChild))+ await user.click(screen.getByRole('button', { name: 'common.operation.saveAndRegenerate' }))+ expect(await screen.findByRole('alertdialog')).toBeInTheDocument()++ rerender(detail(false, ChunkingMode.parentChild))++ await waitFor(() => expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument())+ expect(screen.queryByRole('button', { name: /common.operation.save/ })).not.toBeInTheDocument()+ expect(onUpdate).not.toHaveBeenCalled()+})diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsxnew file mode 100644index 00000000000..09f697a1768--- /dev/null+++ b/web/app/components/datasets/documents/detail/completed/__tests__/permissions.spec.tsx@@ -0,0 +1,240 @@+import type { ChildChunkDetail, ParentMode, SegmentDetailModel } from '@/models/datasets'+import { screen, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'+import { ChunkingMode } from '@/models/datasets'+import { renderWithConsoleQuery as render } from '@/test/console/query-data'+import { DocumentContext } from '../../context'+import Completed from '../index'++const childChunk: ChildChunkDetail = {+ id: 'child-1',+ segment_id: 'segment-1',+ position: 1,+ content: 'Child chunk content',+ word_count: 19,+ created_at: 1700000000,+ updated_at: 1700000000,+ type: 'automatic',+}++const segment: SegmentDetailModel = {+ id: 'segment-1',+ document_id: 'document-1',+ position: 1,+ content: 'Chunk content',+ sign_content: '',+ word_count: 13,+ tokens: 3,+ keywords: [],+ index_node_id: 'index-1',+ index_node_hash: 'hash-1',+ hit_count: 0,+ enabled: true,+ disabled_at: 0,+ disabled_by: '',+ status: 'completed',+ created_by: 'user-1',+ created_at: 1700000000,+ indexing_at: 1700000000,+ completed_at: 1700000000,+ error: null,+ stopped_at: 0,+ updated_at: 1700000000,+ attachments: [],+ child_chunks: [childChunk],+}++let parentMode: ParentMode = 'paragraph'+const onChangeSwitch = vi.fn()+const onDelete = vi.fn()+const onUpdate = vi.fn()+const onDeleteChildChunk = vi.fn()+const onUpdateChildChunk = vi.fn()++// Keep selection, cards, action bars and drawers real; isolate their data and mutation hooks.+vi.mock('../hooks/use-segment-list-data', () => ({+ useSegmentListData: () => ({+ segments: [segment],+ segmentListData: { total: 1 },+ totalText: '1 chunk',+ isLoadingSegmentList: false,+ isFullDocMode: parentMode === 'full-doc',+ onChangeSwitch,+ onDelete,+ handleUpdateSegment: onUpdate,+ }),+}))++vi.mock('../hooks/use-child-segment-data', () => ({+ useChildSegmentData: () => ({+ childSegments: [childChunk],+ childChunkListData: { total: 1 },+ isLoadingChildSegmentList: false,+ onDeleteChildChunk,+ handleUpdateChildChunk: onUpdateChildChunk,+ }),+}))++vi.mock('@/context/dataset-detail', () => ({+ useDatasetDetailContextWithSelector: (+ selector: (state: { dataset: { indexing_technique: string; runtime_mode: string } }) => unknown,+ ) => selector({ dataset: { indexing_technique: 'high_quality', runtime_mode: 'general' } }),+}))++vi.mock('@/app/components/base/markdown', () => ({+ Markdown: ({ content }: { content: string }) => <div>{content}</div>,+}))++vi.mock('@/app/components/datasets/common/image-uploader/image-uploader-in-chunk', () => ({+ default: () => null,+}))++function renderChunks(canEdit: boolean, docForm = ChunkingMode.text) {+ return render(+ // oxlint-disable-next-line eslint-react/no-context-provider -- use-context-selector contexts are not React 19 context components.+ <DocumentContext.Provider+ value={{ datasetId: 'dataset-1', documentId: 'document-1', docForm, parentMode, canEdit }}+ >+ <Completed+ embeddingAvailable+ showNewSegmentModal={false}+ onNewSegmentModalChange={vi.fn()}+ importStatus={undefined}+ />+ </DocumentContext.Provider>,+ )+}++describe('Chunk permissions', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ parentMode = 'paragraph'+ })++ it('should pass read-only permission to the batch actions and allow cancelling selection', async () => {+ const user = userEvent.setup()+ renderChunks(false)++ const checkbox = screen.getByRole('checkbox', { name: 'datasetDocuments.segment.chunk 1' })+ await user.click(checkbox)++ for (const action of ['enable', 'disable', 'delete']) {+ const button = screen.getByRole('button', { name: `dataset.batchAction.${action}` })+ expect(button).toBeDisabled()+ await user.click(button)+ }+ expect(onChangeSwitch).not.toHaveBeenCalled()+ expect(onDelete).not.toHaveBeenCalled()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'dataset.batchAction.cancel' }))+ expect(checkbox).not.toBeChecked()+ expect(+ screen.queryByRole('button', { name: 'dataset.batchAction.enable' }),+ ).not.toBeInTheDocument()+ })++ it('should allow batch mutations with edit permission', async () => {+ const user = userEvent.setup()+ renderChunks(true)+ await user.click(screen.getByRole('checkbox', { name: 'datasetDocuments.segment.chunk 1' }))++ await user.click(screen.getByRole('button', { name: 'dataset.batchAction.enable' }))+ expect(onChangeSwitch).toHaveBeenCalledWith(true, '')+ await user.click(screen.getByRole('button', { name: 'dataset.batchAction.disable' }))+ expect(onChangeSwitch).toHaveBeenCalledWith(false, '')++ await user.click(screen.getByRole('button', { name: 'dataset.batchAction.delete' }))+ const dialog = await screen.findByRole('alertdialog')+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.sure' }))+ expect(onDelete).toHaveBeenCalledWith('')+ })++ it.each([ChunkingMode.text, ChunkingMode.qa, ChunkingMode.parentChild])(+ 'should open %s chunk content in read-only mode without edit permission',+ async (docForm) => {+ const user = userEvent.setup()+ renderChunks(false, docForm)+ await user.click(screen.getByText('Chunk content'))++ const dialog = await screen.findByRole('dialog')+ expect(within(dialog).getByText('datasetDocuments.segment.chunkDetail')).toBeInTheDocument()+ if (docForm === ChunkingMode.qa)+ expect(within(dialog).getByDisplayValue('Chunk content')).toBeDisabled()+ else expect(within(dialog).getByText('Chunk content')).toBeInTheDocument()++ for (const input of within(dialog).queryAllByRole('textbox')) expect(input).toBeDisabled()+ expect(+ within(dialog).queryByRole('button', { name: /common.operation.save/ }),+ ).not.toBeInTheDocument()++ await user.click(within(dialog).getByRole('button', { name: 'common.operation.zoomIn' }))+ expect(+ within(dialog).queryByRole('button', { name: /common.operation.save/ }),+ ).not.toBeInTheDocument()+ await user.keyboard('{Control>}s{/Control}{Meta>}s{/Meta}')+ expect(onUpdate).not.toHaveBeenCalled()+ await user.click(within(dialog).getByRole('button', { name: 'common.operation.close' }))+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()+ },+ )++ it('should allow editing chunk content with edit permission', async () => {+ const user = userEvent.setup()+ renderChunks(true)+ await user.click(screen.getByRole('button', { name: 'common.operation.edit' }))++ const dialog = await screen.findByRole('dialog')+ const input = within(dialog).getByDisplayValue('Chunk content')+ expect(input).toBeEnabled()+ await user.type(input, ' updated')+ await user.click(within(dialog).getByRole('button', { name: /common.operation.save/ }))+ expect(onUpdate).toHaveBeenCalledWith(+ 'segment-1',+ 'Chunk content updated',+ '',+ [],+ [],+ '',+ false,+ )+ })++ it.each(['paragraph', 'full-doc'] as const)(+ 'should disable child mutations and keep %s child content readable',+ async (mode) => {+ const user = userEvent.setup()+ parentMode = mode+ renderChunks(false, ChunkingMode.parentChild)++ const addButton = screen.getByRole('button', { name: 'common.operation.add' })+ expect(addButton).toBeDisabled()+ await user.click(addButton)+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument()++ if (mode === 'paragraph')+ await user.click(screen.getByText(/datasetDocuments.segment.childChunks/))++ const content = screen.getByText('Child chunk content')+ await user.hover(content)+ const deleteButton = await screen.findByRole('button', { name: 'common.operation.remove' })+ expect(deleteButton).toBeDisabled()+ await user.click(deleteButton)+ expect(onDeleteChildChunk).not.toHaveBeenCalled()++ await user.click(content)+ const dialog = (await screen.findAllByRole('dialog')).find((element) =>+ within(element).queryByText('datasetDocuments.segment.chunkDetail'),+ )!+ expect(dialog).toBeInTheDocument()+ expect(within(dialog).getByText('Child chunk content')).toBeInTheDocument()+ expect(within(dialog).queryByRole('textbox')).not.toBeInTheDocument()+ expect(+ within(dialog).queryByRole('button', { name: /common.operation.save/ }),+ ).not.toBeInTheDocument()+ await user.keyboard('{Control>}s{/Control}{Meta>}s{/Meta}')+ expect(onUpdateChildChunk).not.toHaveBeenCalled()+ },+ )+})diff --git a/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx b/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsxindex 3bf0d36e5b4..1c1b96f8bc0 100644--- a/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/__tests__/segment-detail.spec.tsx@@ -23,8 +23,8 @@ vi.mock('@/context/dataset-detail', () => ({// Mock document contextlet mockParentMode = 'paragraph'vi.mock('../../context', () => ({- useDocumentContext: (selector: (state: { parentMode: string }) => unknown) => {- return selector({ parentMode: mockParentMode })+ useDocumentContext: (selector: (state: { parentMode: string; canEdit: boolean }) => unknown) => {+ return selector({ parentMode: mockParentMode, canEdit: true })},}))diff --git a/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx b/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsxindex cff2be97ed3..742a1c312d5 100644--- a/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx+++ b/web/app/components/datasets/documents/detail/completed/child-segment-detail.tsx@@ -9,6 +9,7 @@ import Divider from '@/app/components/base/divider'import { useEventEmitterContextContext } from '@/context/event-emitter'import { formatNumber } from '@/utils/format'import { formatTime } from '@/utils/time'+import { useDocumentContext } from '../context'import { ActionButtons } from './common/action-buttons'import ChunkContent from './common/chunk-content'import Dot from './common/dot'@@ -34,6 +35,7 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({docForm,}) => {const { t } = useTranslation()+ const canEdit = useDocumentContext((s) => s.canEdit)const [content, setContent] = useState(childChunkInfo?.content || '')const { eventEmitter } = useEventEmitterContextContext()const [loading, setLoading] = useState(false)@@ -76,7 +78,9 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({><div className="flex flex-col"><div className="system-xl-semibold text-text-primary">- {t(($) => $['segment.editChildChunk'], { ns: 'datasetDocuments' })}+ {t(($) => $[canEdit ? 'segment.editChildChunk' : 'segment.chunkDetail'], {+ ns: 'datasetDocuments',+ })}</div><div className="flex items-center gap-x-2"><SegmentIndexTag@@ -90,7 +94,7 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({</div></div><div className="flex items-center">- {fullScreen && (+ {canEdit && fullScreen && (<><ActionButtonshandleCancel={handleCancel}@@ -127,13 +131,14 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({</div><divclassName={cn(- 'flex w-full grow',+ 'flex h-0 w-full grow',fullScreen ? 'flex-row justify-center px-6 pt-6' : 'px-4 py-3',)}><divclassName={cn(- 'h-full overflow-hidden break-all whitespace-pre-line',+ 'h-full break-all whitespace-pre-line',+ canEdit ? 'overflow-hidden' : 'overflow-y-auto',fullScreen ? 'w-1/2' : 'w-full',)}>@@ -141,11 +146,11 @@ const ChildSegmentDetail: FC<IChildSegmentDetailProps> = ({docForm={docForm}question={content}onQuestionChange={(content) => setContent(content)}- isEditMode={true}+ isEditMode={canEdit}/></div></div>- {!fullScreen && (+ {canEdit && !fullScreen && (<div className="flex items-center justify-end border-t border-t-divider-subtle p-4 pt-3"><ActionButtonshandleCancel={handleCancel}diff --git a/web/app/components/datasets/documents/detail/completed/child-segment-list.tsx b/web/app/components/datasets/documents/detail/completed/child-segment-list.tsxindex aa2a26f231d..cdda3982db0 100644--- a/web/app/components/datasets/documents/detail/completed/child-segment-list.tsx+++ b/web/app/components/datasets/documents/detail/completed/child-segment-list.tsx@@ -80,6 +80,7 @@ const ChildSegmentList: FC<IChildSegmentCardProps> = ({}) => {const { t } = useTranslation()const parentMode = useDocumentContext((s) => s.parentMode)+ const canEdit = useDocumentContext((s) => s.canEdit)const currChildChunk = useSegmentListContext((s) => s.currChildChunk)const [collapsed, setCollapsed] = useState(true)@@ -119,6 +120,7 @@ const ChildSegmentList: FC<IChildSegmentCardProps> = ({label={label}text={childChunk.content}onDelete={() => onDelete?.(childChunk.segment_id, childChunk.id)}+ deleteDisabled={!canEdit}className="child-chunk"labelClassName={isFocused ? 'bg-state-accent-solid text-text-primary-on-surface' : ''}labelInnerClassName="text-[10px] font-semibold align-bottom leading-6"@@ -200,12 +202,14 @@ const ChildSegmentList: FC<IChildSegmentCardProps> = ({'px-1.5 py-1 system-xs-semibold-uppercase text-components-button-secondary-accent-text',hoverVisibleClass,isFullDocMode && isLoading && 'text-components-button-secondary-accent-text-disabled',+ !canEdit &&+ 'cursor-not-allowed text-components-button-secondary-accent-text-disabled',)}onClick={(event) => {event.stopPropagation()handleAddNewChildChunk?.(parentChunkId)}}- disabled={isLoading}+ disabled={!canEdit || isLoading}>{t(($) => $['operation.add'], { ns: 'common' })}</button>diff --git a/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsx b/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsxindex 9d0fcdc6537..559c6559445 100644--- a/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/common/__tests__/batch-action.spec.tsx@@ -1,4 +1,5 @@import { fireEvent, screen, waitFor, within } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import { beforeEach, describe, expect, it, vi } from 'vite-plus/test'import { renderWithConsoleQuery as render } from '@/test/console/query-data'import BatchAction from '../batch-action'@@ -49,6 +50,25 @@ describe('BatchAction', () => {})describe('User Interactions', () => {+ it('should disable mutations while keeping cancellation available', async () => {+ const user = userEvent.setup()+ render(<BatchAction {...defaultProps} disabled />)++ for (const action of ['enable', 'disable', 'delete']) {+ const button = screen.getByRole('button', { name: `dataset.batchAction.${action}` })+ expect(button).toBeDisabled()+ await user.click(button)+ }++ expect(defaultProps.onBatchEnable).not.toHaveBeenCalled()+ expect(defaultProps.onBatchDisable).not.toHaveBeenCalled()+ expect(defaultProps.onBatchDelete).not.toHaveBeenCalled()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()++ await user.click(screen.getByRole('button', { name: 'dataset.batchAction.cancel' }))+ expect(defaultProps.onCancel).toHaveBeenCalledOnce()+ })+it('should call onBatchEnable when enable button is clicked', () => {const mockOnBatchEnable = vi.fn()render(<BatchAction {...defaultProps} onBatchEnable={mockOnBatchEnable} />)diff --git a/web/app/components/datasets/documents/detail/completed/common/batch-action.tsx b/web/app/components/datasets/documents/detail/completed/common/batch-action.tsxindex 3c8b921373a..07604caad60 100644--- a/web/app/components/datasets/documents/detail/completed/common/batch-action.tsx+++ b/web/app/components/datasets/documents/detail/completed/common/batch-action.tsx@@ -31,6 +31,7 @@ const i18nPrefix = 'batchAction'type IBatchActionProps = {className?: stringselectedIds: string[]+ disabled?: booleanonBatchEnable?: () => voidonBatchDisable?: () => voidonBatchDownload?: () => void@@ -45,6 +46,7 @@ type IBatchActionProps = {const BatchAction: FC<IBatchActionProps> = ({className,selectedIds,+ disabled = false,onBatchEnable,onBatchDisable,onBatchSummary,@@ -85,49 +87,54 @@ const BatchAction: FC<IBatchActionProps> = ({</div><Divider type="vertical" className="mx-0.5 h-3.5 bg-divider-regular" />{onBatchEnable && (- <Button variant="ghost" onClick={onBatchEnable}>+ <Button variant="ghost" disabled={disabled} onClick={onBatchEnable}><RiCheckboxCircleLine className="size-4" /><span>{t(($) => $[`${i18nPrefix}.enable`], { ns: 'dataset' })}</span></Button>)}{onBatchDisable && (- <Button variant="ghost" onClick={onBatchDisable}>+ <Button variant="ghost" disabled={disabled} onClick={onBatchDisable}><RiCloseCircleLine className="size-4" /><span>{t(($) => $[`${i18nPrefix}.disable`], { ns: 'dataset' })}</span></Button>)}{onEditMetadata && (- <Button variant="ghost" onClick={onEditMetadata}>+ <Button variant="ghost" disabled={disabled} onClick={onEditMetadata}><RiDraftLine className="size-4" /><span>{t(($) => $['metadata.metadata'], { ns: 'dataset' })}</span></Button>)}{onBatchSummary && isNonCloudEdition && (- <Button variant="ghost" onClick={onBatchSummary}>+ <Button variant="ghost" disabled={disabled} onClick={onBatchSummary}><SearchLinesSparkle className="size-4" /><span>{t(($) => $['list.action.summary'], { ns: 'datasetDocuments' })}</span></Button>)}{onArchive && (- <Button variant="ghost" onClick={onArchive}>+ <Button variant="ghost" disabled={disabled} onClick={onArchive}><RiArchive2Line className="size-4" /><span>{t(($) => $[`${i18nPrefix}.archive`], { ns: 'dataset' })}</span></Button>)}{onBatchReIndex && (- <Button variant="ghost" onClick={onBatchReIndex}>+ <Button variant="ghost" disabled={disabled} onClick={onBatchReIndex}><RiRefreshLine className="size-4" /><span>{t(($) => $[`${i18nPrefix}.reIndex`], { ns: 'dataset' })}</span></Button>)}{onBatchDownload && (- <Button variant="ghost" onClick={onBatchDownload}>+ <Button variant="ghost" disabled={disabled} onClick={onBatchDownload}><RiDownload2Line className="size-4" /><span>{t(($) => $[`${i18nPrefix}.download`], { ns: 'dataset' })}</span></Button>)}{onBatchDelete && (- <Button variant="ghost" tone="destructive" onClick={showDeleteConfirm}>+ <Button+ variant="ghost"+ tone="destructive"+ disabled={disabled}+ onClick={showDeleteConfirm}+ ><RiDeleteBinLine className="size-4" /><span>{t(($) => $[`${i18nPrefix}.delete`], { ns: 'dataset' })}</span></Button>@@ -156,7 +163,11 @@ const BatchAction: FC<IBatchActionProps> = ({<AlertDialogCancelButton>{t(($) => $['operation.cancel'], { ns: 'common' })}</AlertDialogCancelButton>- <AlertDialogConfirmButton loading={isDeleting} onClick={handleBatchDelete}>+ <AlertDialogConfirmButton+ disabled={disabled}+ loading={isDeleting}+ onClick={handleBatchDelete}+ >{t(($) => $['operation.sure'], { ns: 'common' })}</AlertDialogConfirmButton></AlertDialogActions>diff --git a/web/app/components/datasets/documents/detail/completed/index.tsx b/web/app/components/datasets/documents/detail/completed/index.tsxindex 304fc03aab5..275f3a9ef3e 100644--- a/web/app/components/datasets/documents/detail/completed/index.tsx+++ b/web/app/components/datasets/documents/detail/completed/index.tsx@@ -51,6 +51,7 @@ const Completed: FC<ICompletedProps> = ({}) => {const { t } = useTranslation()const docForm = useDocumentContext((s) => s.docForm)+ const canEdit = useDocumentContext((s) => s.canEdit)// Pagination stateconst [currentPage, setCurrentPage] = useState(1)@@ -289,6 +290,7 @@ const Completed: FC<ICompletedProps> = ({<BatchActionclassName="absolute bottom-16 left-0 z-20"selectedIds={selectionState.selectedSegmentIds}+ disabled={!canEdit}onBatchEnable={() => segmentListDataHook.onChangeSwitch(true, '')}onBatchDisable={() => segmentListDataHook.onChangeSwitch(false, '')}onBatchDelete={() => segmentListDataHook.onDelete('')}diff --git a/web/app/components/datasets/documents/detail/completed/segment-card/__tests__/index.spec.tsx b/web/app/components/datasets/documents/detail/completed/segment-card/__tests__/index.spec.tsxindex b43e812d1d8..229ddbe4850 100644--- a/web/app/components/datasets/documents/detail/completed/segment-card/__tests__/index.spec.tsx+++ b/web/app/components/datasets/documents/detail/completed/segment-card/__tests__/index.spec.tsx@@ -7,6 +7,7 @@ import type {SegmentDetailModel,} from '@/models/datasets'import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'import * as React from 'react'import { ChunkingMode } from '@/models/datasets'import SegmentCard from '../index'@@ -15,6 +16,7 @@ import SegmentCard from '../index'const mockDocForm = { current: ChunkingMode.text }const mockParentMode = { current: 'paragraph' as ParentMode }+const mockCanEdit = { current: true }vi.mock('../../../context', () => ({useDocumentContext: (selector: (value: DocumentContextValue) => unknown) => {@@ -23,6 +25,7 @@ vi.mock('../../../context', () => ({documentId: 'test-document-id',docForm: mockDocForm.current,parentMode: mockParentMode.current,+ canEdit: mockCanEdit.current,}return selector(value)},@@ -157,8 +160,48 @@ describe('SegmentCard', () => {mockDocForm.current = ChunkingMode.textmockParentMode.current = 'paragraph'mockIsCollapsed.current = true+ mockCanEdit.current = true})+ it.each([true, false])(+ 'should disable single chunk mutations without edit permission (enabled: %s)',+ async (enabled) => {+ mockCanEdit.current = false+ const user = userEvent.setup()+ const onClickEdit = vi.fn()+ const onChangeSwitch = vi.fn()+ const onDelete = vi.fn()++ render(+ <SegmentCard+ loading={false}+ detail={createMockSegmentDetail({ enabled })}+ embeddingAvailable+ focused={defaultFocused}+ onClickEdit={onClickEdit}+ onChangeSwitch={onChangeSwitch}+ onDelete={onDelete}+ />,+ )++ const editButton = screen.getByRole('button', { name: 'common.operation.edit' })+ const deleteButton = screen.getByRole('button', { name: 'common.operation.delete' })+ const statusSwitch = screen.getByRole('switch')+ expect(editButton).toBeDisabled()+ expect(deleteButton).toBeDisabled()+ expect(statusSwitch).toHaveAttribute('aria-disabled', 'true')++ await user.click(editButton)+ await user.click(deleteButton)+ await user.click(statusSwitch)++ expect(onClickEdit).not.toHaveBeenCalled()+ expect(onChangeSwitch).not.toHaveBeenCalled()+ expect(onDelete).not.toHaveBeenCalled()+ expect(screen.queryByRole('alertdialog')).not.toBeInTheDocument()+ },+ )+describe('Rendering', () => {it('should render loading skeleton when loading is true', () => {render(<SegmentCard loading={true} focused={defaultFocused} />)diff --git a/web/app/components/datasets/documents/detail/completed/segment-card/index.tsx b/web/app/components/datasets/documents/detail/completed/segment-card/index.tsxindex 80526d4995b..ec65723a442 100644--- a/web/app/components/datasets/documents/detail/completed/segment-card/index.tsx+++ b/web/app/components/datasets/documents/detail/completed/segment-card/index.tsx@@ -9,6 +9,7 @@ import {AlertDialogTitle,} from '@langgenius/dify-ui/alert-dialog'import { cn } from '@langgenius/dify-ui/cn'+import { IconButton } from '@langgenius/dify-ui/icon-button'import { Switch } from '@langgenius/dify-ui/switch'import { Tooltip, TooltipContent, TooltipTrigger } from '@langgenius/dify-ui/tooltip'import { RiDeleteBinLine, RiEditLine } from '@remixicon/react'@@ -85,6 +86,7 @@ const SegmentCard: FC<ISegmentCardProps> = ({const [showModal, setShowModal] = useState(false)const docForm = useDocumentContext((s) => s.docForm)const parentMode = useDocumentContext((s) => s.parentMode)+ const canEdit = useDocumentContext((s) => s.canEdit)const isGeneralMode = useMemo(() => {return docForm === ChunkingMode.text@@ -193,47 +195,40 @@ const SegmentCard: FC<ISegmentCardProps> = ({<Tooltip><TooltipTriggerrender={- <button- type="button"+ <IconButtonaria-label={t(($) => $['operation.edit'], { ns: 'common' })}- className="flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-lg border-none bg-transparent p-0 hover:bg-state-base-hover"+ disabled={!canEdit}onClick={(e) => {e.stopPropagation()onClickEdit?.()}}>- <RiEditLine- className="size-4 text-text-tertiary"- aria-hidden="true"- />- </button>+ <RiEditLine className="size-4" aria-hidden="true" />+ </IconButton>}/><TooltipContent className="system-xs-medium text-text-secondary">- Edit+ {t(($) => $['operation.edit'], { ns: 'common' })}</TooltipContent></Tooltip><Tooltip><TooltipTriggerrender={- <button- type="button"+ <IconButtonaria-label={t(($) => $['operation.delete'], { ns: 'common' })}- className="group/delete flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-lg border-none bg-transparent p-0 hover:bg-state-destructive-hover"+ tone="destructive"+ disabled={!canEdit}onClick={(e) => {e.stopPropagation()setShowModal(true)}}>- <RiDeleteBinLine- className="size-4 text-text-tertiary group-hover/delete:text-text-destructive"- aria-hidden="true"- />- </button>+ <RiDeleteBinLine className="size-4" aria-hidden="true" />+ </IconButton>}/><TooltipContent className="system-xs-medium text-text-secondary">- Delete+ {t(($) => $['operation.delete'], { ns: 'common' })}</TooltipContent></Tooltip><Divider type="vertical" className="h-3.5 bg-divider-regular" />@@ -247,7 +242,8 @@ const SegmentCard: FC<ISegmentCardProps> = ({><Switchsize="md"- disabled={archived || detail?.status !== 'completed'}+ aria-label={t(($) => $['batchAction.enable'], { ns: 'dataset' })}+ disabled={!canEdit || archived || detail?.status !== 'completed'}checked={enabled}onCheckedChange={async (val) => {await onChangeSwitch?.(val, id)@@ -310,6 +306,7 @@ const SegmentCard: FC<ISegmentCardProps> = ({{t(($) => $['operation.cancel'], { ns: 'common' })}</AlertDialogCancelButton><AlertDialogConfirmButton+ disabled={!canEdit}onClick={async () => {await onDelete?.(id)}}diff --git a/web/app/components/datasets/documents/detail/completed/segment-detail.tsx b/web/app/components/datasets/documents/detail/completed/segment-detail.tsxindex 7a49fe808a6..8c7e7b2c16e 100644--- a/web/app/components/datasets/documents/detail/completed/segment-detail.tsx+++ b/web/app/components/datasets/documents/detail/completed/segment-detail.tsx@@ -42,13 +42,13 @@ export function SegmentDetail({segInfo,onUpdate,onCancel,- isEditMode,+ isEditMode: requestedEditMode,docForm,}: ISegmentDetailProps) {const { t } = useTranslation()- const [question, setQuestion] = useState(- isEditMode ? segInfo?.content || '' : segInfo?.sign_content || '',- )+ const canEdit = useDocumentContext((s) => s.canEdit)+ const isEditMode = requestedEditMode && canEdit+ const [question, setQuestion] = useState(segInfo?.content || '')const [answer, setAnswer] = useState(segInfo?.answer || '')const [summary, setSummary] = useState(segInfo?.summary || '')const [attachments, setAttachments] = useState<FileEntity[]>(() => {@@ -192,7 +192,6 @@ export function SegmentDetail({fullScreen? 'w-full flex-row justify-center gap-x-8 px-6 pt-6': 'flex-col gap-y-1 px-4 py-3',- !isEditMode && 'pb-0',)}><div@@ -203,7 +202,7 @@ export function SegmentDetail({><ChunkContentdocForm={docForm}- question={question}+ question={isEditMode ? question : segInfo?.sign_content || segInfo?.content || ''}answer={answer}onQuestionChange={(question) => setQuestion(question)}onAnswerChange={(answer) => setAnswer(answer)}@@ -250,7 +249,7 @@ export function SegmentDetail({/></div>)}- {showRegenerationModal && (+ {isEditMode && showRegenerationModal && (<RegenerationModalisShow={showRegenerationModal}onConfirm={onConfirmRegeneration}diff --git a/web/app/components/datasets/documents/detail/context.ts b/web/app/components/datasets/documents/detail/context.tsindex ae737994d97..b33c2aa88e5 100644--- a/web/app/components/datasets/documents/detail/context.ts+++ b/web/app/components/datasets/documents/detail/context.ts@@ -6,6 +6,7 @@ export type DocumentContextValue = {documentId?: stringdocForm?: ChunkingModeparentMode?: ParentMode+ canEdit?: boolean}export const DocumentContext = createContext<DocumentContextValue>({})diff --git a/web/app/components/datasets/documents/detail/index.tsx b/web/app/components/datasets/documents/detail/index.tsxindex 4b03ff319b5..40a353f6737 100644--- a/web/app/components/datasets/documents/detail/index.tsx+++ b/web/app/components/datasets/documents/detail/index.tsx@@ -217,8 +217,9 @@ const DocumentDetail: FC<DocumentDetailProps> = ({ datasetId, documentId }) => {documentId,docForm: documentDetail?.doc_form as ChunkingMode,parentMode,+ canEdit: canEditDocument,}),- [datasetId, documentId, documentDetail?.doc_form, parentMode],+ [datasetId, documentId, documentDetail?.doc_form, parentMode, canEditDocument],)const statusDetail = useMemo(diff --git a/web/app/components/datasets/formatted-text/flavours/edit-slice.tsx b/web/app/components/datasets/formatted-text/flavours/edit-slice.tsxindex 33f00172ed4..67ca50c7026 100644--- a/web/app/components/datasets/formatted-text/flavours/edit-slice.tsx+++ b/web/app/components/datasets/formatted-text/flavours/edit-slice.tsx@@ -22,6 +22,7 @@ import { SliceContainer, SliceContent, SliceDivider, SliceLabel } from './sharedtype EditSliceProps = SliceProps<{label: ReactNodeonDelete: () => void+ deleteDisabled?: booleanlabelClassName?: stringlabelInnerClassName?: stringcontentClassName?: string@@ -36,6 +37,7 @@ export const EditSlice: FC<EditSliceProps> = (props) => {className,text,onDelete,+ deleteDisabled = false,labelClassName,labelInnerClassName,contentClassName,@@ -58,7 +60,7 @@ export const EditSlice: FC<EditSliceProps> = (props) => {const role = useRole(context)const { getReferenceProps, getFloatingProps } = useInteractions([hover, dismiss, role])- const isDestructive = delBtnShow && isDelBtnHover+ const isDestructive = !deleteDisabled && delBtnShow && isDelBtnHoverreturn (<>@@ -86,7 +88,7 @@ export const EditSlice: FC<EditSliceProps> = (props) => {<SliceDivider className={cn(isDestructive && 'bg-state-destructive-hover-alt!')} />)}{delBtnShow && (- <FloatingFocusManager context={context}>+ <FloatingFocusManager context={context} disabled={deleteDisabled}><spanref={refs.setFloating}style={floatingStyles}@@ -99,7 +101,11 @@ export const EditSlice: FC<EditSliceProps> = (props) => {aria-label={t(($) => $['operation.remove'], { ns: 'common' })}variant="ghost"tone="destructive"- className="rounded-lg bg-state-destructive-hover hover:bg-state-destructive-hover"+ disabled={deleteDisabled}+ className={cn(+ 'rounded-lg',+ !deleteDisabled && 'bg-state-destructive-hover hover:bg-state-destructive-hover',+ )}onClick={(e) => {e.stopPropagation()onDelete()