Skip to content

Feat: Search for knowledge-base-level graph nodes. - #17444

Merged
yingfeng merged 19 commits into
infiniflow:mainfrom
cike8899:feat-structure-wiki
Jul 27, 2026
Merged

yingfeng merged 19 commits into
infiniflow:mainfrom
cike8899:feat-structure-wiki

Conversation

@cike8899

Copy link
Copy Markdown
Contributor

Summary

Feat: Search for knowledge-base-level graph nodes.

@dosubot dosubot Bot added the size:L This PR changes 100-499 lines, ignoring generated files. label Jul 27, 2026
@cike8899 cike8899 added the ci Continue Integration label Jul 27, 2026
@coderabbitai

coderabbitai Bot commented Jul 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d349a1a4-bdb7-4ebe-b388-a6a6951387a0

📥 Commits

Reviewing files that changed from the base of the PR and between a9cf161 and f1dbcd8.

📒 Files selected for processing (4)
  • web/src/components/structure-graph/timeline-x6-graph/types.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-blueprint-selection.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-builtin-template.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/index.tsx
🚧 Files skipped from review as they are similar to previous changes (4)
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-builtin-template.ts
  • web/src/components/structure-graph/timeline-x6-graph/types.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/index.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-blueprint-selection.ts

📝 Walkthrough

Walkthrough

The frontend adds searchable dataset structure views, Wiki artifact update controls, compilation-template group management, and an edit-next template editor. Supporting changes add graph labels, query caching, API endpoints, route wiring, shared types, localized labels, and UI behavior updates.

Changes

Graph and structure views

Layer / File(s) Summary
Graph rendering and entity search
web/src/components/artifact-force-graph/*, web/src/components/structure-graph/*, web/src/pages/chunk/representation/*
Force graphs support relation labels, center gravity, highlighting, searchable entities, and memoized graph data.
Dataset structure and Wiki updates
web/src/pages/dataset/compilation/*, web/src/hooks/use-knowledge-request.ts, web/src/services/*, web/src/utils/api.ts
Dataset structure modes, artifact alteration queries, index execution, graph keyword parameters, and Wiki update progress controls are added.
Agent compilation flow
web/src/pages/agents/*, web/src/pages/agent/*, web/src/interfaces/database/agent.ts
Compilation template groups are represented in agent listings with dedicated cards, filtering, deletion, navigation, and compiler creation behavior.

Compilation template editor

Layer / File(s) Summary
Edit-next editor
web/src/pages/user-setting/compilation-templates/edit-next/*
A new editor validates, transforms, displays, previews, and submits compilation template groups with dynamic sections, fields, blueprints, and tree configuration.
Shared contracts and UI support
web/src/routes.tsx, web/src/hooks/*, web/src/interfaces/*, web/src/locales/*, web/src/components/originui/select-with-search.tsx
Routes, query keys, request types, generation mappings, translations, and Enter/no-match selection behavior support the new flows.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant AgentPage
  participant CreateAgentForm
  participant EditNextPage
  participant CompilationTemplateService
  AgentPage->>CreateAgentForm: select compiler
  CreateAgentForm->>EditNextPage: navigate to edit-next route
  EditNextPage->>CompilationTemplateService: fetch or submit template group
  CompilationTemplateService-->>EditNextPage: return template data or save result
Loading

Possibly related PRs

Suggested labels: 💞 feature, 🧰 typescript

Poem

A rabbit hops through graphs so bright,
With Wiki updates taking flight.
Templates bloom in fields and rows,
New routes guide where editing goes.
“Thump!” says Bun, “the build now flows!”

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.78% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: adding search for knowledge-base-level graph nodes.
Description check ✅ Passed The description includes the required Summary section and briefly states the PR goal, though it is minimal.
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.

@cike8899
cike8899 marked this pull request as draft July 27, 2026 12:01
@cike8899
cike8899 marked this pull request as ready for review July 27, 2026 12:01

@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: 15

🧹 Nitpick comments (9)
web/src/components/artifact-force-graph/use-artifact-graph-data.ts (1)

50-55: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Keep the graph-data link type aligned with ArtifactGraphLink.

Line 54 now emits type, but Line 32 still declares links as { source: string; target: string }, so the hook’s public type omits the field consumed by linkLabel. Use GraphData<ArtifactGraphNode, ArtifactGraphLink> or a dedicated link-data type.

Suggested fix
-    GraphData<ArtifactGraphNode, { source: string; target: string }>
+    GraphData<ArtifactGraphNode, ArtifactGraphLink>
🤖 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/components/artifact-force-graph/use-artifact-graph-data.ts` around
lines 50 - 55, Update the graph data type declaration in the artifact graph data
hook to use GraphData<ArtifactGraphNode, ArtifactGraphLink> (or an equivalent
link type including type), so the links mapped in the relations transformation
expose type to linkLabel while preserving source and target.
web/src/pages/dataset/compilation/constants.ts (1)

10-11: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the inactive Session-mode comments.

  • web/src/pages/dataset/compilation/constants.ts#L10-L11: remove the commented enum members.
  • web/src/pages/dataset/compilation/constants.ts#L23-L24: remove the commented structure-mode entries.
  • web/src/pages/dataset/compilation/constants.ts#L38-L39: remove the commented generation mappings.
  • web/src/pages/dataset/compilation/index.tsx#L52-L59: remove the commented selector options.

As per coding guidelines, remove commented-out code rather than preserving inactive implementation paths.

🤖 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/constants.ts` around lines 10 - 11, Remove
the inactive commented-out Session-mode enum members, structure-mode entries,
generation mappings, and selector options. Apply the cleanup at
web/src/pages/dataset/compilation/constants.ts lines 10-11, 23-24, and 38-39,
plus web/src/pages/dataset/compilation/index.tsx lines 52-59; no replacement
implementation is needed.

Source: Coding guidelines

web/src/pages/dataset/compilation/wiki-left-panel/wiki-nav-bar.tsx (1)

89-97: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the unreachable directory-creation flow.

The sole trigger is permanently hidden, so useCreateDirectory, CreateDirectoryDialog, and the Plus import are now dead in this component. Delete them rather than preserving an inaccessible path.

As per coding guidelines, “Remove dead tests, commented-out code, stale documentation, and 'move later' notes instead of preserving them.”

🤖 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/wiki-left-panel/wiki-nav-bar.tsx` around
lines 89 - 97, Remove the unreachable directory-creation flow from the wiki
navigation component: delete the hidden create button using
handleShowCreateDialog, the useCreateDirectory integration, the
CreateDirectoryDialog rendering, and the unused Plus import. Preserve the
remaining navigation behavior and remove any now-unused related symbols.

Source: Coding guidelines

web/src/pages/agents/index.tsx (1)

94-104: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reimplements route-building already provided by navigateToCompilationTemplateEditNext.

handleAddCompilation/handleEditCompilation manually construct the CompilationTemplatesEditNext URL (with ?source=agents) instead of reusing useNavigatePage().navigateToCompilationTemplateEditNext, which builds the same route but lacks query-param support. As per coding guidelines, "Before adding logic such as ... boilerplate, search for duplicate or similar hooks and functions and reuse them instead of reimplementing the behavior inline."

🤖 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/agents/index.tsx` around lines 94 - 104, Update
handleAddCompilation and handleEditCompilation to reuse
useNavigatePage().navigateToCompilationTemplateEditNext instead of manually
constructing the CompilationTemplatesEditNext URLs. Extend or use that
navigation helper to preserve the source=agents query parameter for both
creating and editing compilation templates.

Source: Coding guidelines

web/src/pages/agents/create-agent-form.tsx (1)

33-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use PascalCase for top-level React constants.

  • web/src/pages/agents/create-agent-form.tsx#L33-L43: rename FLOW_TYPE_CONFIG to FlowTypeConfig.
  • web/src/pages/user-setting/compilation-templates/edit-next/index.tsx#L16-L18: rename agentsUrl to AgentsUrl.

As per coding guidelines, “Use PascalCase for React component names and top-level constants.”

🤖 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/agents/create-agent-form.tsx` around lines 33 - 43, Rename the
top-level constant FLOW_TYPE_CONFIG to FlowTypeConfig in
web/src/pages/agents/create-agent-form.tsx:33-43 and update all references.
Rename agentsUrl to AgentsUrl in
web/src/pages/user-setting/compilation-templates/edit-next/index.tsx:16-18 and
update all references.

Source: Coding guidelines

web/src/hooks/use-compilation-template-group-request.ts (1)

229-232: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use a query-key factory for this invalidation.

Define an AgentKeys factory returning as const keys, then use it here and migrate the other query/invalidation keys in this hook to their domain factories.

As per coding guidelines, “Never write raw React Query queryKey arrays inline. Define a same-file {Domain}Keys factory whose return values use as const.”

🤖 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-compilation-template-group-request.ts` around lines 229 -
232, Replace the inline queryKey arrays throughout the hook, including the
AgentApiAction.FetchAgentListByPage invalidation, with a same-file AgentKeys
factory whose returned keys use as const. Migrate all other query and
invalidation keys in this hook to the appropriate domain key factories while
preserving their existing key values and behavior.

Source: Coding guidelines

web/src/pages/user-setting/compilation-templates/edit-next/components/json-preview-sheet.tsx (1)

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

Duplicated Sheet/Tooltip scaffold between JsonPreviewSheet and WorkflowPreviewSheet. Both components share an identical Sheet + Tooltip + icon-Button trigger + SheetHeader/SheetTitle structure, differing only by icon, translation keys, and body content — a good candidate for a shared reusable wrapper per the "avoid duplicated JSX structures, favor reusable components" guideline.

  • web/src/pages/user-setting/compilation-templates/edit-next/components/json-preview-sheet.tsx#L25-62: extract the Sheet/Tooltip scaffold into a shared PreviewSheet component parameterized by icon, title, and children (the body), then render <JsonEditor .../> as its children.
  • web/src/pages/user-setting/compilation-templates/edit-next/components/workflow-preview-sheet.tsx#L23-56: reuse the same shared PreviewSheet component, passing the Workflow icon, processFlow title, and the coming-soon placeholder as children.

As per coding guidelines, "Keep components lean by extracting complex logic into hooks or utilities, avoiding duplicated JSX structures, and favoring render props or reusable components."

🤖 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/user-setting/compilation-templates/edit-next/components/json-preview-sheet.tsx`
at line 1, Extract the duplicated Sheet/Tooltip trigger and header JSX from
JsonPreviewSheet and WorkflowPreviewSheet into a shared PreviewSheet component,
parameterized by icon, title, and children. Update JsonPreviewSheet to pass its
JsonEditor as children, and WorkflowPreviewSheet to pass the Workflow icon,
processFlow title, and coming-soon content while preserving each component’s
existing behavior.

Source: Path instructions

web/src/pages/user-setting/compilation-templates/edit-next/components/add-field-modal.tsx (1)

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

Inline JSX event handlers across the edit-next editor. Several new components define onChange/onEdit/onDelete/onKeyDown as inline arrow functions instead of extracted named handlers, per the repo's frontend guideline for web/src/**/*.{ts,tsx}.

  • web/src/pages/user-setting/compilation-templates/edit-next/components/add-field-modal.tsx#L87-103: extract the onChange at L94-97 (which calls field.onChange then handleTypeChange) into a useCallback-wrapped named handler.
  • web/src/pages/user-setting/compilation-templates/edit-next/components/section-field-grid.tsx#L38-59: extract onEdit, onDelete (per-row) and the card's onKeyDown into named handlers (e.g. via a small per-row sub-component or useCallback factory keyed by index).
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx#L163-177: extract the onChange at L171 ((value) => handleKindChange(field, value)) into a named handler.

As per coding guidelines, "Avoid inline JSX event handlers such as onClick={() => ...} and onChange={(e) => ...}; extract handlers and reference named functions instead."

🤖 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/user-setting/compilation-templates/edit-next/components/add-field-modal.tsx`
at line 1, Replace the inline JSX event handlers identified across the edit-next
editor with named handlers: in the add-field modal, use a useCallback handler
that invokes field.onChange and handleTypeChange; in section-field-grid, extract
per-row onEdit/onDelete and the card onKeyDown via named handlers or a small row
component; in template-configuration, extract the field kind onChange into a
named handler. Update JSX to reference these handlers directly while preserving
existing behavior.

Source: Path instructions

web/src/pages/user-setting/compilation-templates/edit-next/utils.ts (1)

102-226: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Duplicated config-building logic between buildConfigFromBuiltin and transformDetailToForm.

Both functions build near-identical config base objects (kind/llm_id/global_rules/example/synthesis/use_blueprint, instruction/page_example splitting, raptor defaults, section normalization loop). Extracting a shared helper would reduce the risk of the two diverging as new config fields are added.

🤖 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/user-setting/compilation-templates/edit-next/utils.ts` around
lines 102 - 226, The config construction in buildConfigFromBuiltin and
transformDetailToForm is duplicated and can diverge. Extract the shared
base-config creation, blueprint field splitting, Tree raptor defaults, and
section normalization into a reusable helper, then update both functions to use
it while preserving their existing inputs, metadata, and return shapes.
🤖 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/components/artifact-force-graph/utils.ts`:
- Around line 7-15: Update getBaseLinkColor so it returns the existing `#b2b5b7`
fallback when the trimmed --border-default value is empty, while preserving the
current fallback for missing window or element and returning the computed color
when present.

In `@web/src/hooks/use-agent-request.ts`:
- Around line 141-151: Extract the shared single-value derivation from
use-agent-request.ts around the request parameter construction into an exported
helper such as getSingleFilterValue, and use it for canvasCategory. In
web/src/hooks/use-agent-request.ts lines 141-151, update the local derivation to
call that helper; in web/src/pages/agents/index.tsx lines 32-55, replace the
duplicate derivation with the same helper and compare against
AgentListItemType.CompilationTemplateGroup imported from
`@/interfaces/database/agent` instead of the local string literal.

In `@web/src/hooks/use-knowledge-request.ts`:
- Around line 791-803: Update useRunArtifactIndex to invalidate
artifactGraphKeys.graph(knowledgeBaseId) after the artifact index completes,
alongside the existing alteration, list, topic, and artifact trace
invalidations. Use the exact graph key consumed by WikiGraphPanel so the
artifact-graph cache refreshes immediately.

In `@web/src/locales/en.ts`:
- Line 1866: Update the llmForExtraction translation value to use sentence case:
capitalize only the first word while preserving the rest of the label.

In `@web/src/pages/agents/index.tsx`:
- Line 32: Replace the local CompilationGroupCategory magic string with
AgentListItemType.CompilationTemplateGroup at its comparison site. Extract the
duplicated canvasCategory derivation from this page and use-agent-request.ts
into a shared hook or utility, then update both consumers to reuse it.
- Around line 183-201: Replace the `(data as any[])` cast in the agent list
rendering with a discriminated-union return type from `useFetchAgentListByPage`,
using the existing `AgentListItemType` values for agent and compilation-template
groups. Narrow each item by its `type` discriminator before rendering
`CompilationTemplateCard` or `AgentCard`, and update the surrounding conditional
as needed so both branches receive their correct typed shape.

In `@web/src/pages/dataset/compilation/wiki-left-panel/index.tsx`:
- Around line 61-64: Update handleUpdateClick to handle the success result or
rejection from handleUpdate: keep the progress sheet open only when an update
task starts, and call onUpdateSheetOpenChange(false) when handleUpdate returns a
non-success response or throws. Modify handleUpdate to return an explicit
success indicator that distinguishes task creation from failure.

In `@web/src/pages/dataset/compilation/wiki-left-panel/wiki-update-sheet.tsx`:
- Around line 85-92: Update the pause control in the status action around
handlePause to use a native button instead of a clickable span, and add an
accessible label describing the pause action. Preserve the existing
failed-status condition, click handler, styling, and CirclePause icon.
- Around line 68-80: Update the width class values in the status-based `cn` call
to use valid CSS `calc()` subtraction syntax with whitespace around the minus
operator for both `running` and `failed` states. Preserve the existing width
offsets and all other progress-bar behavior.

In
`@web/src/pages/user-setting/compilation-templates/edit-next/components/add-field-modal.tsx`:
- Around line 69-84: The Modal title in add-field-modal should use the same
localized section-label resolution as template-configuration.tsx: apply
SectionTitleKeyMap[sectionName] when available and fall back to
startCase(sectionName), then pass that key through t(). Reuse the existing
SectionTitleKeyMap symbol and preserve the current add/edit title selection.

In
`@web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-blueprint-selection.ts`:
- Line 31: Update the selection state in useBlueprintSelection so selectedValue
follows the freshly computed matchedPresetId when content changes instead of
being permanently overridden by explicitValue. Track an explicit custom override
only when the user diverges from a preset, reset that override when
matchedPresetId becomes defined again, and clear it from handlePageExampleChange
and kind-change flows so the dropdown cannot remain stale.

In
`@web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-form.ts`:
- Around line 30-40: Update the useEffect in the compilation template group form
to avoid resetting user edits when a refetch replaces detail with an equivalent
record: track the loaded detail.id and form dirty state, and only call
form.reset through transformGroupDetailToForm when the underlying group changes
or an explicit initial-load/reset trigger occurs. Preserve the create-mode
defaultLlmId initialization in the existing branch.

In `@web/src/pages/user-setting/compilation-templates/edit-next/schema.ts`:
- Around line 19-44: The buildSynthesisSchema branch is a catch-all for object
configs because all fields are optional and passthrough is enabled. Make
synthesis configs strictly identifiable by requiring a discriminator/type field
and rejecting unknown keys, or refactor buildTemplateSchema’s config union to
use a discriminated union with distinct required type values while preserving
the existing raptor and section validation.

In `@web/src/pages/user-setting/compilation-templates/index.tsx`:
- Around line 30-33: Converge the compilation-template group flow on the new
Next implementation: update the create-group action and related handlers in the
page component to use navigateToCompilationTemplateEditNext, remove the legacy
navigateToCompilationTemplate usage and overlapping old entry point, and replace
the literal placeholder Next button with the existing translated/action path so
only one group flow remains.

In `@web/src/utils/compilation-template-util.ts`:
- Around line 5-11: Update formatKindLabel to return
t('knowledgeDetails.llmWiki') for CompilationTemplateKind.Artifacts instead of
the hard-coded Wiki label, and add the missing knowledgeDetails.structureGraph
translation key to the Japanese locale so both supported labels remain
localized.

---

Nitpick comments:
In `@web/src/components/artifact-force-graph/use-artifact-graph-data.ts`:
- Around line 50-55: Update the graph data type declaration in the artifact
graph data hook to use GraphData<ArtifactGraphNode, ArtifactGraphLink> (or an
equivalent link type including type), so the links mapped in the relations
transformation expose type to linkLabel while preserving source and target.

In `@web/src/hooks/use-compilation-template-group-request.ts`:
- Around line 229-232: Replace the inline queryKey arrays throughout the hook,
including the AgentApiAction.FetchAgentListByPage invalidation, with a same-file
AgentKeys factory whose returned keys use as const. Migrate all other query and
invalidation keys in this hook to the appropriate domain key factories while
preserving their existing key values and behavior.

In `@web/src/pages/agents/create-agent-form.tsx`:
- Around line 33-43: Rename the top-level constant FLOW_TYPE_CONFIG to
FlowTypeConfig in web/src/pages/agents/create-agent-form.tsx:33-43 and update
all references. Rename agentsUrl to AgentsUrl in
web/src/pages/user-setting/compilation-templates/edit-next/index.tsx:16-18 and
update all references.

In `@web/src/pages/agents/index.tsx`:
- Around line 94-104: Update handleAddCompilation and handleEditCompilation to
reuse useNavigatePage().navigateToCompilationTemplateEditNext instead of
manually constructing the CompilationTemplatesEditNext URLs. Extend or use that
navigation helper to preserve the source=agents query parameter for both
creating and editing compilation templates.

In `@web/src/pages/dataset/compilation/constants.ts`:
- Around line 10-11: Remove the inactive commented-out Session-mode enum
members, structure-mode entries, generation mappings, and selector options.
Apply the cleanup at web/src/pages/dataset/compilation/constants.ts lines 10-11,
23-24, and 38-39, plus web/src/pages/dataset/compilation/index.tsx lines 52-59;
no replacement implementation is needed.

In `@web/src/pages/dataset/compilation/wiki-left-panel/wiki-nav-bar.tsx`:
- Around line 89-97: Remove the unreachable directory-creation flow from the
wiki navigation component: delete the hidden create button using
handleShowCreateDialog, the useCreateDirectory integration, the
CreateDirectoryDialog rendering, and the unused Plus import. Preserve the
remaining navigation behavior and remove any now-unused related symbols.

In
`@web/src/pages/user-setting/compilation-templates/edit-next/components/add-field-modal.tsx`:
- Line 1: Replace the inline JSX event handlers identified across the edit-next
editor with named handlers: in the add-field modal, use a useCallback handler
that invokes field.onChange and handleTypeChange; in section-field-grid, extract
per-row onEdit/onDelete and the card onKeyDown via named handlers or a small row
component; in template-configuration, extract the field kind onChange into a
named handler. Update JSX to reference these handlers directly while preserving
existing behavior.

In
`@web/src/pages/user-setting/compilation-templates/edit-next/components/json-preview-sheet.tsx`:
- Line 1: Extract the duplicated Sheet/Tooltip trigger and header JSX from
JsonPreviewSheet and WorkflowPreviewSheet into a shared PreviewSheet component,
parameterized by icon, title, and children. Update JsonPreviewSheet to pass its
JsonEditor as children, and WorkflowPreviewSheet to pass the Workflow icon,
processFlow title, and coming-soon content while preserving each component’s
existing behavior.

In `@web/src/pages/user-setting/compilation-templates/edit-next/utils.ts`:
- Around line 102-226: The config construction in buildConfigFromBuiltin and
transformDetailToForm is duplicated and can diverge. Extract the shared
base-config creation, blueprint field splitting, Tree raptor defaults, and
section normalization into a reusable helper, then update both functions to use
it while preserving their existing inputs, metadata, and return shapes.
🪄 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: 2a34c64d-799c-4394-a493-4497cc0233c9

📥 Commits

Reviewing files that changed from the base of the PR and between f73f4cb and a9cf161.

⛔ Files ignored due to path filters (1)
  • web/package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (97)
  • web/package.json
  • web/src/components/artifact-force-graph/index.tsx
  • web/src/components/artifact-force-graph/node-label.ts
  • web/src/components/artifact-force-graph/types.ts
  • web/src/components/artifact-force-graph/use-artifact-graph-data.ts
  • web/src/components/artifact-force-graph/use-center-gravity.ts
  • web/src/components/artifact-force-graph/use-graph-highlight.ts
  • web/src/components/artifact-force-graph/utils.ts
  • web/src/components/floating-chat-widget-markdown.tsx
  • web/src/components/markdown-content/index.tsx
  • web/src/components/next-markdown-content/index.tsx
  • web/src/components/originui/select-with-search.tsx
  • web/src/components/structure-graph/adapters.ts
  • web/src/components/structure-graph/mindmap-g6-graph/index.tsx
  • web/src/components/structure-graph/mindmap-g6-graph/types.ts
  • web/src/components/structure-graph/representation-renderer.tsx
  • web/src/components/structure-graph/timeline-x6-graph/hooks/use-x6-graph.ts
  • web/src/components/structure-graph/timeline-x6-graph/index.tsx
  • web/src/components/structure-graph/timeline-x6-graph/types.ts
  • web/src/hooks/logic-hooks/navigate-hooks.ts
  • web/src/hooks/use-agent-request.ts
  • web/src/hooks/use-compilation-template-group-request.ts
  • web/src/hooks/use-compilation-template-request.ts
  • web/src/hooks/use-document-request.ts
  • web/src/hooks/use-knowledge-request.ts
  • web/src/interfaces/database/agent.ts
  • web/src/interfaces/database/dataset.ts
  • web/src/interfaces/request/knowledge.ts
  • web/src/locales/en.ts
  • web/src/locales/ja.ts
  • web/src/locales/zh.ts
  • web/src/pages/agent/canvas/node/compilation-node.tsx
  • web/src/pages/agent/constant/pipeline.tsx
  • web/src/pages/agent/form/compilation-form/index.tsx
  • web/src/pages/agent/hooks/use-add-node.ts
  • web/src/pages/agents/agent-card.tsx
  • web/src/pages/agents/agent-templates.tsx
  • web/src/pages/agents/compilation-template-card.tsx
  • web/src/pages/agents/compilation-template-dropdown.tsx
  • web/src/pages/agents/constant.ts
  • web/src/pages/agents/create-agent-dialog.tsx
  • web/src/pages/agents/create-agent-form.tsx
  • web/src/pages/agents/hooks/use-select-filters.ts
  • web/src/pages/agents/index.tsx
  • web/src/pages/chunk/representation/components/representation-select.tsx
  • web/src/pages/chunk/representation/hooks/use-graph-entity-search.ts
  • web/src/pages/chunk/representation/index.tsx
  • web/src/pages/dataset/compilation/constants.ts
  • web/src/pages/dataset/compilation/dataset-structure-view.tsx
  • web/src/pages/dataset/compilation/empty-state.tsx
  • web/src/pages/dataset/compilation/index.tsx
  • web/src/pages/dataset/compilation/llm-wiki-view.tsx
  • web/src/pages/dataset/compilation/skills-view.tsx
  • web/src/pages/dataset/compilation/wiki-left-panel/hooks/use-wiki-update.ts
  • web/src/pages/dataset/compilation/wiki-left-panel/index.tsx
  • web/src/pages/dataset/compilation/wiki-left-panel/wiki-graph-panel.tsx
  • web/src/pages/dataset/compilation/wiki-left-panel/wiki-nav-bar.tsx
  • web/src/pages/dataset/compilation/wiki-left-panel/wiki-update-sheet.tsx
  • web/src/pages/dataset/dataset-overview/dataset-common.ts
  • web/src/pages/dataset/dataset/generate-button/constants.ts
  • web/src/pages/dataset/dataset/generate-button/hook.ts
  • web/src/pages/next-search/markdown-content/index.tsx
  • web/src/pages/user-setting/compilation-templates/create-next/components/template-sidebar.tsx
  • web/src/pages/user-setting/compilation-templates/create-next/hooks/use-create-next-compilation-template-group.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/components/add-field-modal.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/blueprint-section.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/field-card.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/json-preview-sheet.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/section-field-grid.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-configuration.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/template-preview-header.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/tree-template-fields.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/components/workflow-preview-sheet.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-active-section-tab.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-add-field-form.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-available-kind-options.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-blueprint-selection.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-builtin-template.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-form.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-submit.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-edit-next-compilation-template-group.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-field-array-handlers.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-field-modal.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-template-kind-change.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-template-preview-sheets.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-template-section-data.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/index.tsx
  • web/src/pages/user-setting/compilation-templates/edit-next/schema.ts
  • web/src/pages/user-setting/compilation-templates/edit-next/utils.ts
  • web/src/pages/user-setting/compilation-templates/index.tsx
  • web/src/pages/user-setting/compilation-templates/template-card.tsx
  • web/src/pages/user-setting/sidebar/index.tsx
  • web/src/routes.tsx
  • web/src/services/document-structure-service.ts
  • web/src/services/knowledge-service.ts
  • web/src/utils/api.ts
  • web/src/utils/compilation-template-util.ts
💤 Files with no reviewable changes (3)
  • web/src/pages/agent/constant/pipeline.tsx
  • web/src/pages/agent/form/compilation-form/index.tsx
  • web/src/pages/user-setting/sidebar/index.tsx

Comment on lines +7 to +15
export const getBaseLinkColor = (element?: HTMLElement | null): string => {
if (typeof window === 'undefined' || !element) {
return '#b2b5b7';
}
return window
.getComputedStyle(element)
.getPropertyValue('--border-default')
.trim();
};

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 | 🟡 Minor | ⚡ Quick win

Fall back when --border-default is unset.

When the element exists but the CSS variable is missing, .trim() returns ''; getLinkColor then receives an invalid empty color. Return the existing fallback whenever the computed token is empty.

Suggested fix
-  return window
+  const color = window
     .getComputedStyle(element)
     .getPropertyValue('--border-default')
     .trim();
+  return color || '`#b2b5b7`';
📝 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
export const getBaseLinkColor = (element?: HTMLElement | null): string => {
if (typeof window === 'undefined' || !element) {
return '#b2b5b7';
}
return window
.getComputedStyle(element)
.getPropertyValue('--border-default')
.trim();
};
export const getBaseLinkColor = (element?: HTMLElement | null): string => {
if (typeof window === 'undefined' || !element) {
return '`#b2b5b7`';
}
const color = window
.getComputedStyle(element)
.getPropertyValue('--border-default')
.trim();
return color || '`#b2b5b7`';
};
🤖 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/components/artifact-force-graph/utils.ts` around lines 7 - 15, Update
getBaseLinkColor so it returns the existing `#b2b5b7` fallback when the trimmed
--border-default value is empty, while preserving the current fallback for
missing window or element and returning the computed color when present.

Comment on lines 141 to +151
const canvasCategory = Array.isArray(filterValue.canvasCategory)
? filterValue.canvasCategory
: [];
? (filterValue.canvasCategory[0] as string | undefined)
: undefined;
const owner = filterValue.owner;
const tags = Array.isArray(filterValue.tags) ? filterValue.tags : undefined;

const requestParams = buildAgentListParams({
page: pagination.current,
pageSize: pagination.pageSize,
keywords: debouncedSearchString,
canvasCategory: canvasCategory.length === 1 ? canvasCategory[0] : undefined,
canvasCategory,

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 | ⚡ Quick win

Duplicate canvasCategory derivation logic across two files. Both sites independently implement Array.isArray(filterValue.canvasCategory) ? arr[0] : undefined, and both had to be edited together in this PR — a sign of drift risk if one is updated without the other.

  • web/src/hooks/use-agent-request.ts#L141-L151: extract this derivation into a shared helper/hook (e.g. getSingleFilterValue(filterValue.canvasCategory)) and export it for reuse.
  • web/src/pages/agents/index.tsx#L32-L55: reuse the shared helper here instead of re-deriving canvasCategory, and replace the local CompilationGroupCategory string literal with AgentListItemType.CompilationTemplateGroup (imported from @/interfaces/database/agent) so the comparison stays type-linked to the enum.
📍 Affects 2 files
  • web/src/hooks/use-agent-request.ts#L141-L151 (this comment)
  • web/src/pages/agents/index.tsx#L32-L55
🤖 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-agent-request.ts` around lines 141 - 151, Extract the
shared single-value derivation from use-agent-request.ts around the request
parameter construction into an exported helper such as getSingleFilterValue, and
use it for canvasCategory. In web/src/hooks/use-agent-request.ts lines 141-151,
update the local derivation to call that helper; in
web/src/pages/agents/index.tsx lines 32-55, replace the duplicate derivation
with the same helper and compare against
AgentListItemType.CompilationTemplateGroup imported from
`@/interfaces/database/agent` instead of the local string literal.

Comment on lines +791 to +803
export const DatasetStructureKeys = {
all: (datasetId: string) =>
[KnowledgeApiAction.FetchDatasetStructure, datasetId] as const,
kind: (datasetId: string, kind: string) =>
[KnowledgeApiAction.FetchDatasetStructure, datasetId, kind] as const,
kindWithKeywords: (datasetId: string, kind: string, keywords: string) =>
[
KnowledgeApiAction.FetchDatasetStructure,
datasetId,
kind,
keywords,
] as const,
};

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
fd -a use-wiki-update.ts | xargs cat -n

Repository: infiniflow/ragflow

Length of output: 1274


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== files =="
fd -a use-knowledge-request.ts | while read -r f; do
  echo "$f"
  wc -l "$f"
done

echo "== relevant key references =="
rg -n "DatasetStructureKeys|FetchDatasetStructure|FetchArtifactGraph|artifactGraphKeys|useFetchDatasetStructureGraph|WikiGraphPanel|dataset-structure-view" web/src -S

echo "== use-knowledge-request sections =="
file="$(fd -a use-knowledge-request.ts | head -n1)"
if [ -n "${file:-}" ]; then
  echo "--- section 760-830 ---"
  sed -n '760,830p' "$file" | cat -n | sed 's/^/  /'
  echo "--- section 900-990 ---"
  sed -n '900,990p' "$file" | cat -n | sed 's/^/  /'
fi

echo "== invalidation/key calls summary =="
python3 - <<'PY'
from pathlib import Path
p = next(Path('web/src').rglob('use-knowledge-request.ts'))
text = p.read_text()
for needle in ('DatasetStructureKeys', 'artifactGraphKeys', 'useFetchDatasetStructureGraph'):
    print("\n", needle)
    for i,line in enumerate(text.splitlines(), 1):
        if needle in line:
            print(f"{p}:{i}: {line}")
PY

Repository: infiniflow/ragflow

Length of output: 10945


Invalidate the artifact-graph cache after running the artifact index.

useRunArtifactIndex currently only invalidates alteration/list/topic and artifact trace queries, but WikiGraphPanel reads artifactGraphKeys.graph(knowledgeBaseId), so the static graph remains stale until unrelated queries refresh. Add an exact key invalidation for artifactGraphKeys.graph(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 791 - 803, Update
useRunArtifactIndex to invalidate artifactGraphKeys.graph(knowledgeBaseId) after
the artifact index completes, alongside the existing alteration, list, topic,
and artifact trace invalidations. Use the exact graph key consumed by
WikiGraphPanel so the artifact-graph cache refreshes immediately.

Comment thread web/src/locales/en.ts
templateNameRequired: 'Please input template name',
templateDescription: 'Description',
llmForExtraction: 'LLM for extraction',
llmForExtraction: 'Default Model for extraction',

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 | 🟡 Minor | ⚡ Quick win

Use sentence case for this label.

Change this to Default model for extraction.

As per coding guidelines, “In en.ts, use sentence case for translations while preserving proper nouns.”

🤖 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/locales/en.ts` at line 1866, Update the llmForExtraction translation
value to use sentence case: capitalize only the first word while preserving the
rest of the label.

Source: Coding guidelines

import { useHandleImportJsonFile } from './use-import-json';
import { useRenameAgent } from './use-rename-agent';

const CompilationGroupCategory = 'compilation_template_group';

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 | ⚡ Quick win

Use the shared enum instead of a local magic string; derivation duplicated with use-agent-request.ts.

CompilationGroupCategory re-implements AgentListItemType.CompilationTemplateGroup as a raw string with no compile-time link to the enum, and the canvasCategory derivation (lines 48-54) is identical to the one in use-agent-request.ts (lines 141-143) — both had to change together in this PR.

♻️ Proposed fix
-const CompilationGroupCategory = 'compilation_template_group';
+import { AgentListItemType } from '`@/interfaces/database/agent`';

Then replace CompilationGroupCategory with AgentListItemType.CompilationTemplateGroup at the comparison site, and extract the canvasCategory derivation into a shared hook/util reused by both this file and use-agent-request.ts.

Also applies to: 48-55

🤖 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/agents/index.tsx` at line 32, Replace the local
CompilationGroupCategory magic string with
AgentListItemType.CompilationTemplateGroup at its comparison site. Extract the
duplicated canvasCategory derivation from this page and use-agent-request.ts
into a shared hook or utility, then update both consumers to reuse it.

presets,
}: UseBlueprintSelectionParams) {
const { t } = useTranslation();
const [explicitValue, setExplicitValue] = useState<string>();

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

Dropdown selection desyncs from actual instruction/page_example content.

selectedValue prefers explicitValue over the freshly computed matchedPresetId (Line 55). Once a preset is picked, explicitValue is pinned for the component lifetime. Any later edit to the content — via the instructionPath textarea bound directly in blueprint-section.tsx (Lines 54-59, which never touches this hook's state), via handlePageExampleChange (Lines 111-116), or via a kind change resetting config (use-template-kind-change.ts) — changes the actual instruction/page_example, yet the dropdown keeps showing the old preset because explicitValue still overrides the recomputed matchedPresetId. Users can end up with a preset shown as "selected" while its content has diverged, or vice versa.

🐛 Proposed fix: derive selection from content, only forcing "custom" when the user explicitly diverges
-  const [explicitValue, setExplicitValue] = useState<string>();
+  const [isCustomOverride, setIsCustomOverride] = useState(false);
@@
-  const selectedValue =
-    explicitValue ?? matchedPresetId ?? CustomBlueprintValue;
+  const selectedValue = matchedPresetId
+    ? matchedPresetId
+    : isCustomOverride
+      ? CustomBlueprintValue
+      : (matchedPresetId ?? CustomBlueprintValue);
@@
   const handleSelect = useCallback(
     (value: string) => {
       if (value === selectedValue) return;
-      setExplicitValue(value);
+      setIsCustomOverride(value === CustomBlueprintValue);

Also reset isCustomOverride (or the equivalent flag) whenever matchedPresetId becomes defined again, and clear it in handlePageExampleChange/kind-change flows so "custom" doesn't get stuck once content diverges further.

Also applies to: 43-116

🤖 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/user-setting/compilation-templates/edit-next/hooks/use-blueprint-selection.ts`
at line 31, Update the selection state in useBlueprintSelection so selectedValue
follows the freshly computed matchedPresetId when content changes instead of
being permanently overridden by explicitValue. Track an explicit custom override
only when the user diverges from a preset, reset that override when
matchedPresetId becomes defined again, and clear it from handlePageExampleChange
and kind-change flows so the dropdown cannot remain stale.

Comment on lines +30 to +40
useEffect(() => {
if (detail) {
form.reset(transformGroupDetailToForm(detail));
} else if (
isCreate &&
defaultLlmId &&
!form.getValues('templates.0.llm_id')
) {
form.setValue('templates.0.llm_id', defaultLlmId);
}
}, [defaultLlmId, detail, form, isCreate]);

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Locate relevant files:"
fd -a 'use-compilation-template-group-form|use-compilation-template-group-request|compilation-templates' web/src 2>/dev/null | sed 's#^\./##'

echo
echo "Search hook usages:"
rg -n "useFetchCompilationTemplateGroup|useCompilationTemplateGroupForm|staleTime|refetchOnWindowFocus|invalidate|detail:" web/src || true

echo
echo "Inspect target hook outline and contents:"
if [ -f web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-form.ts ]; then
  wc -l web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-form.ts
  cat -n web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-form.ts
fi

echo
echo "Inspect request file outline and contents:"
request_file="$(fd 'use-compilation-template-group-request' web/src 2>/dev/null | head -n 1)"
if [ -n "${request_file:-}" ]; then
  wc -l "$request_file"
  cat -n "$request_file"
fi

Repository: infiniflow/ragflow

Length of output: 31278


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Check app-level query client defaults:"
if [ -f web/src/app.tsx ]; then
  cat -n web/src/app.tsx | sed -n '1,110p'
fi

echo
echo "Find all query options for useFetchCompilationTemplateGroup key/action:"
rg -n "FetchCompilationTemplateGroup|refetchOnWindowFocus:" web/src -g '*.ts' -g '*.tsx'

echo
echo "Inspect edit next wrappers and mutation calls:"
for f in \
  web/src/pages/user-setting/compilation-templates/edit-next/hooks/use-edit-next-compilation-template-group.ts \
  web/src/pages/user-setting/compilation-templates/edit-next/index.tsx
do
  echo "--- $f"
  wc -l "$f"
  cat -n "$f"
done

Repository: infiniflow/ragflow

Length of output: 14570


Reset the form only when the loaded template group changes.

useFetchCompilationTemplateGroup uses the app-wide refetch settings, so a successful refetch can replace the detail object even though the user is still editing. Guard the reset by detail.id/dirty tracking, with an explicit reset trigger when the underlying record is intentionally loaded.

🤖 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/user-setting/compilation-templates/edit-next/hooks/use-compilation-template-group-form.ts`
around lines 30 - 40, Update the useEffect in the compilation template group
form to avoid resetting user edits when a refetch replaces detail with an
equivalent record: track the loaded detail.id and form dirty state, and only
call form.reset through transformGroupDetailToForm when the underlying group
changes or an explicit initial-load/reset trigger occurs. Preserve the
create-mode defaultLlmId initialization in the existing branch.

Comment on lines +19 to +44
export const buildSynthesisSchema = () =>
z
.object({
compile_kwd: z.string().optional(),
enabled: z.boolean().optional(),
example: z.string().optional(),
})
.passthrough();

export const buildTemplateSchema = (t: (key: string) => string) =>
z.object({
id: z.string().optional(),
name: z.string().min(1, t('setting.templateNameRequired')),
description: z.string().optional(),
llm_id: z.string().min(1, t('setting.llmForExtractionRequired')),
kind: z.string().min(1, t('setting.templateKindRequired')),
config: z.record(
z.union([
buildRaptorConfigSchema(t),
buildSectionSchema(t),
buildSynthesisSchema(),
z.string(),
z.boolean(),
]),
),
});

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== locate schema file =="
fd -a 'schema\.ts$' web/src/pages/user-setting/compilation-templates/edit-next 2>/dev/null || true

echo "== file contents =="
if [ -f web/src/pages/user-setting/compilation-templates/edit-next/schema.ts ]; then
  cat -n web/src/pages/user-setting/compilation-templates/edit-next/schema.ts
fi

echo "== search buildSynthesis/buildTemplate usages =="
rg -n "buildSynthesisSchema|buildTemplateSchema|buildRaptorConfigSchema|buildSectionSchema|config:" web/src || true

echo "== zod dependency/version =="
for f in package.json web/package.json pnpm-lock.yaml package-lock.json yarn.lock; do
  [ -f "$f" ] && (echo "--- $f"; rg -n '"zod"|zod@|zod:' "$f" | head -50 || true)
done

Repository: infiniflow/ragflow

Length of output: 16512


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json, subprocess
try:
    import pkg_resources
    dist = next(pkg_resources.working_set.require('zod'))
    print("installed zod version:", dist.version)
except Exception as e:
    print("zod not importable:", repr(e))

# Read-only behavioral probe: fetch zod package metadata/source, install a temp writable venv just to run parser semantics probe
# against exactly the package version dependency is not installed.
PY

python3 - <<'PY'
import tempfile, subprocess, sys, pathlib, json
mods=[]
for req in ('pip','pipx','uvx'):
    p = subprocess.run([req,'list','zod'], capture_output=True, text=True)
    print(f"{req}:", p.returncode, p.stdout.splitlines()[:5])
PY

Repository: infiniflow/ragflow

Length of output: 759


🌐 Web query:

Zod 3.23.8 z.union tries members in order first schema that succeeds z.object passthrough behavior

💡 Result:

In Zod, z.union schemas operate by checking the input against each provided schema in the order they are defined [1][2]. The union will return the result of the first schema that successfully validates the input [1][3]. Regarding z.object passthrough behavior in unions: 1. Default Stripping: By default, Zod objects are non-strict, meaning they strip any unknown keys from the output [4][5]. When a union member is a z.object, it will successfully validate input containing extra keys by stripping those keys [4][5]. Because z.union short-circuits at the first successful match, if an early union member is "loose" (non-strict) and matches your input structure, it may match and strip your data before a later, more specific schema can be evaluated [6][7]. 2. Passthrough Usage: If you use.passthrough on an object schema, that schema is explicitly configured to retain unknown keys during validation [8]. If this schema is part of a z.union, and it is the first to successfully match the input, it will return the object including the extra keys [8]. 3. Common Issues: Users often encounter unexpected behavior where a union "ignores" a later schema because an earlier, broader schema (such as one with optional fields) successfully matched the input, effectively "consuming" it [5][7]. Because the first match is returned, the data is processed according to that specific schema's rules (e.g., stripping unknown keys), which can lead to data loss if that schema was not the most appropriate or intended match [6][7]. To mitigate these issues, the recommended approaches include: - Reordering: Place more specific schemas before more general or permissive schemas [6][7]. - Strictness: Use.strict on object schemas to prevent them from accepting data with extra keys, forcing the union to keep looking if the input does not match exactly [6][4][5]. - Discriminated Unions: If the schemas share a common field, use z.discriminatedUnion [1][2]. This is more efficient and avoids order-dependency issues because the parser uses the discriminator key to immediately identify the correct schema [1][3].

Citations:


🌐 Web query:

Zod z.object optional fields parse empty object passthrough strict undefined required check

💡 Result:

In Zod, the behavior of object schemas regarding fields, optionality, and unknown keys is defined by specific configurations [1][2][3]. Optional Fields and Parsing: By default, all object properties are required [2][4]. To make a property optional, you must use.optional on the individual field (e.g., z.string.optional) [2][4]. When parsing, if an optional field is missing from the input, it is omitted from the resulting object [2][4]. Zod 4 introduces a change where default values applied inside optional fields are now correctly populated even when the field is missing or the object is parsed from an empty object [1][5]. Handling Unknown Keys: Zod object schemas handle unrecognized keys (keys not explicitly defined in the schema) in three primary ways [3]: 1. Strip (Default): Unrecognized keys are silently removed from the parsed output [2][3][4]. 2. Strict: If unknown keys are present, parsing will throw a ZodError [2][3][6]. You can achieve this using.strict on a standard object or by using z.strictObject [1][2][6]. 3. Passthrough (or Loose): Unrecognized keys are kept in the parsed output without validation [3][6]. You can use.passthrough (legacy) or z.looseObject [1][3][6]. Parsing Empty Objects: When parsing an empty object ({}) against a schema: - If the schema has only required fields and no defaults, parsing will fail [2][4]. - If the schema has only optional fields, or fields with default values, it will succeed and return an object with those defaults applied [1][5]. - Empty object schemas (z.object({})) effectively strip all input data, returning an empty object [7][8]. Best Practices: - Use z.strictObject or z.looseObject instead of the legacy.strict or.passthrough methods [1][6]. - For API gateway or input validation where extra data is a bug, prefer z.strictObject [3]. - For proxying or forwarding data, use z.looseObject [3].

Citations:


Make synthesis config strict or discriminative.

config is a z.record(z.union([raptorSchema, sectionSchema, synthesisSchema, …])). Zod evaluates union members in order and stops at the first success; buildSynthesisSchema() has only optional fields and is .passthrough(), so object-shaped raptor/section configs with missing or invalid required fields can be accepted by the synthesis branch instead of failing their intended schema. Add a strict discriminator/type field or switch this to a z.discriminatedUnion; otherwise the union becomes a catch-all object schema.

🤖 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/user-setting/compilation-templates/edit-next/schema.ts` around
lines 19 - 44, The buildSynthesisSchema branch is a catch-all for object configs
because all fields are optional and passthrough is enabled. Make synthesis
configs strictly identifiable by requiring a discriminator/type field and
rejecting unknown keys, or refactor buildTemplateSchema’s config union to use a
discriminated union with distinct required type values while preserving the
existing raptor and section validation.

Comment on lines +30 to +33
const {
navigateToCompilationTemplate,
navigateToCompilationTemplateEditNext,
} = useNavigatePage();

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

Old and new template-group flows coexist; converge before merge.

Creating a group still routes through the old flow (navigateToCompilationTemplate → /compilation-templates/create-next), while editing an existing group was switched to the new flow (navigateToCompilationTemplateEditNext → /compilation-templates/edit-next). The new "Next" button is also a literal, untranslated placeholder string sitting next to the real "Add Template Group" button. This is a dual-track migration state that leaves two overlapping entry points live for users.

As per coding guidelines, "When old and new implementations coexist, converge on one implementation path unless an external contract requires compatibility," and legacy surfaces should be removed rather than kept alongside new ones.

Also applies to: 46-49, 79-86, 99-99

🤖 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/user-setting/compilation-templates/index.tsx` around lines 30 -
33, Converge the compilation-template group flow on the new Next implementation:
update the create-group action and related handlers in the page component to use
navigateToCompilationTemplateEditNext, remove the legacy
navigateToCompilationTemplate usage and overlapping old entry point, and replace
the literal placeholder Next button with the existing translated/action path so
only one group flow remains.

Source: Coding guidelines

Comment on lines +5 to +11
export function formatKindLabel(t: TFunction, kind: string): string {
if (kind === CompilationTemplateKind.Artifacts) {
return 'Wiki';
}
if (kind === CompilationTemplateKind.KnowledgeGraph) {
return t('knowledgeDetails.structureGraph');
}

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 | 🟡 Minor | ⚡ Quick win

Keep kind labels localized across all supported locales.

KnowledgeGraph now requests knowledgeDetails.structureGraph, but web/src/locales/ja.ts does not define it. Also, Artifacts bypasses t with a hard-coded Wiki. Add the Japanese graph key and return t('knowledgeDetails.llmWiki') for artifacts.

🤖 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/utils/compilation-template-util.ts` around lines 5 - 11, Update
formatKindLabel to return t('knowledgeDetails.llmWiki') for
CompilationTemplateKind.Artifacts instead of the hard-coded Wiki label, and add
the missing knowledgeDetails.structureGraph translation key to the Japanese
locale so both supported labels remain localized.

@yingfeng
yingfeng merged commit 1cce9b6 into infiniflow:main Jul 27, 2026
3 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:L This PR changes 100-499 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants