Skip to content

Fix: The tool icon for the agent operator created from the template is not clickable. - #17794

Merged
wangq8 merged 4 commits into
infiniflow:mainfrom
cike8899:fix-search-required
Aug 4, 2026
Merged

wangq8 merged 4 commits into
infiniflow:mainfrom
cike8899:fix-search-required

Conversation

@cike8899

@cike8899 cike8899 commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Fix: The tool icon for the agent operator created from the template is not clickable.

@dosubot dosubot Bot added size:XL This PR changes 500-999 lines, ignoring generated files. 🐞 bug Something isn't working, pull request that fix bug. labels Aug 4, 2026
@cike8899 cike8899 added the ci Continue Integration label Aug 4, 2026
@cike8899
cike8899 marked this pull request as draft August 4, 2026 07:20
@cike8899
cike8899 marked this pull request as ready for review August 4, 2026 07:21
@cike8899
cike8899 requested a review from wangq8 August 4, 2026 07:21
@coderabbitai

coderabbitai Bot commented Aug 4, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The change adds stable tool identifiers and expanded graph metadata to agent templates, restructures the SEO workflow into peer components, and updates React settings, tree-selection refs, and tool-list fallback keys.

Changes

Template and workflow updates

Layer / File(s) Summary
Stable template identifiers and serialization
agent/templates/deep_research.json, agent/templates/reflective_academic_paper_generator.json, agent/templates/trip_planner.json, agent/templates/cajal_scientific_paper_agent.json, agent/templates/your_starter_dataset_chatbot.json, agent/templates/web_search_assistant.json
Templates gain stable tool or retrieval identifiers. Literal Unicode replaces escaped text in selected templates. The academic template adds Recommended to its canvas types.
Workflow graph serialization
agent/templates/market_seo_article_writer.json, agent/templates/stock_market_research_assistant.json, agent/templates/user_interaction.json
Templates expand component, node, edge, layout, and runtime metadata. Existing workflow behavior remains unchanged except that the stock research retrieval agent becomes a separate node.
SEO workflow component architecture
agent/templates/seo_article_writer.json
Nested sub-agents become peer components with explicit connections, graph metadata, documentation notes, and Chinese title and description translations.

Web UI updates

Layer / File(s) Summary
UI refs and settings rendering
web/src/components/llm-setting-items/next.tsx, web/src/components/model-tree-select.tsx, web/src/components/tree-select.tsx
LLM settings use a shared JSX block with explicit conditional collapsing. TreeSelect and ModelTreeSelect forward button refs.
UI rendering key fallbacks
web/src/pages/agent/canvas/node/tool-node.tsx, web/src/pages/agent/form/agent-form/agent-tools.tsx
Tool and MCP list keys fall back to indexes or component names when IDs are unavailable. Tool card tooltip behavior remains unchanged.

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

Sequence Diagram(s)

sequenceDiagram
  participant BeginNode
  participant LeadAgent
  participant OutlineAgent
  participant BodyAgent
  participant EditorAgent
  participant MessageOutput
  BeginNode->>LeadAgent: start workflow with user query
  LeadAgent->>OutlineAgent: request article outline
  LeadAgent->>BodyAgent: request article body
  LeadAgent->>EditorAgent: request edited article
  LeadAgent->>MessageOutput: return generated article
Loading

Suggested reviewers: wangq8

Poem

A rabbit maps each graph node twice,
Stable IDs make paths precise.
Refs now reach the buttons below,
Fallback keys keep lists in flow.
Unicode blooms in prompts anew.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% 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 clearly describes the primary fix: making the tool icon clickable for agent operators created from templates.
Description check ✅ Passed The description includes the required Summary section and clearly states the issue that this pull request fixes.
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: 11

🧹 Nitpick comments (4)
agent/templates/stock_market_research_assistant.json (1)

283-289: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Normalize the output type casing and avoid a hard failure in the script.

md_table declares type "String", while every other output in this template uses "string" (for example Line 374 and Line 989). Use the lowercase form for consistency.

The script also raises ValueError when no date header line is found, which aborts the branch instead of emitting an empty table. The bare except: in format_number hides real errors. Both apply to the duplicated script at Line 866 as well.

🤖 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 `@agent/templates/stock_market_research_assistant.json` around lines 283 - 289,
Change the md_table output type from "String" to lowercase "string" and apply
the same casing in both duplicated script definitions. Update
extract_md_table_single_column in each script to return an empty table result
instead of raising ValueError when no date header is found, and replace the bare
except in format_number with targeted numeric-conversion error handling.
web/src/pages/agent/form/agent-form/agent-tools.tsx (1)

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

Reuse one LabelCard element in ToolCard.

The tooltip and plain branches duplicate the same LabelCard props and class expression at Line [46-55] and Line [65-74]. Build the card once, then use it in TooltipTrigger or return it.

Suggested refactor
 }: ToolCardProps) {
+  const card = (
+    <LabelCard
+      {...props}
+      className={cn(
+        'flex justify-between ',
+        { 'p-2.5 text-text-primary text-sm': !isNodeTool },
+        className,
+      )}
+    >
+      {children}
+    </LabelCard>
+  );
+
   if (children === Operator.Code) {
     return (
       <Tooltip>
         <TooltipTrigger asChild>
-          <LabelCard>
-            ...
-          </LabelCard>
+          {card}
         </TooltipTrigger>
       </Tooltip>
     );
   }
 
-  return <LabelCard>...</LabelCard>;
+  return card;
 }

As per coding guidelines: web/src/**/*.{tsx,jsx} says, “Avoid duplicating component structures in JSX; prefer 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/agent/form/agent-form/agent-tools.tsx` around lines 42 - 75,
Refactor ToolCard to construct the shared LabelCard element once, preserving its
existing props, className expression, and children. Return that element directly
for non-Code operators, and wrap the same element in Tooltip and TooltipTrigger
for Operator.Code instead of duplicating the JSX structure.

Source: Coding guidelines

web/src/components/tree-select.tsx (1)

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

Use theme color tokens for muted controls.

text-slate-400 and placeholder:text-slate-400 bypass the project token set. Use the matching semantic token for the selected-value placeholder, search icon, input placeholder, and empty state.

Proposed token replacement
-            <span className={cn('truncate', !selectedNode && 'text-slate-400')}>
+            <span className={cn('truncate', !selectedNode && 'text-text-secondary')}>
...
-              <Search className="h-4 w-4 text-slate-400 mr-2 flex-shrink-0" />
+              <Search className="h-4 w-4 text-text-secondary mr-2 flex-shrink-0" />
...
-                className="flex-1 bg-transparent text-sm outline-none placeholder:text-slate-400"
+                className="flex-1 bg-transparent text-sm outline-none placeholder:text-text-secondary"
...
-              <div className="py-6 text-center text-sm text-slate-400">
+              <div className="py-6 text-center text-sm text-text-secondary">

Verify that the selected token has the intended contrast in supported themes. As per coding guidelines, use project-defined color tokens and do not use Tailwind default palette colors directly.

Also applies to: 251-254, 268-268

🤖 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/tree-select.tsx` at line 225, Replace the hard-coded
text-slate-400 and placeholder:text-slate-400 classes in the tree-select
selected-value placeholder, search icon, input placeholder, and empty-state
elements with the project’s matching semantic muted color token, preserving the
existing conditional styling and verifying appropriate contrast across supported
themes.

Source: Coding guidelines

web/src/components/llm-setting-items/next.tsx (1)

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

Extract the inline setting handlers.

settingFields contains inline onValueChange and slider onChange callbacks. Define handleParameterValueChange in the parameter field render function. Pass checkParameterIsEqual directly to each SliderInputSwitchFormField.

Proposed slider handler update
-          onChange={() => {
-            checkParameterIsEqual();
-          }}
+          onChange={checkParameterIsEqual}

Verify that handleParameterValueChange preserves the handleChange(value) then field.onChange(value) order. As per coding guidelines, avoid inline JSX event handlers and reference named handlers by name.

Also applies to: 185-188, 198-201, 211-214, 224-227, 237-240

🤖 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/llm-setting-items/next.tsx` around lines 156 - 159, In the
parameter field render function, extract the inline value-change callback into a
named handleParameterValueChange that calls handleChange(value) before
field.onChange(value), then pass that handler by name to the relevant setting
fields. For each SliderInputSwitchFormField, replace the inline slider onChange
callback with a direct checkParameterIsEqual reference, including all listed
occurrences.

Source: Coding guidelines

🤖 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 `@agent/templates/cajal_scientific_paper_agent.json`:
- Around line 60-84: Add a `Tool:Retrieval:NewPumasLick` node to the `dsl.graph`
for `Agent:NewPumasLick`, and add the corresponding agent-to-tool edge using
`sourceHandle` set to `tool` with the matching `...tool-Tool:...end` connection
format used by neighboring templates. Keep the existing `form.tools` Retrieval
declaration unchanged.

In `@agent/templates/market_seo_article_writer.json`:
- Line 623: Synchronize the Body_Agent prompt and its matching workflow notes so
they define one consistent output contract: resolve the conflicting per-section
word counts between the prompt near sys_prompt, the note around line 873, and
the output requirements around line 900, and make the outline/request near line
737 ask for Meta Title and Meta Description only if those outputs remain
required. Update all corresponding documentation together and remove stale
superseded wording.
- Around line 8-11: Update the German description in the description.en/de/zh
object so it begins with “Der SEO-Blog-Magnetiseur erstellt automatisch” and
forms a complete, grammatically correct sentence while preserving the original
meaning and remaining localized text.
- Around line 88-89: Update the nested tool entry IDs and corresponding graph
node/edge targets throughout the template so they use the same Tool.*
identifiers, including the SharpPensBurn and WickedDeerHeal targets and
flow.tool_0/flow.tool_1 references. Apply this consistently at the referenced
locations, preserving the canvas tool.id lookup contract.

In `@agent/templates/seo_article_writer.json`:
- Around line 95-125: Update the tool ids in the components definitions for the
Outline Agent and Body Agent so each matches its corresponding
graph.nodes[].data.form id: use the graph ids associated with those agents,
including TavilySearch:SlickSpidersTurn and TavilySearch:IcyPawsRescue. Ensure
the components copy has no duplicate TavilySearch ids and remains identical to
the graph copy.
- Around line 771-878: Update the workflow Note, Body Agent sys_prompt, and
Editor Agent Note to consistently use Lead Agent, Outline Agent, Body Agent, and
Editor Agent instead of the stale *_Agent names. Change the Body Agent Note’s
section length from 150–220 words to 500–600 words so it matches the Lead Agent
prompt and Body Agent output format. Remove all remaining stale agent-name
references in these notes and prompts.

In `@agent/templates/stock_market_research_assistant.json`:
- Around line 116-121: The stock market research template embeds
deployment-specific mcp_id and kb_ids values in the MCP configuration and
repeated graph node forms. Remove these hardcoded resource IDs so deployments
can supply their own values, or update the existing SadWallsSniff note to
explicitly cover both MCP and knowledge-base references if retaining
placeholders.
- Around line 1119-1139: Update the workflow around Tool:ClearKiwisRoll and
Agent:SadDodosRescue so the agent no longer has an unwired tool node: either
remove Tool:ClearKiwisRoll together with its connecting edge, or add the
intended real tool entry to Agent:SadDodosRescue’s form.tools array and preserve
the connection.
- Around line 359-379: Update both YahooFinance
configurations—“YahooFinance:QuickAdsDig” and the corresponding graph node
form—to set params.stock_code to the extracted ticker from
Agent:ManyToesBrush@content instead of sys.query, preserving the existing
routing through Switch:FluffyCoinsSell and downstream CodeExec:LightSheepTrade.
- Around line 178-204: Update the nested Retrieval tool definition under
Agent:MightyIdeasGlow so its id matches the graph node identifier
Retrieval:MightyIdeasGlow instead of Retrieval:SadDodosRescue. Keep the tool
configuration and ownership unchanged while aligning the component id with its
owning agent.

In `@web/src/pages/agent/form/agent-form/agent-tools.tsx`:
- Around line 141-156: Update the ActionButton wiring in the tools.map render to
pass the same identity used by record: use id when available and component_name
as the fallback for deleteNodeTool. Ensure deleteNodeTool filters against that
identity so tools without IDs are not all deleted.

---

Nitpick comments:
In `@agent/templates/stock_market_research_assistant.json`:
- Around line 283-289: Change the md_table output type from "String" to
lowercase "string" and apply the same casing in both duplicated script
definitions. Update extract_md_table_single_column in each script to return an
empty table result instead of raising ValueError when no date header is found,
and replace the bare except in format_number with targeted numeric-conversion
error handling.

In `@web/src/components/llm-setting-items/next.tsx`:
- Around line 156-159: In the parameter field render function, extract the
inline value-change callback into a named handleParameterValueChange that calls
handleChange(value) before field.onChange(value), then pass that handler by name
to the relevant setting fields. For each SliderInputSwitchFormField, replace the
inline slider onChange callback with a direct checkParameterIsEqual reference,
including all listed occurrences.

In `@web/src/components/tree-select.tsx`:
- Line 225: Replace the hard-coded text-slate-400 and placeholder:text-slate-400
classes in the tree-select selected-value placeholder, search icon, input
placeholder, and empty-state elements with the project’s matching semantic muted
color token, preserving the existing conditional styling and verifying
appropriate contrast across supported themes.

In `@web/src/pages/agent/form/agent-form/agent-tools.tsx`:
- Around line 42-75: Refactor ToolCard to construct the shared LabelCard element
once, preserving its existing props, className expression, and children. Return
that element directly for non-Code operators, and wrap the same element in
Tooltip and TooltipTrigger for Operator.Code instead of duplicating the JSX
structure.
🪄 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: f484a97e-8780-4a9f-8f65-47e6430f57ec

📥 Commits

Reviewing files that changed from the base of the PR and between 912a728 and 07791b6.

📒 Files selected for processing (15)
  • agent/templates/cajal_scientific_paper_agent.json
  • agent/templates/deep_research.json
  • agent/templates/market_seo_article_writer.json
  • agent/templates/reflective_academic_paper_generator.json
  • agent/templates/seo_article_writer.json
  • agent/templates/stock_market_research_assistant.json
  • agent/templates/trip_planner.json
  • agent/templates/user_interaction.json
  • agent/templates/web_search_assistant.json
  • agent/templates/your_starter_dataset_chatbot.json
  • web/src/components/llm-setting-items/next.tsx
  • web/src/components/model-tree-select.tsx
  • web/src/components/tree-select.tsx
  • web/src/pages/agent/canvas/node/tool-node.tsx
  • web/src/pages/agent/form/agent-form/agent-tools.tsx

Comment on lines +60 to +84
"tools": [
{
"component_name": "Retrieval",
"name": "Retrieval",
"params": {
"cross_languages": [],
"description": "Retrieve papers, reports, datasets, and notes that ground CAJAL scientific writing outputs.",
"empty_response": "",
"kb_ids": [],
"keywords_similarity_weight": 0.7,
"outputs": {
"formalized_content": {
"type": "string",
"value": ""
}
},
"rerank_id": "",
"similarity_threshold": 0.2,
"top_k": 1024,
"top_n": 10,
"use_kg": false
},
"id": "Retrieval:NewPumasLick"
}
],

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check which templates declare agent tools but no toolNode/tool edge in the graph.
fd -e json . agent/templates --exec python3 -c '
import json,sys
p=sys.argv[1]
d=json.load(open(p))
g=d.get("dsl",{}).get("graph",{})
nodes=g.get("nodes",[]) or []
edges=g.get("edges",[]) or []
tool_nodes=[n.get("id") for n in nodes if n.get("type")=="toolNode"]
tool_edges=[e.get("id") for e in edges if e.get("sourceHandle")=="tool"]
has_tools=False
for n in nodes:
    f=(n.get("data") or {}).get("form") or {}
    if f.get("tools"):
        has_tools=True
if has_tools and not (tool_nodes and tool_edges):
    print(p, "tool_nodes:", tool_nodes, "tool_edges:", tool_edges)
' {}

Repository: infiniflow/ragflow

Length of output: 2416


🏁 Script executed:

#!/bin/bash
set -u
echo "Template candidates:"
fd -e json 'cajal_scientific_paper_agent|reflective_academic_paper_generator|your_starter_dataset_chatbot' agent/templates || true
echo
python3 - <<'PY'
import json
import pathlib

for path in pathlib.Path("agent/templates").glob("*.json"):
    text = path.read_text()
    if any(s in text for s in ["Retrieval:NewPumasLick", "Agent:NewPumasLick"]):
        data=json.loads(text)
        g=data.get("dsl",{}).get("graph",{})
        nodes=g.get("nodes",[]) or []
        edges=g.get("edges",[]) or []
        tool_nodes=[n.get("id") for n in nodes if n.get("type")=="toolNode"]
        tool_edges=[e.get("id") for e in edges if e.get("sourceHandle")=="tool"]
        has_tools=[]
        for n in nodes:
            f=(n.get("data") or {}).get("form") or {}
            if f.get("tools"):
                has_tools.append((n.get("id"), len(f.get("tools"))))
        print(f"{path}: tool_nodes={tool_nodes}, tool_edges={tool_edges}, nodes_with_tools={has_tools}")
PY

Repository: infiniflow/ragflow

Length of output: 969


🏁 Script executed:

#!/bin/bash
set -u
python3 - <<'PY'
import json
import pathlib
# Search runtime/canvas behavior for tool node rendering or edge sourceHandle.
patterns = ["toolNode", "sourceHandle", "handle-Tool", "Tool:]"]
files = []
for root in ["."]:
    for p in pathlib.Path(root).rglob("*"):
        if not p.is_file():
            continue
        s=str(p)
        if any(part.startswith(".") for part in p.parts):
            continue
        if any(part in {"node_modules","dist","build",".git"} for part in p.parts):
            continue
        ext = p.suffix.lower()
        if ext in {".json",".js",".jsx",".ts",".tsx",".css",".styl",".vue",".html",".md"}:
            files.append(p)
for p in files:
    try:
        txt=p.read_text(errors="ignore")
    except Exception:
        continue
    if any(tok in txt for tok in patterns):
        print(p)
        for line in txt.splitlines()[:20]:
            if any(tok in line for tok in patterns):
                print("  ", line[:200])
PY

Repository: infiniflow/ragflow

Length of output: 3251


🏁 Script executed:

#!/bin/bash
set -u
echo "Agent canvas files outlines:"
for f in web/src/pages/agent/canvas/index.tsx web/src/pages/agent/canvas/node/tool-node.tsx web/src/pages/agent/canvas/edge/index.tsx web/src/pages/agent/form/agent-form/agent-tools.tsx; do
  echo "--- $f ($(wc -l < "$f") lines) ---"
  ast-grep outline "$f" --view compact || true
done
echo
echo "Relevant searches:"
rg -n 'toolNode|tool-Tool:|xy-edge__.*tool|sourceHandle.*tool|agent-tools|tools|Form' web/src/pages/agent -g '*.tsx' -g '*.ts'

Repository: infiniflow/ragflow

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -u
echo "Selected canvas snippets:"
for f in web/src/pages/agent/canvas/index.tsx web/src/pages/agent/canvas/node/tool-node.tsx web/src/pages/agent/canvas/edge/index.tsx; do
  echo "--- $f $(wc -l < $f) lines ---"
  rg -n 'toolNode|nodes|edges|ReactFlow|id=|nodeTypes|connectionMode|sourceHandle|handle-' "$f" || true
done
echo
echo "Agent tool form snippets:"
for f in web/src/pages/agent/form/agent-form/agent-tools.tsx web/src/pages/agent/store.ts web/src/pages/agent/utils.ts web/src/pages/agent/constant/index.tsx; do
  echo "--- $f $(wc -l < $f) lines ---"
  rg -n 'tools|toolNode|tool|sourceHandle|targetHandle|handle-Tool|generate' "$f" || true
done

Repository: infiniflow/ragflow

Length of output: 6820


Add the missing Tool: node and matching edge.

Agent:NewPumasLick declares Retrieval:NewPumasLick in form.tools, but dsl.graph has no toolNode for it and no sourceHandle of tool. Match the other agent templates by adding a Tool: node and a ...tool-Tool:...end edge so the canvas creates a clickable tool handle for this agent.

🤖 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 `@agent/templates/cajal_scientific_paper_agent.json` around lines 60 - 84, Add
a `Tool:Retrieval:NewPumasLick` node to the `dsl.graph` for
`Agent:NewPumasLick`, and add the corresponding agent-to-tool edge using
`sourceHandle` set to `tool` with the matching `...tool-Tool:...end` connection
format used by neighboring templates. Keep the existing `form.tools` Retrieval
declaration unchanged.

Comment on lines 8 to +11
"description": {
"en": "This SEO article writer automatically generates a complete SEO-optimized blog article based on a simple user input. You don't need any writing experience. Just provide a topic or short request — the system will handle the rest.",
"de": "SEO-Blog-Magnetiseur automatisch einen vollständigen SEO-optimierten Blogartikel basierend auf einer einfachen Benutzereingabe. Sie benötigen keine Schreiberfahrung. Geben Sie einfach ein Thema oder eine kurze Anfrage ein – das System übernimmt den Rest.",
"zh": "此 SEO 博客写手根据简单的用户输入自动生成完整的SEO博客文章。你无需任何写作经验,只需提供一个主题或简短请求,系统将处理其余部分。"},
"zh": "此 SEO 博客写手根据简单的用户输入自动生成完整的SEO博客文章。你无需任何写作经验,只需提供一个主题或简短请求,系统将处理其余部分。"

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

Fix the German description.

Line 10 omits the verb after SEO-Blog-Magnetiseur. German users see an incomplete sentence. Use Der SEO-Blog-Magnetiseur erstellt automatisch ....

🤖 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 `@agent/templates/market_seo_article_writer.json` around lines 8 - 11, Update
the German description in the description.en/de/zh object so it begins with “Der
SEO-Blog-Magnetiseur erstellt automatisch” and forms a complete, grammatically
correct sentence while preserving the original meaning and remaining localized
text.

Comment on lines +88 to +89
"id": "TavilySearch:BetterSitesSend"
}

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:

#!/usr/bin/env bash
set -euo pipefail

template='agent/templates/market_seo_article_writer.json'
python3 -m json.tool "$template" >/dev/null

python3 - "$template" <<'PY'
import json
import sys

template = json.load(open(sys.argv[1], encoding="utf-8"))
dsl = template["dsl"]
components = dsl["components"]
nodes = {node["id"]: node for node in dsl["graph"]["nodes"]}
edges = dsl["graph"]["edges"]

for agent_id, component in components.items():
    tools = component.get("obj", {}).get("params", {}).get("tools", [])
    if not tools:
        continue

    tool_edges = [
        edge for edge in edges
        if edge["source"] == agent_id and edge.get("sourceHandle") == "tool"
    ]
    print(f"\n{agent_id}")
    for tool in tools:
        tool_id = tool.get("id")
        direct_matches = [
            node_id for node_id, node in nodes.items()
            if tool_id in {node_id, node.get("data", {}).get("name")}
        ]
        print(f"  tool={tool_id!r}, direct_node_matches={direct_matches}")
    for edge in tool_edges:
        target = nodes[edge["target"]]
        print(
            f"  edge_target={edge['target']!r}, "
            f"node_name={target.get('data', {}).get('name')!r}"
        )
PY

for file in \
  web/src/pages/agent/canvas/node/tool-node.tsx \
  web/src/pages/agent/form/agent-form/agent-tools.tsx
do
  [ -f "$file" ] || continue
  ast-grep outline "$file" --items all
  rg -n -C 6 'tool_id|component_name|flow\.tool_|sourceHandle|targetHandle|onClick' "$file" || true
done

Repository: infiniflow/ragflow

Length of output: 5928


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Repository files matching tool-node / constants / agent tools:"
git ls-files | rg 'tool-node\.tsx$|Constants|constant\.ts$|agent-tools\.tsx$|graph.*tool|ToolNode|NodeHandleId' || true

echo
echo "Find relevant symbols in candidate files:"
rg -n -C 8 'selected.*Tool|clickedToolId|tool\.id|component_name|handleClick|findNode|sourceHandle|targetHandle|tool-id|tool_id|NodeHandleId|Operator\.Tool|Tool' \
  web/src/pages/agent \
  web/src/components \
  web/src/interfaces/database/agent.ts 2>/dev/null | head -n 220

Repository: infiniflow/ragflow

Length of output: 14802


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

echo "Search all source usages for clicked/clicked tool state and tool selection by id:"
rg -n -C 5 'clickedToolId|setClickedToolId|selectedToolId|setSelectedToolId|tool-id|data-tool-id|tool\.id|component_name|NodeHandleId\.Tool|sourceHandle.*tool|targetHandle.*tool' web/src/pages/agent web/src/interfaces/database/agent.ts

echo
echo "Inspect relevant parts of web/src/pages/agent/canvas/node/tool-node.tsx:"
wc -l web/src/pages/agent/canvas/node/tool-node.tsx
cat -n web/src/pages/agent/canvas/node/tool-node.tsx | sed -n '1,140p'

echo
echo "Inspect relevant constants:"
fd -a 'constant\.ts$' web/src/pages/agent | head -n 20
while IFS= read -r f; do
  rg -n -C 3 'NodeHandleId|Tool|tool' "$f" || true
done < <(fd 'constant\.ts$' web/src/pages/agent)

Repository: infiniflow/ragflow

Length of output: 50374


Keep the nested tool ID in sync with the graph target.

The nested tool records use TavilySearch:* IDs, while the downstream graph edges point to Tool:*SharpPensBurn, Tool:*WickedDeerHeal, and node names like flow.tool_0 / flow.tool_1. The canvas form resolves the selected tool by storing tool.id, so this template will not link the configured tool IDs to the graph targets. Use matching IDs for the nested tool entries and the Tool.* graph nodes. Also applies to lines 220-221, 346-350, 363-367, 566-588, and 680-702.

🤖 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 `@agent/templates/market_seo_article_writer.json` around lines 88 - 89, Update
the nested tool entry IDs and corresponding graph node/edge targets throughout
the template so they use the same Tool.* identifiers, including the
SharpPensBurn and WickedDeerHeal targets and flow.tool_0/flow.tool_1 references.
Apply this consistently at the referenced locations, preserving the canvas
tool.id lookup contract.

@@ -180,7 +620,7 @@
"role": "user"
}
],
"sys_prompt": "# Role\n\nYou are the **Body_Agent**, responsible for generating the full content of each section of an SEO-optimized blog based on the provided outline and keyword strategy.\n\n# Tool Access:\n\nYou can use the `Tavily Search` tool to retrieve relevant content, statistics, or examples to support each section you're writing.\n\nUse it **only** when the provided outline lacks enough information, or if the section requires factual grounding.\n\nAlways cite the original link or indicate source where possible.\n\n\n# Goals\n\n1. Write each section (based on H2/H3 structure) as a complete and natural blog paragraph.\n\n2. Integrate the suggested long-tail keywords naturally into each section.\n\n3. When appropriate, use the `Tavily Search` tool to enrich your writing with relevant facts, examples, or quotes.\n\n4. Ensure each section is clear, engaging, and informative, suitable for both human readers and search engines.\n\n\n# Style Guidelines\n\n- Write in a tone appropriate to the audience. Be explanatory, not promotional, unless it's a marketing blog.\n\n- Avoid generic filler content. Prioritize clarity, structure, and value.\n\n- Ensure SEO keywords are embedded seamlessly, not forcefully.\n\n\n\n- Maintain writing rhythm. Vary sentence lengths. Use transitions between ideas.\n\n\n# Input\n\n\nYou will receive:\n\n- Blog title\n\n- Structured outline (including section titles, keywords, and descriptions)\n\n- Target audience\n\n- Blog type and user intent\n\nYou must **follow the outline strictly**. Write content **section-by-section**, based on the structure.\n\n\n# Output Format\n\n```markdown\n\n## H2: [Section Title]\n\n[Your generated content for this section \u2014 500-600 words, using keywords naturally.]\n\n",
"sys_prompt": "# Role\n\nYou are the **Body_Agent**, responsible for generating the full content of each section of an SEO-optimized blog based on the provided outline and keyword strategy.\n\n# Tool Access:\n\nYou can use the `Tavily Search` tool to retrieve relevant content, statistics, or examples to support each section you're writing.\n\nUse it **only** when the provided outline lacks enough information, or if the section requires factual grounding.\n\nAlways cite the original link or indicate source where possible.\n\n\n# Goals\n\n1. Write each section (based on H2/H3 structure) as a complete and natural blog paragraph.\n\n2. Integrate the suggested long-tail keywords naturally into each section.\n\n3. When appropriate, use the `Tavily Search` tool to enrich your writing with relevant facts, examples, or quotes.\n\n4. Ensure each section is clear, engaging, and informative, suitable for both human readers and search engines.\n\n\n# Style Guidelines\n\n- Write in a tone appropriate to the audience. Be explanatory, not promotional, unless it's a marketing blog.\n\n- Avoid generic filler content. Prioritize clarity, structure, and value.\n\n- Ensure SEO keywords are embedded seamlessly, not forcefully.\n\n\n\n- Maintain writing rhythm. Vary sentence lengths. Use transitions between ideas.\n\n\n# Input\n\n\nYou will receive:\n\n- Blog title\n\n- Structured outline (including section titles, keywords, and descriptions)\n\n- Target audience\n\n- Blog type and user intent\n\nYou must **follow the outline strictly**. Write content **section-by-section**, based on the structure.\n\n\n# Output Format\n\n```markdown\n\n## H2: [Section Title]\n\n[Your generated content for this section — 500-600 words, using keywords naturally.]\n\n",

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

Synchronize the workflow notes and prompt contracts.

Line 623 requires 500-600 words per section, but Line 873 promises 150–220. Line 900 promises a Meta Title and Meta Description, but Line 737 does not request either output. Choose the intended output contract. Then update each prompt and its matching note together.

As per coding guidelines, remove stale superseded comments and documentation.

Also applies to: 737-737, 873-873, 900-900

🤖 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 `@agent/templates/market_seo_article_writer.json` at line 623, Synchronize the
Body_Agent prompt and its matching workflow notes so they define one consistent
output contract: resolve the conflicting per-section word counts between the
prompt near sys_prompt, the note around line 873, and the output requirements
around line 900, and make the outline/request near line 737 ask for Meta Title
and Meta Description only if those outputs remain required. Update all
corresponding documentation together and remove stale superseded wording.

Source: Coding guidelines

Comment on lines +95 to +125
"tools": [
{
"component_name": "TavilySearch",
"name": "TavilySearch",
"params": {
"api_key": "",
"days": 7,
"exclude_domains": [],
"include_answer": false,
"include_domains": [],
"include_image_descriptions": false,
"include_images": false,
"include_raw_content": true,
"max_results": 5,
"outputs": {
"formalized_content": {
"type": "string",
"value": ""
},
"json": {
"type": "Array<Object>",
"value": []
}
},
"query": "sys.query",
"search_depth": "basic",
"topic": "general"
},
"id": "TavilySearch:LuckyApplesGrab"
}
],

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

Fix the duplicated TavilySearch tool id in components.

Line 123 assigns TavilySearch:LuckyApplesGrab to the Outline Agent's tool. Line 198 assigns the same string to the Body Agent's tool. Two different sub-agents now share one tool identifier, which defeats the stable-id fix this PR introduces.

The ids also disagree with the graph copy of the same forms. Line 547 uses TavilySearch:SlickSpidersTurn and line 637 uses TavilySearch:IcyPawsRescue. Every other template in this PR keeps the components copy and the graph.nodes[].data.form copy identical. normalize_chunker_dsl in agent/dsl_migration.py rewrites both copies from a single component_id_map, so divergent copies are not safe to assume interchangeable.

Align the components ids with the graph ids.

🐛 Proposed fix for the duplicated tool ids

Outline Agent tool (line 123):

-                                            "id": "TavilySearch:LuckyApplesGrab"
+                                            "id": "TavilySearch:SlickSpidersTurn"

Body Agent tool (line 198):

-                                            "id": "TavilySearch:LuckyApplesGrab"
+                                            "id": "TavilySearch:IcyPawsRescue"

Run the following script to check every template for duplicate tool ids and for components/graph id divergence:

#!/bin/bash
# Report duplicate tool ids and components-vs-graph tool id mismatches per template.
fd -e json . agent/templates --exec python3 -c '
import json,sys
p=sys.argv[1]
d=json.load(open(p))
dsl=d.get("dsl",{}) or {}

def walk(params, out):
    for t in (params.get("tools") or []):
        if isinstance(t, dict):
            out.append((t.get("component_name"), t.get("id")))
            walk(t.get("params") or {}, out)

comp=[]
for cid, c in (dsl.get("components") or {}).items():
    walk(((c.get("obj") or {}).get("params") or {}), comp)

graph=[]
for n in ((dsl.get("graph") or {}).get("nodes") or []):
    walk(((n.get("data") or {}).get("form") or {}), graph)

ids=[i for _, i in comp if i]
dup=sorted({i for i in ids if ids.count(i) > 1})
if dup: print(p, "DUPLICATE_TOOL_IDS:", dup)
if sorted(comp) != sorted(graph):
    print(p, "COMPONENTS_VS_GRAPH_MISMATCH")
    print("   components:", sorted(comp))
    print("   graph     :", sorted(graph))
' {}

Also applies to: 170-200

🤖 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 `@agent/templates/seo_article_writer.json` around lines 95 - 125, Update the
tool ids in the components definitions for the Outline Agent and Body Agent so
each matches its corresponding graph.nodes[].data.form id: use the graph ids
associated with those agents, including TavilySearch:SlickSpidersTurn and
TavilySearch:IcyPawsRescue. Ensure the components copy has no duplicate
TavilySearch ids and remains identical to the graph copy.

Comment on lines +116 to +121
"mcp": [
{
"mcp_id": "30d6ef8ea8d511f0828382e3548809fa",
"tools": {}
}
],

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

Deployment-specific mcp_id and kb_ids are shipped in the template.

mcp_id 30d6ef8ea8d511f0828382e3548809fa and kb_ids 60c53ed89acc11f0bc1e7a2a6d0b2755 refer to resources of one deployment. The same values repeat in the graph node forms at Line 807 and Line 1013. In any other deployment both references fail to resolve, so the information-extraction branch returns nothing. Note:SadWallsSniff warns about the MCP server only. Clear these ids in the template, or extend the note to cover the knowledge base as well.

Also applies to: 186-188

🤖 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 `@agent/templates/stock_market_research_assistant.json` around lines 116 - 121,
The stock market research template embeds deployment-specific mcp_id and kb_ids
values in the MCP configuration and repeated graph node forms. Remove these
hardcoded resource IDs so deployments can supply their own values, or update the
existing SadWallsSniff note to explicitly cover both MCP and knowledge-base
references if retaining placeholders.

Comment on lines +178 to +204
"tools": [
{
"component_name": "Retrieval",
"name": "Retrieval",
"params": {
"cross_languages": [],
"description": "A knowledge base of research reports on stock analysis by senior experts",
"empty_response": "",
"kb_ids": [
"60c53ed89acc11f0bc1e7a2a6d0b2755"
],
"keywords_similarity_weight": 0.7,
"outputs": {
"formalized_content": {
"type": "string",
"value": ""
}
},
"rerank_id": "",
"similarity_threshold": 0.2,
"top_k": 1024,
"top_n": 8,
"use_kg": false
},
"id": "Retrieval:SadDodosRescue"
}
],

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
# Description: Compare tool ids in dsl.components against dsl.graph.nodes[].data.form.tools for each template.
set -euo pipefail

fd -e json . agent/templates | while IFS= read -r f; do
  python - "$f" <<'PY'
import json, sys
path = sys.argv[1]
with open(path) as fh:
    doc = json.load(fh)
dsl = doc.get("dsl") or {}

def walk_tools(obj, out):
    if isinstance(obj, dict):
        tools = obj.get("tools")
        if isinstance(tools, list):
            for t in tools:
                if isinstance(t, dict) and "id" in t:
                    out.append((t.get("component_name"), t.get("name"), t["id"]))
        for v in obj.values():
            walk_tools(v, out)
    elif isinstance(obj, list):
        for v in obj:
            walk_tools(v, out)

comp, graph = [], []
walk_tools(dsl.get("components"), comp)
walk_tools((dsl.get("graph") or {}).get("nodes"), graph)
if sorted(comp) != sorted(graph):
    print(f"MISMATCH {path}")
    print("  components:", sorted(comp))
    print("  graph     :", sorted(graph))
PY
done

Repository: infiniflow/ragflow

Length of output: 1579


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Inspect relevant sections of stock_market_research_assistant.json:"
python3 - <<'PY'
import json
from pathlib import Path

path = Path("agent/templates/stock_market_research_assistant.json")
doc = json.loads(path.read_text())
dsl = doc.get("dsl") or {}

def find_tools_by_component(components, component_name):
    out = []
    if components:
        for comp in components:
            tools = comp.get("tools") or []
            owner = comp.get("component_name")
            if owner == component_name:
                out.append([{**tool, "owner_component_name": owner} for tool in tools])
    return out

print("components list count:", len(dsl.get("components") or []))
for i, comp in enumerate(dsl.get("components") or []):
    if comp.get("component_name") in {"Agent:MightyIdeasGlow", "Agent:SadDodosRescue"} or any(t.get("id") in {"Retrieval:SadDodosRescue"} for t in (comp.get("tools") or [])):
        print(f"\ncomponent[{i}] title={comp.get('component_name')} type={comp.get('object') or comp.get('type')} id={comp.get('id')}")
        for j, tool in enumerate(comp.get("tools") or []):
            print(f"  tool[{j}] id={tool.get('id')} name={tool.get('name')} component_name={tool.get('component_name')}")

for i, node in enumerate((dsl.get("graph") or {}).get("nodes") or []):
    node_id = node.get("id")
    data = node.get("data") or {}
    form = data.get("form") or {}
    tools = form.get("tools") or []
    if "MightyIdeasGlow" in node_id or "SadDodosRescue" in node_id or any(t.get("id") == "Retrieval:SadDodosRescue" for t in tools):
        print(f"\nnode[{i}] id={node_id}")
        for j, tool in enumerate(tools):
            print(f"  form.tool[{j}] id={tool.get('id')} name={tool.get('name')} component_name={tool.get('component_name')}")
PY

Repository: infiniflow/ragflow

Length of output: 374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Check DSL shape and file size:"
python3 - <<'PY'
import json
from pathlib import Path

path = Path("agent/templates/stock_market_research_assistant.json")
doc = json.loads(path.read_text())
dsl = doc.get("dsl") or {}
print("dsl type:", type(dsl).__name__)
if isinstance(dsl, dict):
    print("dsl keys:", ", ".join(sorted(dsl.keys())))
    print("components type:", type(dsl.get("components")).__name__)
elif isinstance(dsl, list):
    print("dsl first keys:", ", ".join(sorted(set(tuple(x.get("key") for x in (obj.get("value") or []) if isinstance(obj, dict) and isinstance(obj.get("value"), dict)) for obj in dsl))) if len(dsl) else "none")
PY

echo
echo "Print raw lines 10-225 and 990-1045:"
sed -n '10,225p' agent/templates/stock_market_research_assistant.json | nl -ba
echo
echo "-------------------------------"
echo "-------------------------------"
sed -n '990,1045p' agent/templates/stock_market_research_assistant.json | nl -ba

Repository: infiniflow/ragflow

Length of output: 376


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json
from pathlib import Path

path = Path("agent/templates/stock_market_research_assistant.json")
doc = json.loads(path.read_text().replace("\r\n", "\n"))
dsl = doc.get("dsl") or {}

print("dsl.components type:", type(dsl["components"]).__name__)
print("dsl.graph type:", type(dsl.get("graph")).__name__)
print("dsl.graph.id:", dsl.get("graph", {}).get("id"))

for key, value in dsl["components"].items():
    if key in {"Agent:MightyIdeasGlow", "Agent:SadDodosRescue"} or not value:
        continue
    print(f"\nkey={key}")
    print("value=", json.dumps(value, indent=2)[:4000] if isinstance(value, (dict, list)) else value)

print("\n--- graph nodes with Relevant ids ---")
for node in (dsl.get("graph") or {}).get("nodes") or []:
    node_id = node.get("id")
    data = node.get("data") or {}
    form = data.get("form") or {}
    tools = form.get("tools") or []
    if "MightyIdeasGlow" in node_id or "SadDodosRescue" in node_id:
        print(f"\nnode_id={node_id}")
        print("component_name=", [tools[i]["component_name"] if isinstance(tool, dict) else None for i, tool in enumerate(tools)])
        print("ids=", [tool["id"] if isinstance(tool, dict) else None for tool in tools])
PY

echo
echo "Use awk for line numbers; raw line ranges:"
awk 'NR>=178 && NR<=205 {printf "%6d  %s\n", NR, $0}' agent/templates/stock_market_research_assistant.json
echo
awk 'NR>=1018 && NR<=1035 {printf "%6d  %s\n", NR, $0}' agent/templates/stock_market_research_assistant.json

Repository: infiniflow/ragflow

Length of output: 16647


Align the nested Retrieval tool id with Agent:MightyIdeasGlow.

Retrieval is attached to Agent:MightyIdeasGlow, but dsl.components["Agent:MightyIdeasGlow"].obj.params.tools uses id Retrieval:SadDodosRescue while the graph node form uses Retrieval:MightyIdeasGlow. Match the component id to the owning agent so tool ids stay stable and consistent.

🔧 Proposed fix
-                                            "id": "Retrieval:SadDodosRescue"
+                                            "id": "Retrieval:MightyIdeasGlow"
📝 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
"tools": [
{
"component_name": "Retrieval",
"name": "Retrieval",
"params": {
"cross_languages": [],
"description": "A knowledge base of research reports on stock analysis by senior experts",
"empty_response": "",
"kb_ids": [
"60c53ed89acc11f0bc1e7a2a6d0b2755"
],
"keywords_similarity_weight": 0.7,
"outputs": {
"formalized_content": {
"type": "string",
"value": ""
}
},
"rerank_id": "",
"similarity_threshold": 0.2,
"top_k": 1024,
"top_n": 8,
"use_kg": false
},
"id": "Retrieval:SadDodosRescue"
}
],
"tools": [
{
"component_name": "Retrieval",
"name": "Retrieval",
"params": {
"cross_languages": [],
"description": "A knowledge base of research reports on stock analysis by senior experts",
"empty_response": "",
"kb_ids": [
"60c53ed89acc11f0bc1e7a2a6d0b2755"
],
"keywords_similarity_weight": 0.7,
"outputs": {
"formalized_content": {
"type": "string",
"value": ""
}
},
"rerank_id": "",
"similarity_threshold": 0.2,
"top_k": 1024,
"top_n": 8,
"use_kg": false
},
"id": "Retrieval:MightyIdeasGlow"
}
],
🤖 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 `@agent/templates/stock_market_research_assistant.json` around lines 178 - 204,
Update the nested Retrieval tool definition under Agent:MightyIdeasGlow so its
id matches the graph node identifier Retrieval:MightyIdeasGlow instead of
Retrieval:SadDodosRescue. Keep the tool configuration and ownership unchanged
while aligning the component id with its owning agent.

Comment on lines +359 to +379
"YahooFinance:QuickAdsDig": {
"downstream": [
"CodeExec:LightSheepTrade"
],
"obj": {
"component_name": "YahooFinance",
"params": {
"balance_sheet": true,
"cash_flow_statement": false,
"financials": false,
"history": false,
"info": false,
"news": false,
"outputs": {
"report": {
"type": "string",
"value": ""
}
},
"stock_code": "sys.query"
}

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

YahooFinance receives the raw query instead of the extracted stock code.

stock_code is set to "sys.query". The graph node form repeats this at Line 769. Agent:ManyToesBrush exists only to convert the natural-language query into a ticker, and Switch:FluffyCoinsSell routes on Agent:ManyToesBrush@content (Line 338). With sys.query, the Yahoo Finance lookup receives text such as "Help me check the research report of Apple", so the balance-sheet branch and the downstream CodeExec:LightSheepTrade table produce no data. Update both the component params and the graph node form.

🐛 Proposed fix (apply at Line 378 and Line 769)
-                        "stock_code": "sys.query"
+                        "stock_code": "Agent:ManyToesBrush@content"
📝 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
"YahooFinance:QuickAdsDig": {
"downstream": [
"CodeExec:LightSheepTrade"
],
"obj": {
"component_name": "YahooFinance",
"params": {
"balance_sheet": true,
"cash_flow_statement": false,
"financials": false,
"history": false,
"info": false,
"news": false,
"outputs": {
"report": {
"type": "string",
"value": ""
}
},
"stock_code": "sys.query"
}
"YahooFinance:QuickAdsDig": {
"downstream": [
"CodeExec:LightSheepTrade"
],
"obj": {
"component_name": "YahooFinance",
"params": {
"balance_sheet": true,
"cash_flow_statement": false,
"financials": false,
"history": false,
"info": false,
"news": false,
"outputs": {
"report": {
"type": "string",
"value": ""
}
},
"stock_code": "Agent:ManyToesBrush@content"
}
🤖 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 `@agent/templates/stock_market_research_assistant.json` around lines 359 - 379,
Update both YahooFinance configurations—“YahooFinance:QuickAdsDig” and the
corresponding graph node form—to set params.stock_code to the extracted ticker
from Agent:ManyToesBrush@content instead of sys.query, preserving the existing
routing through Switch:FluffyCoinsSell and downstream CodeExec:LightSheepTrade.

Comment on lines 1119 to +1139
},
"selected": false,
"sourcePosition": "right",
"targetPosition": "left",
"type": "agentNode"
"label": "Tool",
"name": "flow.tool_2"
},
{
"data": {
"form": {
"description": "This is an agent for a specific task.",
"user_prompt": "This is the order you need to send to the agent."
},
"label": "Tool",
"name": "flow.tool_1"
},
"dragging": false,
"id": "Tool:FullIconsStop",
"measured": {
"height": 48,
"width": 200
},
"position": {
"x": 786.0879409003913,
"y": 373.7912225392144
},
"selected": false,
"sourcePosition": "right",
"targetPosition": "left",
"type": "toolNode"
"id": "Tool:ClearKiwisRoll",
"measured": {
"height": 44,
"width": 200
},
{
"data": {
"form": {
"conditions": [
{
"items": [
{
"cpn_id": "Agent:ManyToesBrush@content",
"operator": "not contains",
"value": "Not Found"
}
],
"logical_operator": "and",
"to": [
"YahooFinance:QuickAdsDig",
"Agent:SadDodosRescue"
]
}
],
"end_cpn_ids": [
"Message:TwentyBanksLeave"
]
},
"label": "Switch",
"name": "Switch"
},
"dragging": false,
"id": "Switch:FluffyCoinsSell",
"measured": {
"height": 146,
"width": 200
},
"position": {
"x": 244.5649388872756,
"y": 249.25263304293162
},
"selected": false,
"sourcePosition": "right",
"targetPosition": "left",
"type": "switchNode"
"position": {
"x": 592.0210917308762,
"y": 294.6374701767713
},
{
"data": {
"form": {
"description": "This is an agent for a specific task.",
"user_prompt": "This is the order you need to send to the agent."
},
"label": "Tool",
"name": "flow.tool_2"
},
"id": "Tool:ClearKiwisRoll",
"measured": {
"height": 44,
"width": 200
},
"position": {
"x": 592.0210917308762,
"y": 294.6374701767713
"sourcePosition": "right",
"targetPosition": "left",
"type": "toolNode"

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: For each toolNode, report the source agent from graph.edges and that agent's form.tools length.
set -euo pipefail

python - agent/templates/stock_market_research_assistant.json <<'PY'
import json, sys
doc = json.load(open(sys.argv[1]))
g = doc["dsl"]["graph"]
nodes = {n["id"]: n for n in g["nodes"]}
for e in g["edges"]:
    tgt = e.get("target")
    if isinstance(tgt, str) and tgt.startswith("Tool:"):
        src = nodes.get(e.get("source"), {})
        tools = ((src.get("data") or {}).get("form") or {}).get("tools")
        print(tgt, "<-", e.get("source"), "form.tools:", tools)
PY

Repository: infiniflow/ragflow

Length of output: 1305


Remove or wire Tool:ClearKiwisRoll to a real tool.

This node is the only one wired to an agent with an empty form.tools array (Agent:SadDodosRescue), so it renders as an operator without any tool behavior. Delete the node and its edge, or add the missing tool entry to Agent:SadDodosRescue.

🤖 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 `@agent/templates/stock_market_research_assistant.json` around lines 1119 -
1139, Update the workflow around Tool:ClearKiwisRoll and Agent:SadDodosRescue so
the agent no longer has an unwired tool node: either remove Tool:ClearKiwisRoll
together with its connecting edge, or add the intended real tool entry to
Agent:SadDodosRescue’s form.tools array and preserve the connection.

Comment on lines +141 to +156
{tools.map(({ id, component_name, name }, idx) => (
<ToolCard key={id || `tool-${idx}`} isNodeTool={false}>
<div className="flex gap-2 items-center">
<OperatorIcon name={component_name as Operator}></OperatorIcon>
{component_name === Operator.Retrieval ? name : component_name}
</div>
<ActionButton
record={id}
record={id || component_name}
deleteRecord={deleteNodeTool(id)}
edit={handleEdit}
/>
</ToolCard>
))}

{mcpIds.map((id) => (
<ToolCard key={id} isNodeTool={false}>
{mcpIds.map((id, idx) => (
<ToolCard key={id || `mcp-${idx}`} isNodeTool={false}>

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

mapfile -t hooks < <(fd -t f 'use-update-tools' web/src)
((${`#hooks`[@]} > 0))

for hook in "${hooks[@]}"; do
  printf '%s\n' "--- $hook"
  rg -n -C 12 '\b(deleteNodeTool|useDeleteAgentNodeTools)\b' "$hook"
done

# Expected: the delete callback accepts the same resolved identity used by
# ActionButton, or explicitly deletes by the complete tool record.

Repository: infiniflow/ragflow

Length of output: 208


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Repository root:"
pwd

echo "Find target file:"
fd -t f 'agent-tools\.tsx$' . || true

echo "Find possible delete/update hooks:"
find web/src -type f \( -name '*update*tools*.ts*' -o -name '*delete*tools*.ts*' -o -name 'useDelete*.ts*' -o -name 'useUpdate*.ts*' \) -print | sed 's#^\./##' | head -100

echo "Search symbols:"
rg -n --glob 'web/src/**/*.{ts,tsx}' 'deleteNodeTool|useDeleteAgentNodeTools|useDelete.*NodeTool|useUpdate.*NodeTool|ActionButton' || true

Repository: infiniflow/ragflow

Length of output: 384


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="web/src/pages/agent/form/agent-form/agent-tools.tsx"
hook="web/src/pages/agent/form/agent-form/tool-popover/use-update-tools.ts"

echo "--- $file outline"
ast-grep outline "$file" --view compact || true

echo "--- $file imports/top/srelevant lines 1-220"
sed -n '1,220p' "$file" | nl -ba | sed -n '1,220p'

echo "--- $hook outline"
ast-grep outline "$hook" --view compact || true

echo "--- $hook full"
sed -n '1,260p' "$hook" | nl -ba | sed -n '1,260p'

Repository: infiniflow/ragflow

Length of output: 502


🏁 Script executed:

#!/bin/bash
set -euo pipefail

file="web/src/pages/agent/form/agent-form/agent-tools.tsx"
hook="web/src/pages/agent/form/agent-form/tool-popover/use-update-tools.ts"

echo "--- file search matching symbols"
rg -n --glob 'web/src/**/*.{ts,tsx}' -C 5 'deleteNodeTool|useDeleteAgentNodeTools|useDelete.*Agent.*Tool|useUpdate.*Agent.*Tool|ActionButton|deleteNodeTools' || true

echo "--- agent-tools context"
awk 'NR>=1 && NR<=220 { printf "%6d  %s\n", NR, $0 }' "$file"

echo "--- use-update-tools"
awk 'NR>=1 && NR<=260 { printf "%6d  %s\n", NR, $0 }' "$hook"

Repository: infiniflow/ragflow

Length of output: 189


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "--- candidate files"
git ls-files 'web/src/**' | grep -E 'agent-tools\.tsx$|update-tools\.ts$' || true

echo "--- agent-tools full"
awk '1 { printf "%6d  %s\n", NR, $0 }' web/src/pages/agent/form/agent-form/agent-tools.tsx

echo "--- use-update-tools full"
awk '1 { printf "%6d  %s\n", NR, $0 }' web/src/pages/agent/form/agent-form/tool-popover/use-update-tools.ts

Repository: infiniflow/ragflow

Length of output: 12009


Use the same identity for the delete callback.

ActionButton uses component_name when id is missing, but deleteNodeTool(id) filters by x.id !== toolId, so a missing id still deletes every tool with no ID. Pass the same identity used by record, or pass the full tool record if deletes should target a tool by component name.

🤖 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/agent/form/agent-form/agent-tools.tsx` around lines 141 - 156,
Update the ActionButton wiring in the tools.map render to pass the same identity
used by record: use id when available and component_name as the fallback for
deleteNodeTool. Ensure deleteNodeTool filters against that identity so tools
without IDs are not all deleted.

@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.

Thanks for the fix! The core issue (tools from templates missing id fields) is correctly addressed.

What looks good:

  1. deep_research.json: Adding id fields to TavilySearch/TavilyExtract tool nodes is the right fix — these template tools were missing IDs, which caused the React key to be undefined and broke click handling.

  2. tool-node.tsx & agent-tools.tsx: Fallback keys (tool.id || tool-${idx}``) are a good defensive pattern for when IDs might still be missing from other sources.

  3. ToolCard refactor: Removing useMemo is important — the memoized element can interfere with Radix TooltipTrigger asChild when it clones the child and attaches event handlers. This is likely the real fix for the unclickable tool icon.

  4. TreeSelect & ModelTreeSelect → forwardRef: Correct pattern for enabling ref forwarding through to the trigger button. Clean conversion.

  5. next.tsx refactor: Clean simplification — extracting settingFields, removing the CollapseComponent indirection. No regression.

One thing to watch:

In agent-tools.tsx, ActionButton record now falls back to component_name when id is undefined:

record={id || component_name}

This changes the identifier passed to deleteRecord and edit callbacks. Please double-check that downstream handlers work correctly with a component_name-based identifier where they previously expected an id.

Otherwise looks solid!

@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

🧹 Nitpick comments (1)
agent/templates/stock_market_research_assistant.json (1)

140-212: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Remove the nested agent tool and keep the peer graph node shape.

Agent:SadDodos already has an empty tools array in the graph node, and Agent:MightyIdeasGlow exists as the peer agentNode linked by agentBottom/agentTop. Leaving the full nested tool definition in dsl.components["Agent:SadDodosRescue"].params.tools creates one stored shape that executes an agent tool and another executed shape that does not. Remove the nested tool copy so both paths use the peer node shape.

🤖 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 `@agent/templates/stock_market_research_assistant.json` around lines 140 - 212,
Remove the nested Agent tool definition for Agent:MightyIdeasGlow from the
parent agent’s params.tools, leaving that tools array empty while preserving the
peer agentNode and its agentBottom/agentTop links. Ensure the graph uses the
existing peer node shape consistently rather than storing a second executable
nested-agent copy.

Source: Coding guidelines

🤖 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 `@agent/templates/web_search_assistant.json`:
- Around line 46-51: Update both copies of the answer-organizer prompt to keep
`{Agent:WildGoatsRule@content}` only for “Web search result” and use the
retrieval agent’s `formalized_content` output for “Retrieval result,”
referencing the upstream retrieval node `Retrieval:WarmTimesRun` rather than
duplicating the search output.
- Around line 306-311: Remove captured session state from the
web_search_assistant template’s globals and related template fields: set
sys.conversation_turns to 0, clear sys.user_id and sys.query, and reset task_id,
history, path, and retrieval to their empty defaults. Preserve the template
structure so api/db/init_data.py continues to persist a clean baseline for each
deployment.
- Around line 157-235: Align the tool ids in dsl.components with the
corresponding dsl.graph.nodes[].data.form.tools.id values instead of using
separately generated ids. Update every affected tool definition in
agent/templates/web_search_assistant.json (lines 157-235),
agent/templates/cajal_scientific_paper_agent.json (lines 60-85),
agent/templates/your_starter_dataset_chatbot.json (lines 77-79),
agent/templates/user_interaction.json (lines 107-137), and
agent/templates/stock_market_research_assistant.json (lines 55-85); each sibling
site requires the same direct id-alignment change.

---

Nitpick comments:
In `@agent/templates/stock_market_research_assistant.json`:
- Around line 140-212: Remove the nested Agent tool definition for
Agent:MightyIdeasGlow from the parent agent’s params.tools, leaving that tools
array empty while preserving the peer agentNode and its agentBottom/agentTop
links. Ensure the graph uses the existing peer node shape consistently rather
than storing a second executable nested-agent copy.
🪄 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: f0b13313-985c-44cf-bd92-db8787cd79af

📥 Commits

Reviewing files that changed from the base of the PR and between d482ce2 and 856bf3a.

📒 Files selected for processing (5)
  • agent/templates/cajal_scientific_paper_agent.json
  • agent/templates/stock_market_research_assistant.json
  • agent/templates/user_interaction.json
  • agent/templates/web_search_assistant.json
  • agent/templates/your_starter_dataset_chatbot.json

Comment on lines +46 to +51
"prompts": [
{
"content": "User's query:\n{sys.query}\n\nRefined question:\n{Agent:ThreePathsDecide@content}\n\nWeb search result:\n{Agent:WildGoatsRule@content}\n\nRetrieval result:\n{Agent:WildGoatsRule@content}",
"role": "user"
}
],

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

The prompt reads the search agent output twice and never reads the retrieval output.

"Web search result" and "Retrieval result" both interpolate {Agent:WildGoatsRule@content}. Retrieval:WarmTimesRun is an upstream of Agent:SmartSchoolsCross (Line 64) and its formalized_content output is never referenced, so knowledge-base evidence never reaches the answer organizer. The graph node form repeats the same prompt at Line 682.

🐛 Proposed fix (apply at Line 48 and Line 682)
-                                "content": "User's query:\n{sys.query}\n\nRefined question:\n{Agent:ThreePathsDecide@content}\n\nWeb search result:\n{Agent:WildGoatsRule@content}\n\nRetrieval result:\n{Agent:WildGoatsRule@content}",
+                                "content": "User's query:\n{sys.query}\n\nRefined question:\n{Agent:ThreePathsDecide@content}\n\nWeb search result:\n{Agent:WildGoatsRule@content}\n\nRetrieval result:\n{Retrieval:WarmTimesRun@formalized_content}",
📝 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
"prompts": [
{
"content": "User's query:\n{sys.query}\n\nRefined question:\n{Agent:ThreePathsDecide@content}\n\nWeb search result:\n{Agent:WildGoatsRule@content}\n\nRetrieval result:\n{Agent:WildGoatsRule@content}",
"role": "user"
}
],
"prompts": [
{
"content": "User's query:\n{sys.query}\n\nRefined question:\n{Agent:ThreePathsDecide@content}\n\nWeb search result:\n{Agent:WildGoatsRule@content}\n\nRetrieval result:\n{Retrieval:WarmTimesRun@formalized_content}",
"role": "user"
}
],
🤖 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 `@agent/templates/web_search_assistant.json` around lines 46 - 51, Update both
copies of the answer-organizer prompt to keep `{Agent:WildGoatsRule@content}`
only for “Web search result” and use the retrieval agent’s `formalized_content`
output for “Retrieval result,” referencing the upstream retrieval node
`Retrieval:WarmTimesRun` rather than duplicating the search output.

Comment on lines +157 to +235
"tools": [
{
"component_name": "TavilySearch",
"name": "TavilySearch",
"params": {
"api_key": "",
"days": 7,
"exclude_domains": [],
"include_answer": false,
"include_domains": [],
"include_image_descriptions": false,
"include_images": false,
"include_raw_content": true,
"max_results": 5,
"outputs": {
"formalized_content": {
"type": "string",
"value": ""
},
"json": {
"type": "Array<Object>",
"value": []
}
},
"query": "sys.query",
"search_depth": "basic",
"topic": "general"
},
"id": "TavilySearch:SafeBeansFall"
},
{
"component_name": "TavilyExtract",
"name": "TavilyExtract",
"params": {
"api_key": ""
},
"id": "TavilyExtract:LoudWindsBurn"
},
{
"component_name": "Google",
"name": "Google",
"params": {
"api_key": "",
"country": "us",
"language": "en"
},
"id": "Google:QuickCloudsDream"
},
{
"component_name": "Bing",
"name": "Bing",
"params": {
"api_key": "YOUR_API_KEY (obtained from https://www.microsoft.com/en-us/bing/apis/bing-web-search-api)",
"channel": "Webpages",
"country": "CH",
"language": "en",
"top_n": 10
},
"id": "Bing:WiseHawksFly"
},
{
"component_name": "DuckDuckGo",
"name": "DuckDuckGo",
"params": {
"channel": "text",
"top_n": 10
},
"id": "DuckDuckGo:CalmHorsesSing"
},
{
"component_name": "Wikipedia",
"name": "Wikipedia",
"params": {
"language": "en",
"top_n": 10
},
"id": "Wikipedia:SharpFoxesSing"
}
],

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
# Description: Compare tool ids in dsl.components against dsl.graph.nodes[].data.form.tools per template.
set -euo pipefail

fd -e json . agent/templates --exec python3 -c '
import json,sys
p=sys.argv[1]
d=json.load(open(p)).get("dsl",{}) or {}

def walk(o,out):
    if isinstance(o,dict):
        t=o.get("tools")
        if isinstance(t,list):
            for x in t:
                if isinstance(x,dict):
                    out.append((x.get("component_name"),x.get("name"),x.get("id")))
        for v in o.values(): walk(v,out)
    elif isinstance(o,list):
        for v in o: walk(v,out)

c=[];g=[]
walk(d.get("components"),c)
walk((d.get("graph") or {}).get("nodes"),g)
if sorted(c)!=sorted(g):
    print("MISMATCH",p)
    print("  components:",sorted(c))
    print("  graph     :",sorted(g))
' {}

Repository: infiniflow/ragflow

Length of output: 2416


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf 'Candidate files:\n'
git ls-files agent/templates/*.json | sed -n '1,80p'

printf '\nTemplate excerpts mentioning component/graph tool ids:\n'
for f in \
  agent/templates/web_search_assistant.json \
  agent/templates/cajal_scientific_paper_agent.json \
  agent/templates/your_starter_dataset_chatbot.json \
  agent/templates/user_interaction.json \
  agent/templates/stock_market_research_assistant.json
do
  printf '\n--- %s ---\n' "$f"
  wc -l "$f"
  python3 - <<'PY' "$f"
import json, sys
from collections import defaultdict
p = sys.argv[1]
d = json.load(open(p)).get("dsl") or {}

def extract(obj):
    out = []
    if isinstance(obj, dict):
        if isinstance(obj.get("tools"), list):
            for x in obj["tools"]:
                if isinstance(x, dict) and "component_name" in x:
                    out.append((x.get("id"), x.get("component_name"), x.get("name"), x.get("params")))
        for v in obj.values():
            out.extend(extract(v))
    elif isinstance(obj, list):
        for v in obj:
            out.extend(extract(v))
    return out

c = extract(d.get("components") or {})
g = extract((d.get("graph") or {}).get("nodes"))

seen = defaultdict(lambda: {"component": [], "graph": []})
for i, (tool_id, name, display, params) in enumerate(c):
    k = (name, display, json.dumps(params, sort_keys=True))
    seen[k]["component"].append((i+1, tool_id))
for i, node in enumerate((d.get("graph") or {}).get("nodes") or []):
    tools = (node.get("data") or {}).get("form") or {}
    tools = tools.get("tools") if isinstance(tools, dict) else []
    for j, x in enumerate(tools):
        if isinstance(x, dict) and "component_name" in x:
            k = (x.get("component_name"), x.get("name"), json.dumps(x.get("params"), sort_keys=True))
            seen[k]["graph"].append((i+1, x.get("id")))

matches = []
mismatches = []
for k, v in seen.items():
    c_ids = sorted({*v["component"]})
    g_ids = sorted({*v["graph"]})
    if c_ids and g_ids and c_ids == g_ids:
        matches.append((k, c_ids))
    else:
        mismatches.append((k, c_ids, g_ids))

print(f"component tool instances: {len(c)}")
print(f"graph tool instances: {len(g)}")
print(f"matching id-sets: {len(matches)}")
print(f"mismatching id-sets: {len(mismatches)}")
for k, c_ids, g_ids in sorted(mismatches):
    print("MISMATCH", k)
    print("  component:", c_ids)
    print("  graph     :", g_ids)
PY
done

Repository: infiniflow/ragflow

Length of output: 1342


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json
import subprocess
from collections import defaultdict

files = subprocess.check_output(["git", "ls-files", "agent/templates/*.json"], text=True).splitlines()

for p in files:
    d = json.load(open(p)).get("dsl") or {}
    c_tools, g_tools = [], []

    def components(obj):
        if isinstance(obj, dict):
            if isinstance(obj.get("tools"), list):
                for x in obj["tools"]:
                    if isinstance(x, dict) and "component_name" in x:
                        components.append((x.get("id"), x.get("component_name"), x.get("name"), json.dumps(x.get("params"), sort_keys=True)))
            for v in obj.values():
                components(v)
        elif isinstance(obj, list):
            for v in obj:
                components(v)

    components(c_tools.append([]))
    for node in ((d.get("graph") or {}).get("nodes") or []):
        form = (node.get("data") or {}) or {}
        tools = (form.get("form") or {}).get("tools") if isinstance(form.get("form"), dict) else []
        for x in tools:
            if isinstance(x, dict) and "component_name" in x:
                g_tools.append((x.get(`id`), x.get("component_name"), x.get("name"), json.dumps(x.get("params"), sort_keys=True)))

    if c_tools or g_tools:
        print(p, len(c_tools), len(g_tools))
        if c_tools != g_tools:
            for component_tool, graph_tool in zip(c_tools[:5], g_tools[:5]):
                print("  component:", component_tool)
                print("  graph     :", graph_tool)
PY

Repository: infiniflow/ragflow

Length of output: 357


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '140,180p;520,580p' agent/templates/web_search_assistant.json
printf '\n--- cajal snippets ---\n'
sed -n '50,90p;255,280p' agent/templates/cajal_scientific_paper_agent.json
printf '\n--- starter snippets ---\n'
sed -n '70,85p;225,235p' agent/templates/your_starter_dataset_chatbot.json
printf '\n--- user_interaction snippets ---\n'
sed -n '100,140p;435,445p' agent/templates/user_interaction.json
printf '\n--- stock_market snippets ---\n'
sed -n '50,90p;670,685p' agent/templates/stock_market_research_assistant.json

Repository: infiniflow/ragflow

Length of output: 20923


🏁 Script executed:

#!/bin/bash
set -euo pipefail

python3 - <<'PY'
import json
import subprocess

files = subprocess.check_output(["git", "ls-files", "agent/templates/*.json"], text=True).splitlines()

for p in files:
    d = json.load(open(p)).get("dsl") or {}

    component_tools = []
    def walk_component(obj):
        if isinstance(obj, dict) and isinstance(obj.get("tools"), list):
            component_tools.append(
                (len(component_tools), obj.get("id"), obj.get("component_name"), obj.get("name"), obj.get("params"))
            )
        if isinstance(obj, dict):
            for v in obj.values():
                walk_component(v)
        elif isinstance(obj, list):
            for v in obj:
                walk_component(v)
    walk_component(d.get("components"))

    graph_tools = []
    nodes = (d.get("graph") or {}).get("nodes") or []
    for node in nodes:
        data = (node.get("data") or {}) or {}
        form = (data.get("form") or {}) or {}
        tools = form.get("tools") if isinstance(form, dict) and isinstance(form.get("tools"), list) else []
        for tool in tools:
            graph_tools.append(
                (node.get("id"), len(graph_tools), tool.get("component_name"), tool.get("name"), tool.get("params"))
            )

    if component_tools or graph_tools:
        print(f"{p} component_count={len(component_tools)} graph_count={len(graph_tools)}")
        for i, (n, uid, cn, name, params) in zip(range(len(component_tools)), component_tools):
            j = n % len(graph_tools) if graph_tools else None
            a = graph_tools[j] if j is not None else ("", "", "", "", "")
            matches = uid == a[0] and cn == a[2] and name == a[3] and params == a[4]
            if not matches:
                print("  MISMATCH component", uid, cn, name, "!= graph", a[0], a[2], a[3])
            else:
                print("  MATCH", uid, cn, name)
PY

Repository: infiniflow/ragflow

Length of output: 4142


Align the dsl.components tool ids with the linked dsl.graph tool ids.

These templates contain the same tool in dsl.components and in the matched graph node, but with different ids. Use a stable linked id from dsl.graph.nodes[].data.form.tools.id in the component tool instead of generating ids separately.

📍 Affects 5 files
  • agent/templates/web_search_assistant.json#L157-L235 (this comment)
  • agent/templates/cajal_scientific_paper_agent.json#L60-L85
  • agent/templates/your_starter_dataset_chatbot.json#L77-L79
  • agent/templates/user_interaction.json#L107-L137
  • agent/templates/stock_market_research_assistant.json#L55-L85
🤖 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 `@agent/templates/web_search_assistant.json` around lines 157 - 235, Align the
tool ids in dsl.components with the corresponding
dsl.graph.nodes[].data.form.tools.id values instead of using separately
generated ids. Update every affected tool definition in
agent/templates/web_search_assistant.json (lines 157-235),
agent/templates/cajal_scientific_paper_agent.json (lines 60-85),
agent/templates/your_starter_dataset_chatbot.json (lines 77-79),
agent/templates/user_interaction.json (lines 107-137), and
agent/templates/stock_market_research_assistant.json (lines 55-85); each sibling
site requires the same direct id-alignment change.

Comment on lines +306 to +311
"globals": {
"sys.conversation_turns": 1,
"sys.files": [],
"sys.query": "你好",
"sys.user_id": "d6d98fd652f911f0a8fb047c16ec874f"
},

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: List templates whose dsl carries leftover runtime state.
set -euo pipefail

fd -e json . agent/templates --exec python3 -c '
import json,sys
p=sys.argv[1]
d=json.load(open(p)).get("dsl",{}) or {}
g=d.get("globals",{}) or {}
bad=[]
if g.get("sys.user_id"): bad.append("sys.user_id")
if g.get("sys.query"): bad.append("sys.query")
if g.get("sys.conversation_turns"): bad.append("sys.conversation_turns")
for k in ("history","path","messages","memory","retrieval","task_id"):
    if d.get(k): bad.append(k)
if bad: print(p, bad)
' {}

Repository: infiniflow/ragflow

Length of output: 2416


🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "== candidate template snippets =="
python3 - <<'PY'
import json, pathlib, re
p = pathlib.Path("agent/templates/web_search_assistant.json")
text = p.read_text(encoding="utf-8")
print(p, "bytes", len(text))
lines = text.splitlines()
for label in ("globals", "history", "memory", "messages", "path", "retrieval", "task_id"):
    if label == "globals":
        idx = next((i for i,l in enumerate(lines) if '"globals"' in l), None)
        start = max(0, idx-3) if idx is not None else 0
        end = min(len(lines), (idx+20) if idx is not None else 30)
    elif label in ("history", "memory", "messages", "path", "retrieval"):
        idx = next((i for i,l in enumerate(lines) if '"' + label + '"' in l), None)
        start = max(0, idx-3) if idx is not None else 0
        end = min(len(lines), (idx+12) if idx is not None else 30)
    elif label == "task_id":
        for i,l in enumerate(lines):
            if '"task_id"' in l:
                idx=i
                break
        start = max(0, idx-3)
        end = min(len(lines), idx+5)
    else:
        continue
    print(f"\n--- {p}:{start+1}-{end+1} {label} ---")
    for n in range(start, end):
        print(f"{n+1:4}: {lines[n]}")

print("\n== load relevant DSL object ==")
data = json.loads(text)
ds = data.get("dsl") or {}
g = ds.get("globals") or {}
for k in sorted(g.keys()):
    v = g[k]
    if isinstance(v, dict):
        print(k, "dict")
    else:
        print(k, repr(v)[:240])

print("\n== runtime keys ==")
for k in ("history","memory","messages","path","retrieval","task_id"):
    v = ds.get(k)
    print(k, type(v).__name__, "empty" if not v else "non-empty", repr(v)[:200] if not isinstance(v, list) else "list len " + str(len(v)) + (", first: " + repr(v[0][:200] if v and not isinstance(v[0], dict) else "first dict/list")[:200]))

print("\n== init_data relevant loader ==")
init = pathlib.Path("api/db/init_data.py")
if init.exists():
    lines = init.read_text(encoding="utf-8").splitlines()
    for i,l in enumerate(lines):
        if "def add_graph_templates" in l:
            start=max(0,i)
            end=min(len(lines), i+35)
            print("\n--- init_data.py:", start+1, "-", end+1, "---")
            for n in range(start,end):
                print(f"{n+1:4}: {lines[n]}")
else:
    print("api/db/init_data.py missing")

print("\n== remaining json template runtime-state scan ==")
import json, pathlib
bad=[]
for p in sorted(pathlib.Path("agent/templates").glob("*.json")):
    data=json.loads(p.read_text(encoding='utf-8'))
    ds=data.get("dsl") or {}
    g=ds.get("globals") or {}
    toks=[]
    if g.get("sys.user_id"): toks.append("sys.user_id=" + repr(g["sys.user_id"])[:80])
    if g.get("sys.query"): toks.append("sys.query=" + repr(g["sys.query"])[:80])
    if g.get("sys.conversation_turns", 0): toks.append("sys.conversation_turns=" + str(g["sys.conversation_turns"]))
    for k in ("history","path","messages","memory","retrieval","task_id"):
        v=ds.get(k)
        if v:
            toks.append(k+"="+type(v).__name__)
    if toks:
        bad.append((str(p), toks))
print(len(bad))
for p, toks in bad:
    print(p)
    for t in toks:
        print("  ", t)
PY

Repository: infiniflow/ragflow

Length of output: 13097


Sensitive Data Exposure (CWE-359)

Reachability: Internal

Remove the captured session state from the shipped template.

web_search_assistant.json ships with sys.user_id, sys.query, a concrete task_id, and non-empty history, path, and retrieval. api/db/init_data.py persists each JSON template verbatim, so this leaked session state is copied into every deployment. Reset these fields to their empty defaults; set sys.conversation_turns to 0.

🤖 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 `@agent/templates/web_search_assistant.json` around lines 306 - 311, Remove
captured session state from the web_search_assistant template’s globals and
related template fields: set sys.conversation_turns to 0, clear sys.user_id and
sys.query, and reset task_id, history, path, and retrieval to their empty
defaults. Preserve the template structure so api/db/init_data.py continues to
persist a clean baseline for each deployment.

Source: Coding guidelines

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🐞 bug Something isn't working, pull request that fix bug. ci Continue Integration size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants