Skip to content

Feat: Delete dataset level graph. - #17474

Merged
yingfeng merged 1 commit into
infiniflow:mainfrom
cike8899:feat-structure-wiki
Jul 28, 2026
Merged

yingfeng merged 1 commit into
infiniflow:mainfrom
cike8899:feat-structure-wiki

Conversation

@cike8899

Copy link
Copy Markdown
Contributor

Summary

Feat: Delete dataset level graph.

@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jul 28, 2026
@cike8899 cike8899 added the ci Continue Integration label Jul 28, 2026
@cike8899
cike8899 marked this pull request as draft July 28, 2026 06:36
@cike8899
cike8899 marked this pull request as ready for review July 28, 2026 06:36
@coderabbitai

coderabbitai Bot commented Jul 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds dataset structure deletion through a DELETE service helper, React Query mutation, localized confirmation dialog, structure-kind labels, query invalidation, and graph state cleanup after successful deletion.

Changes

Dataset structure deletion

Layer / File(s) Summary
Deletion API and mutation flow
web/src/services/knowledge-service.ts, web/src/hooks/use-knowledge-request.ts
Adds the delete endpoint helper and mutation hook, including success messaging and dataset-structure query invalidation.
Confirmation UI and state reset
web/src/pages/dataset/compilation/..., web/src/locales/en.ts, web/src/locales/zh.ts
Adds localized confirmation text and structure labels, wires the delete dialog to the view, disables deletion while loading, and clears graph state after success.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: euvre, dcc123456, wangq8

Poem

A bunny taps DELETE with care,
A dialog blooms in translated air.
Graph crumbs vanish, queries renew,
Kind labels guide the button through.
Hop, hop—the structure’s cleared!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 inconclusive)

Check name Status Explanation Resolution
Description check ❓ Inconclusive The required Summary section is present, but it is too brief and lacks the background context the template asks for. Expand the Summary with brief background, the problem being solved, and a clearer description of the user-facing change.
✅ Passed checks (4 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title matches the main change: adding deletion support for the dataset-level graph.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@web/src/hooks/use-knowledge-request.ts`:
- Around line 850-855: Update the deletion mutation’s success path around
queryClient.invalidateQueries so it awaits the returned promise before
mutationFn completes. Preserve the existing success message and
DatasetStructureKeys.all(knowledgeBaseId) invalidation while keeping mutateAsync
pending until the dataset structure refresh settles.

In `@web/src/pages/dataset/compilation/dataset-structure-view.tsx`:
- Around line 133-135: Update the delete Button containing the Trash2 icon to
include aria-label={t('common.delete')}, preserving its existing variant, size,
and disabled behavior.

In `@web/src/services/knowledge-service.ts`:
- Around line 434-435: Update deleteArtifactsStructure to use the registered
service-layer pattern: register the endpoint with registerNextServer and send
the request through `@/utils/next-request` instead of calling request.delete
directly. Follow the nearest existing registered service implementation in the
same module while preserving the datasetId and kind parameters.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 768fb46e-3a46-4d43-b2f2-6783cb95215c

📥 Commits

Reviewing files that changed from the base of the PR and between cc0fbd3 and d1dae94.

📒 Files selected for processing (6)
  • web/src/hooks/use-knowledge-request.ts
  • web/src/locales/en.ts
  • web/src/locales/zh.ts
  • web/src/pages/dataset/compilation/constants.ts
  • web/src/pages/dataset/compilation/dataset-structure-view.tsx
  • web/src/services/knowledge-service.ts

Comment on lines +850 to +855
if (data?.code === 0) {
message.success(i18n.t('message.deleted'));
queryClient.invalidateQueries({
queryKey: DatasetStructureKeys.all(knowledgeBaseId),
});
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate file =="
fd -a 'use-knowledge-request\.ts$' . || true

echo "== outline =="
file="$(fd 'use-knowledge-request\.ts$' . | head -n1)"
if [ -n "${file:-}" ]; then
  echo "FILE=$file"
  wc -l "$file"
  ast-grep outline "$file" --view compact | sed -n '1,220p'
fi

echo "== relevant lines =="
if [ -n "${file:-}" ]; then
  sed -n '800,880p' "$file" | nl -ba -v800
fi

echo "== search invalidate/keys usage =="
if [ -n "${file:-}" ] || fd 'use-knowledge-request\.ts$' . >/dev/null; then
  rg -n "DatasetStructureKeys|invalidateQueries|mutateAsync|deleting|message\.deleted|isLoading|isPending" . -g 'web/src/hooks/use-knowledge-request.ts'
fi

echo "== package/react-query if present =="
for f in web/package.json package.json; do
  [ -f "$f" ] && { echo "--- $f"; jq '.dependencies["`@tanstack/react-query`"], .devDependencies["`@tanstack/react-query`"], .dependencies.react, .dependencies["`@tanstack/react-query`"]' "$f" 2>/dev/null || cat "$f"; }
done

Repository: infiniflow/ragflow

Length of output: 489


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd 'use-knowledge-request\.ts$' . | head -n1)"
echo "FILE=$file"
wc -l "$file"

echo "== relevant hook/mutation lines =="
sed -n '800,885p' "$file" | nl -ba -v800

echo "== DatasetStructureKeys/invalidate/metadata lines in file =="
rg -n "DatasetStructureKeys|invalidateQueries|mutateAsync|deleting|message\.deleted|loading|isPending|isSuccess|useMutation" "$file"

echo "== package/react-query deps =="
for f in web/package.json package.json; do
  [ -f "$f" ] && { echo "--- $f"; jq '{dependencies: .dependencies["`@tanstack/react-query`"], devDependencies: .devDependencies["`@tanstack/react-query`"]}' "$f" 2>/dev/null || true; jq '{dependencies: .dependencies.react, devDependencies: .devDependencies.react}' "$f" 2>/dev/null || true; }
done

echo "== behavioral probe: async invalidate vs await mutateAsync and mutation status =="
cat > /tmp/react-query-probe.js <<'JS'
// Model the relevant async ordering when invalidateQueries returns a promise
// and mutateAsync is awaited around the invalidate call.
(async () => {
  let deleting = true;
  let queryRefetched = false;
  let statusOrder = [];

  async function invalidateQueries() {
    return new Promise(resolve => setTimeout(() => { queryRefetched = true; statusOrder.push('refetched'); resolve(); }, 20));
  }

  async function runAwaited() {
    await invalidateQueries();
    deleting = false;
    statusOrder.push('mutation-ended');
    const finishedBeforeRefetch = !queryRefetched && !deleting;
    console.log('awaited mutation-finished-before-refetch:', finishedBeforeRefetch, 'statusOrder:', statusOrder.join(' -> '));
  }

  statusOrder = [];
  async function runUnawaited() {
    invalidateQueries(); // fire and forget
    deleting = false;
    const finishedBeforeRefetch = !queryRefetched && !deleting;
    statusOrder.push('mutation-ended');
    setTimeout(() => console.log('unawaited mutation-finished-before-refetch:', finishedBeforeRefetch, 'statusOrder:', statusOrder.join(' -> ')), 40);
  }

  await runAwaited();
  await runUnawaited();
})();
JS
node /tmp/react-query-probe.js

Repository: infiniflow/ragflow

Length of output: 323


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="$(fd 'use-knowledge-request\.ts$' . | head -n1)"
echo "FILE=$file"

echo "== relevant hook/mutation lines =="
awk 'NR>=800 && NR<=885 { printf "%d\t%s\n", NR, $0 }' "$file"

echo "== DatasetStructureKeys/invalidate/metadata lines in file =="
grep -nE "DatasetStructureKeys|invalidateQueries|mutateAsync|deleting|message\.deleted|loading|isPending|isSuccess|useMutation" "$file" || true

echo "== package/react-query deps =="
for f in web/package.json package.json; do
  if [ -f "$f" ]; then
    echo "--- $f"
    jq '{dependencies: .dependencies["`@tanstack/react-query`"], devDependencies: .devDependencies["`@tanstack/react-query`"]}' "$f" 2>/dev/null || true
    jq '{dependencies: .dependencies.react, devDependencies: .devDependencies.react}' "$f" 2>/dev/null || true
  fi
done

echo "== behavioral probe: async invalidate vs await mutateAsync and mutation status =="
node - <<'JS'
(async () => {
  let deleting = true;
  let queryRefetched = false;
  let statusOrder = [];

  async function invalidateQueries() {
    return new Promise(resolve => setTimeout(() => { queryRefetched = true; statusOrder.push('refetched'); resolve(); }, 20));
  }

  async function runAwaited() {
    await invalidateQueries();
    deleting = false;
    statusOrder.push('mutation-ended');
    const finishedBeforeRefetch = !queryRefetched && !deleting;
    console.log('awaited mutation-finished-before-refetch:', finishedBeforeRefetch, 'statusOrder:', statusOrder.join(' -> '));
  }

  statusOrder = [];
  async function runUnawaited() {
    invalidateQueries(); // fire and forget
    deleting = false;
    const finishedBeforeRefetch = !queryRefetched && !deleting;
    statusOrder.push('mutation-ended');
    setTimeout(() => console.log('unawaited mutation-finished-before-refetch:', finishedBeforeRefetch, 'statusOrder:', statusOrder.join(' -> ')), 40);
  }

  await runAwaited();
  await runUnawaited();
})();
JS

Repository: infiniflow/ragflow

Length of output: 8673


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== useDeleteDatasetStructure callers =="
grep -nE "useDeleteDatasetStructure|deleteDatasetStructure|disabled|loading" web/src -r -g '*.{ts,tsx}' || true

echo "== exact call snippets around deleteDatasetStructure =="
python3 - <<'PY'
from pathlib import Path
import re
for p in Path('web/src').rglob('*'):
    if p.suffix in {'.ts','.tsx'}:
        text=p.read_text(errors='ignore')
        if 'deleteDatasetStructure' in text:
            lines=text.splitlines()
            for i,l in enumerate(lines,1):
                if 'deleteDatasetStructure' in l:
                    start=max(1,i-8); end=min(len(lines),i+8)
                    print(f"\n--- {p}:{start}-{end} ---")
                    for n in range(start,end+1):
                        print(f"{n}\t{lines[n-1]}")
PY

Repository: infiniflow/ragflow

Length of output: 3650


Keep deletion pending until query invalidation settles.

invalidateQueries returns a promise, but here it is fired without awaiting, so mutateAsync and the consumer’s deleting state can finish before the active dataset structure query refetches. Await the invalidation inside mutationFn so the mutation remains pending until the list is refreshed.

Proposed adjustment
-        queryClient.invalidateQueries({
+        await queryClient.invalidateQueries({
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (data?.code === 0) {
message.success(i18n.t('message.deleted'));
queryClient.invalidateQueries({
queryKey: DatasetStructureKeys.all(knowledgeBaseId),
});
}
if (data?.code === 0) {
message.success(i18n.t('message.deleted'));
await queryClient.invalidateQueries({
queryKey: DatasetStructureKeys.all(knowledgeBaseId),
});
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/hooks/use-knowledge-request.ts` around lines 850 - 855, Update the
deletion mutation’s success path around queryClient.invalidateQueries so it
awaits the returned promise before mutationFn completes. Preserve the existing
success message and DatasetStructureKeys.all(knowledgeBaseId) invalidation while
keeping mutateAsync pending until the dataset structure refresh settles.

Comment on lines +133 to +135
<Button variant="outline" size="sm" disabled={deleting}>
<Trash2 />
</Button>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Add an accessible name to the delete button.

The trigger contains only <Trash2 />, so assistive technology receives an unnamed button. Add aria-label={t('common.delete')}.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/pages/dataset/compilation/dataset-structure-view.tsx` around lines
133 - 135, Update the delete Button containing the Trash2 icon to include
aria-label={t('common.delete')}, preserving its existing variant, size, and
disabled behavior.

Comment on lines +434 to +435
export const deleteArtifactsStructure = (datasetId: string, kind: string) =>
request.delete(api.artifactsStructure(datasetId), { params: { kind } });

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Route the new endpoint through the registered service layer.

This helper adds another direct umi-request call. New endpoints under web/src/services must use registerNextServer and route through @/utils/next-request; follow the nearest registered-service implementation instead of extending this legacy path.

As per coding guidelines, web/src/services/**/*.{ts,tsx} endpoints must be registered via registerNextServer and routed through @/utils/next-request.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@web/src/services/knowledge-service.ts` around lines 434 - 435, Update
deleteArtifactsStructure to use the registered service-layer pattern: register
the endpoint with registerNextServer and send the request through
`@/utils/next-request` instead of calling request.delete directly. Follow the
nearest existing registered service implementation in the same module while
preserving the datasetId and kind parameters.

Source: Coding guidelines

@wangq8
wangq8 self-requested a review July 28, 2026 06:48

@wangq8 wangq8 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Review: Feat: Delete dataset level graph

Summary

Adds ability to delete dataset-level structure graphs (Graph, MindMap, Timeline) from the compilation view, with confirmation dialog and i18n support. Clean frontend-only change backed by an existing backend DELETE endpoint.

✅ What Looks Good

  • Follows existing code patterns consistently (useMutation, react-query invalidation, ConfirmDeleteDialog)
  • Confirmation dialog before destructive action -- good UX safety
  • Delete button disabled while deleting to prevent double-clicks
  • Backend DELETE /datasets//artifacts_structure?kind= already exists and the frontend call matches the contract correctly
  • i18n support for both English and Chinese
  • State cleanup (setGraphKeywords, setSelectedNodeId) after successful deletion

⚠️ Issues

1. Layout breaks for non-Graph views (MindMap / Timeline)

The header div now always renders with justify-between, but the SelectWithSearch entity filter only renders when kind === ViewMode.Graph. For MindMap and Timeline views, the delete button sits alone on the left with empty space on the right -- looks visually broken.

Suggestion: Either conditionally use justify-end when there is no search, or always render the search slot but keep it empty for non-graph views.

2. No error handling in useDeleteDatasetStructure

The mutation only handles the success path (code === 0). If the API returns an error code, a network failure occurs, or the request is rejected by the backend, the user gets no feedback -- the dialog closes silently and nothing happens.

Suggestion: Add onError to useMutation to show an error toast.

3. Unused data from mutation hook

useDeleteDatasetStructure destructures data from useMutation but never uses it outside the mutationFn. The return value includes data but callers do not consume it. Minor cleanup.

4. Missing test coverage

No tests added for the new hook or component behavior. A test verifying the mutation flow and query invalidation would be expected.

5. Confirm dialog confirm button may lack loading state

The outer trash button correctly shows disabled={deleting}, but the ConfirmDeleteDialog confirm button may not reflect the loading state during deletion. If ConfirmDeleteDialog supports a loading or confirmLoading prop, it should be wired to the mutation pending state to prevent double-clicks on confirm.

🔍 Suggestions (non-blocking)

  • Consider adding a success toast that names the structure kind being deleted (e.g. "Knowledge Graph deleted successfully") instead of the generic message.deleted.
  • The StructureKindLabelKeyMap is a nice addition that could be reused elsewhere.

Verdict

Looks mostly good. The layout issue and error handling are the main concerns. I would request changes primarily for issues 1 and 2 before merging.

@yingfeng
yingfeng merged commit fe38d5f into infiniflow:main Jul 28, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants