Skip to content

fix(mindmap): search mindmap only shows root node - #16669

Closed
euvre wants to merge 1 commit into
infiniflow:mainfrom
euvre:fix/mindmap-empty-display
Closed

euvre wants to merge 1 commit into
infiniflow:mainfrom
euvre:fix/mindmap-empty-display

Conversation

@euvre

@euvre euvre commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Summary

The search mind-map (思维导图) only shows a single "root" node when the LLM returns an empty or unparsable markdown answer. This PR fixes the issue by adding a fallback tree built from the retrieved chunks on both the Go backend and the frontend, so the mind map always displays meaningful content.

What changed

  • internal/handler/mindmap.go

    • Return a fallback tree from the retrieved sections when the LLM answer is empty or parsing yields no children.
    • Trim whitespace from the LLM answer before deciding it is empty.
  • web/src/pages/next-search/hooks.ts

    • Pass current retrieval chunks to the mind-map request.
    • If the API returns an empty root node, build a fallback tree from the chunk contents.
    • Move the mind-map fetch into a useEffect so it reloads when the question, kb_ids, search_id, or chunks change.

How to verify

  • Run the Go mind-map parser test: bash build.sh --test ./internal/handler -run TestParseMindMapMarkdown
  • The frontend changes pass the pre-commit checks (prettier + eslint).

Type of change

  • Bug Fix (non-breaking change which fixes an issue)

Related issue

  • Search mind map cannot display correctly (only shows "root").

When the LLM returns an empty or malformed markdown answer, the mind-map
panel in the search page only shows a single 'root' node. This change adds a
fallback tree built from the retrieved chunks on both the Go backend and the
frontend.

Backend (internal/handler/mindmap.go):
- Return a fallback tree from retrieved sections when the LLM answer is empty
  or parsing yields no children.
- Trim whitespace from the LLM answer before deciding it is empty.

Frontend (web/src/pages/next-search/hooks.ts):
- Pass current retrieval chunks to the mind-map request.
- If the API returns an empty root node, build a fallback tree from the chunk
  contents so users still see a useful mind map.
- Move the mind-map fetch into a useEffect so it reloads when the question,
  kb_ids, search_id, or chunks change.

Fixes: search mindmap only shows root node
Labels: ci
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jul 6, 2026
@euvre euvre added the ci Continue Integration label Jul 6, 2026
@coderabbitai

coderabbitai Bot commented Jul 6, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds fallback mind-map generation when the primary LLM/backend response is empty or root-only. The Go handler builds a fallback tree from retrieval sections; the frontend hooks build a fallback tree from search chunks and wire the chunks parameter through the mind-map drawer flow.

Changes

Mind Map Fallback

Layer / File(s) Summary
Backend fallback mind map
internal/handler/mindmap.go
runMindMap detects nil/blank LLM answers and root-only parsed trees, returning a new fallbackMindMapFromSections result built from cleaned, truncated retrieval sections.
Frontend fallback mind map wiring
web/src/pages/next-search/hooks.ts
Adds buildFallbackMindMap to derive a tree from chunks, updates useSearchFetchMindMap to substitute it when the backend result is empty, extends useShowMindMapDrawer and useSearching to pass chunks through, and separates showModal into a handleShowModal callback.

Estimated code review effort: 2 (Simple) | ~15 minutes

Sequence Diagram(s)

sequenceDiagram
  participant useSearching
  participant useShowMindMapDrawer
  participant useSearchFetchMindMap
  participant BackendHandler
  participant LLM

  useSearching->>useShowMindMapDrawer: chunks, question, searchId
  useShowMindMapDrawer->>useSearchFetchMindMap: fetchMindMap(searchParams, chunks)
  useSearchFetchMindMap->>BackendHandler: request mind map
  BackendHandler->>LLM: get answer
  LLM-->>BackendHandler: response (nil/blank/root-only)
  BackendHandler->>BackendHandler: fallbackMindMapFromSections(sections)
  BackendHandler-->>useSearchFetchMindMap: mind map (possibly empty)
  useSearchFetchMindMap->>useSearchFetchMindMap: check root-with-no-children
  useSearchFetchMindMap->>useSearchFetchMindMap: buildFallbackMindMap(chunks)
  useSearchFetchMindMap-->>useShowMindMapDrawer: final mind map
Loading

Poem

A root with no leaves? Oh what a scare!
This bunny hops in with sections to spare 🐇
From chunks and from text, new branches take flight,
No empty mind map shall spoil the night,
Fallback trees bloom, all snug and just right!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely summarizes the main fix: the search mind map showing only the root node.
Description check ✅ Passed The description includes the required summary and adds relevant implementation, verification, type, and issue details.
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.

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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
web/src/pages/next-search/hooks.ts (1)

139-152: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Include chunks in the ref gate.
At web/src/pages/next-search/hooks.ts:139-152, the effect depends on chunks, but the isEqual(searchParams, ref.current) check only tracks question, kb_ids, and search_id. A chunks-only update re-runs the effect and then gets blocked, so fetchMindMap never fires with the new chunks. That breaks the fallback path when retrieval results arrive after the first request. Keep chunks (or a stable fingerprint) in the compared state.

🤖 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/next-search/hooks.ts` around lines 139 - 152, The effect in
next-search/hooks.ts is gating fetchMindMap with ref.current using only
question, kb_ids, and search_id, so chunks-only changes are ignored. Update the
ref comparison in the useEffect block to include chunks as part of the
stored/searchParams state, or compare against a stable chunks fingerprint, so
fetchMindMap runs when chunks changes even if the other fields stay the same.
🧹 Nitpick comments (2)
web/src/pages/next-search/hooks.ts (2)

135-138: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Fetch now decoupled from drawer open — mind map generated eagerly on every question/chunk change.

handleShowModal no longer triggers fetchMindMap; the fetch runs unconditionally via the effect whenever question/kb_ids/search_id/chunks change, even if the user never opens the mind-map drawer. This proactively calls the (likely LLM-backed) mind-map endpoint on every search, which may add unnecessary backend/LLM cost for users who never open the mind map. If this eager preloading is intentional (per PR objective), consider gating on visible or lazily fetching only when the drawer is first shown, to avoid wasted calls.

🤖 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/next-search/hooks.ts` around lines 135 - 138, The mind map
fetch in the `useCallback`/`handleShowModal` flow is now decoupled from opening
the drawer, so it runs eagerly on every `question`, `kb_ids`, `search_id`, or
`chunks` change. Update the `hooks.ts` logic so `fetchMindMap` is only triggered
when appropriate for the intended UX, ideally by gating it on `visible` or
fetching lazily inside `handleShowModal`/the drawer-open path, rather than
unconditionally in the effect.

65-80: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider typed chunk shape instead of any[].

buildFallbackMindMap and the surrounding mutation (chunks?: any[], line 95) use any throughout, losing type safety for the chunk content extraction (content_with_weight/content/text). Typing chunks against the project's existing chunk interface (e.g. as used by ITestingResult/useSelectTestingResult) would catch field-name mismatches at compile time.

🤖 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/next-search/hooks.ts` around lines 65 - 80, The fallback mind
map builder currently uses any for chunks, which removes type safety around
content extraction. Update buildFallbackMindMap and the related mutation input
to use the project’s existing chunk interface (the same shape used by
ITestingResult/useSelectTestingResult) instead of any[], and adjust the
content_with_weight/content/text access to compile against that type so
field-name mismatches are caught early.
🤖 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 `@internal/handler/mindmap.go`:
- Around line 232-246: The fallbackMindMapFromSections helper is truncating
section labels with a byte slice, which can break UTF-8 for non-ASCII text;
update the truncation logic to be rune-safe so mind map IDs remain valid for
CJK, accented characters, and emoji. Use a UTF-8 aware approach in
fallbackMindMapFromSections, and add the needed unicode/utf8 handling where the
length check and truncation happen, keeping the existing cleanMindMapText flow
intact.

---

Outside diff comments:
In `@web/src/pages/next-search/hooks.ts`:
- Around line 139-152: The effect in next-search/hooks.ts is gating fetchMindMap
with ref.current using only question, kb_ids, and search_id, so chunks-only
changes are ignored. Update the ref comparison in the useEffect block to include
chunks as part of the stored/searchParams state, or compare against a stable
chunks fingerprint, so fetchMindMap runs when chunks changes even if the other
fields stay the same.

---

Nitpick comments:
In `@web/src/pages/next-search/hooks.ts`:
- Around line 135-138: The mind map fetch in the `useCallback`/`handleShowModal`
flow is now decoupled from opening the drawer, so it runs eagerly on every
`question`, `kb_ids`, `search_id`, or `chunks` change. Update the `hooks.ts`
logic so `fetchMindMap` is only triggered when appropriate for the intended UX,
ideally by gating it on `visible` or fetching lazily inside
`handleShowModal`/the drawer-open path, rather than unconditionally in the
effect.
- Around line 65-80: The fallback mind map builder currently uses any for
chunks, which removes type safety around content extraction. Update
buildFallbackMindMap and the related mutation input to use the project’s
existing chunk interface (the same shape used by
ITestingResult/useSelectTestingResult) instead of any[], and adjust the
content_with_weight/content/text access to compile against that type so
field-name mismatches are caught early.
🪄 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

Run ID: a826efd1-ef95-4cab-ba08-650cd8931196

📥 Commits

Reviewing files that changed from the base of the PR and between 57625c9 and f6ef839.

📒 Files selected for processing (2)
  • internal/handler/mindmap.go
  • web/src/pages/next-search/hooks.ts

Comment on lines +232 to +246
func fallbackMindMapFromSections(sections []string) mindMapNode {
root := mindMapNode{ID: "root", Children: []mindMapNode{}}
for _, section := range sections {
section = cleanMindMapText(section)
if section == "" {
continue
}
if len(section) > 80 {
section = section[:80] + "..."
}
root.Children = append(root.Children, mindMapNode{ID: section, Children: []mindMapNode{}})
}
return root
}

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

Byte-based truncation can corrupt multi-byte UTF-8 text.

section[:80] truncates by byte index. For non-ASCII content (e.g. CJK, accented text, emoji) commonly present in retrieved chunk sections, this can split a multi-byte UTF-8 rune, producing an invalid/garbled string in the fallback mind map labels.

🐛 Proposed fix using rune-safe truncation
+	runeCount := 0
+	byteIdx := 0
 	for _, section := range sections {
 		section = cleanMindMapText(section)
 		if section == "" {
 			continue
 		}
-		if len(section) > 80 {
-			section = section[:80] + "..."
+		if utf8.RuneCountInString(section) > 80 {
+			runeCount = 0
+			byteIdx = 0
+			for byteIdx < len(section) && runeCount < 80 {
+				_, size := utf8.DecodeRuneInString(section[byteIdx:])
+				byteIdx += size
+				runeCount++
+			}
+			section = section[:byteIdx] + "..."
 		}
 		root.Children = append(root.Children, mindMapNode{ID: section, Children: []mindMapNode{}})
 	}

(requires importing unicode/utf8)

📝 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
func fallbackMindMapFromSections(sections []string) mindMapNode {
root := mindMapNode{ID: "root", Children: []mindMapNode{}}
for _, section := range sections {
section = cleanMindMapText(section)
if section == "" {
continue
}
if len(section) > 80 {
section = section[:80] + "..."
}
root.Children = append(root.Children, mindMapNode{ID: section, Children: []mindMapNode{}})
}
return root
}
func fallbackMindMapFromSections(sections []string) mindMapNode {
root := mindMapNode{ID: "root", Children: []mindMapNode{}}
runeCount := 0
byteIdx := 0
for _, section := range sections {
section = cleanMindMapText(section)
if section == "" {
continue
}
if utf8.RuneCountInString(section) > 80 {
runeCount = 0
byteIdx = 0
for byteIdx < len(section) && runeCount < 80 {
_, size := utf8.DecodeRuneInString(section[byteIdx:])
byteIdx += size
runeCount++
}
section = section[:byteIdx] + "..."
}
root.Children = append(root.Children, mindMapNode{ID: section, Children: []mindMapNode{}})
}
return root
}
🤖 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 `@internal/handler/mindmap.go` around lines 232 - 246, The
fallbackMindMapFromSections helper is truncating section labels with a byte
slice, which can break UTF-8 for non-ASCII text; update the truncation logic to
be rune-safe so mind map IDs remain valid for CJK, accented characters, and
emoji. Use a UTF-8 aware approach in fallbackMindMapFromSections, and add the
needed unicode/utf8 handling where the length check and truncation happen,
keeping the existing cleanMindMapText flow intact.

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.

2 participants