Skip to content

feat(go-agent): Ported retrieval node, added Keenable web search tool - #16396

Merged
yuzhichang merged 7 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port
Jun 26, 2026
Merged

yuzhichang merged 7 commits into
infiniflow:mainfrom
yuzhichang:agent-go-port

Conversation

@yuzhichang

Copy link
Copy Markdown
Member

Ported retrieval node, added Keenable web search tool

  • New Feature (non-breaking change which adds functionality)

…alidation to accept any version, ensure retrieval node work

Port of python PR infiniflow#16233 to the Go workflow. Keenable is a web search
API that works without an API key by default (keyless free tier);
providing a key lifts rate limits and unlocks 'realtime' mode.
@yuzhichang yuzhichang added the ci Continue Integration label Jun 26, 2026
@dosubot dosubot Bot added the size:XL This PR changes 500-999 lines, ignoring generated files. label Jun 26, 2026
@yuzhichang
yuzhichang marked this pull request as draft June 26, 2026 12:58
@yuzhichang
yuzhichang marked this pull request as ready for review June 26, 2026 12:58
@dosubot dosubot Bot added the 💞 feature Feature request, pull request that fullfill a new feature. label Jun 26, 2026
@coderabbitai

coderabbitai Bot commented Jun 26, 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

Run ID: 029a3c54-21ee-4ffd-b1de-459bc313a00b

📥 Commits

Reviewing files that changed from the base of the PR and between 3ed10c4 and 398db97.

📒 Files selected for processing (4)
  • api/apps/services/file_api_service.py
  • api/db/joint_services/tenant_model_service.py
  • internal/agent/tool/registry.go
  • internal/agent/tool/registry_test.go
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal/agent/tool/registry.go
  • api/db/joint_services/tenant_model_service.py
  • internal/agent/tool/registry_test.go

📝 Walkthrough

Walkthrough

The PR updates canvas resume and fill-up handling, propagates structured user input through agent chat, normalizes retrieval inputs, adds a Keenable tool, relaxes UUID validation, canonicalizes provider names, updates the Aliyun sandbox SDK, and applies formatting-only cleanup.

Changes

Canvas input flow

Layer / File(s) Summary
Resume handling and initial query
agent/canvas.py, internal/agent/canvas/interrupt_resume.go, internal/agent/canvas/interrupt_resume_test.go, internal/agent/canvas/runner.go, test/testcases/test_web_api/test_canvas_app/test_iteration_runtime_unit.py
Canvas.run() adds resume detection that skips initial bootstrap and workflow-start events; the Go runner accepts any-typed user input and checks nil instead of empty string; structured sys.query maps are consumed during interrupt resume; iteration tests cover the resumed event sequence.
Merged runtime inputs and UserFillUp pipeline
agent/component/fillup.py, agent/component/begin.py, agent/canvas.py, test/testcases/test_web_api/test_canvas_app/test_fillup_unit.py
UserFillUp adds runtime-input merging, one-time sys.query consumption, and file/dict value resolution; Begin uses the same helpers; Canvas._is_input_field_satisfied skips yielding user_inputs when all fields are satisfied; dict questions are JSON-serialized in history; unit tests cover auto-consume, idempotency, and unmatched structured queries.

Agent chat SSE

Layer / File(s) Summary
Structured user input through handler and service
internal/handler/agent.go, internal/handler/agent_test.go, internal/handler/agent_wait_for_user_test.go, internal/service/agent.go
agentChatCompletionsRequest gains Inputs; the handler derives userInput from query, inputs, or last message; RunAgent accepts any throughout; the service normalizes to string for tracking, seeds state.Sys["user_id"], and serializes workflow_finished inputs as map[string]any; tests cover form-style and structured inputs.
SSE event normalization and logging
web/src/hooks/use-send-message.ts, internal/handler/agent.go
WaitingForUser is added; normalizeAgentEvent remaps it to UserInputs with parsed JSON data; per-event, stream-close, and SSE-frame debug logs are added; streaming JSON parse failures resolve to undefined.

Retrieval and tools

Layer / File(s) Summary
Legacy retrieval input normalization
internal/agent/component/universe_a_wrappers.go, internal/agent/component/production_chain_fixes_test.go
Retrieval Invoke normalizes legacy UserFillUp strings and structured state into canonical query and dataset_ids; dataset IDs are resolved through DAO lookups; regression tests use in-memory SQLite fixtures.
Retrieval adapters and startup wiring
internal/agent/tool/retrieval.go, internal/agent/tool/retrieval_nlp.go, internal/agent/tool/retrieval_nlp_test.go, cmd/server_main.go
RetrievalTool adds debug logs; NLPRetrievalAdapter gains kbDAO and TenantIDs handling; startup installs the retrieval service once and reuses the same DocumentDAO; default logging falls back to debug.
Keenable web search tool
internal/agent/tool/keenable.go, internal/agent/tool/keenable_test.go, internal/agent/tool/registry.go, internal/agent/tool/registry_test.go
KeenableTool validates base URLs, dispatches keyless or keyed requests, truncates results, and returns JSON envelopes; the registry adds "keenable" with optional api_key; tests cover routing, validation, truncation, error handling, and schema exposure.
Aliyun sandbox SDK v5 update
internal/agent/sandbox/aliyun.go, agent/sandbox/providers/aliyun_codeinterpreter.py, agent/sandbox/tests/test_aliyun_codeinterpreter.py, go.mod, pyproject.toml
The Aliyun integrations switch to the v5 SDK and Template.list_templates; dependency files raise the SDK versions used by Go and Python packaging.

Validation and provider resolution

Layer / File(s) Summary
UUID format validation (any version)
api/utils/validation_utils.py, test/testcases/restful_api/test_datasets.py, test/testcases/test_http_api/test_dataset_management/*, test/testcases/test_sdk_api/test_dataset_mangement/*
validate_uuid1_hex drops version checking and raises invalid_uuid_format; docs are updated; dataset API, HTTP, and SDK tests now expect "Invalid UUID format" for non-UUID strings and permission failures for valid-but-unauthorized UUID4 hex values.
Provider name canonicalization and instance fallback
api/db/joint_services/tenant_model_service.py, internal/service/model_service.go, test/unit_test/api/db/services/test_tenant_model_service_instance_fallback.py
_resolve_instance_for_model falls back from a missing "default" instance to the sole active instance; model service adds canonicalization helpers and canonicalizes providerName in provider listing and instance APIs.

Small behavior fixes

Layer / File(s) Summary
List operation name normalization
agent/component/list_operations.py, test/testcases/test_web_api/test_canvas_app/test_list_operations_unit.py
_normalize_operation_name maps topn to head and defaults empty values to nth; the unit test asserts topN normalizes to head.
Switch nil operand coercion for string operators
internal/agent/component/switch.go, internal/agent/component/switch_test.go
evaluateClause coerces nil operands to empty strings for contains, not contains, start with, and end with; regression tests cover nil upstream and nil right-hand operand cases.

Low-risk cleanup

Layer / File(s) Summary
Agent infrastructure and handler cleanup
internal/agent/workflowx/loop.go, internal/agent/workflowx/loop_options_test.go, internal/handler/mcp.go, internal/handler/searchbot_test.go, internal/agent/tool/qweather_test.go, internal/handler/agent_upload_test.go, internal/handler/dify_retrieval_handler_test.go, internal/handler/file_commit.go, internal/handler/file_commit_test.go
Formatting-only updates to workflow loop structs and tests; mcpDetailError returns the intended exception payload; handler test helpers are reformatted.
Core infrastructure formatting and comment cleanup
internal/cli/filesystem/*, internal/common/*, internal/deepdoc/*, internal/engine/elasticsearch/*, internal/engine/infinity/*, internal/entity/*, internal/utility/*
Filesystem, common, deepdoc, engine, entity, and utility files receive formatting, comment reflow, and brace-placement cleanup with no behavior changes.
Service and test cleanup
internal/service/chunk/*, internal/service/kg/*, internal/service/nlp/*, internal/service/agent_sessions.go, internal/service/think_tag.go, internal/service/think_tag_test.go, internal/service/tenant_test.go
Import ordering, comment, and formatting cleanup; the KG search test removes stray numeric lines from an assertion block.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

💞 feature, ci, size:XL

Suggested reviewers

  • yingfeng

Poem

🐇 Hop, hop, the canvas found its way,
No duplicate start to greet the day.
Keenable searches through the burrow deep,
UUIDs now hop in any shape they keep.
This bunny twitches a happy nose—
New flows, new tools, and tidy prose.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is missing the required problem/background section and template headings, so it does not meet the repository format. Add the "What problem does this PR solve?" section with context, and format the type-of-change checklist under the exact template headings.
Docstring Coverage ⚠️ Warning Docstring coverage is 40.10% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: porting the retrieval node and adding the Keenable web search tool.
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: 14

Caution

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

⚠️ Outside diff range comments (4)
cmd/server_main.go (1)

94-118: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Restore info as the default log level.

This change turns on debug logging for deployments that do not explicitly set config.Log.Level. In this PR, the retrieval path now debug-logs raw inputs, queries, and tool output, so the new default will persist user prompts and retrieved content into server logs by default.

Suggested fix
-// Temporarily default to debug while investigating the Go chat/SSE path.
-if err := common.Init("debug", common.FileOutput{Path: "server_main.log"}); err != nil {
+bootstrapLevel := "info"
+if debugFlag {
+	bootstrapLevel = "debug"
+}
+if err := common.Init(bootstrapLevel, common.FileOutput{Path: "server_main.log"}); err != nil {
 	panic(fmt.Sprintf("Failed to initialize logger: %v", err))
 }
@@
 if level == "" {
-	level = "debug"
+	level = "info"
 }
🤖 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 `@cmd/server_main.go` around lines 94 - 118, The default log level in server
startup should remain info rather than debug. Update the initialization flow in
server_main so that when config.Log.Level is empty, the fallback used before
reinitializing the logger is info, while still honoring any explicit level from
server.GetConfig() and the existing common.Init/common.Fatal path.
internal/agent/sandbox/aliyun.go (1)

216-224: 🎯 Functional Correctness | 🟠 Major

Fix functional divergence: template_name is silently ignored in the Go provider

The Go implementation computes templateName but does not pass it to CreateCodeInterpreter, falling back to the platform default. The Python provider explicitly resolves and applies the template via Sandbox.create(template_name=...). This causes identical sandbox configurations to produce different runtime environments depending on the execution language.

Since the Go SDK v5.8.4 CreateCodeInterpreterInput lacks the TemplateName field, you must not silently ignore the user's configuration. Update CreateInstance to either:

  1. Fail fast: Return an error immediately if template_name is provided or required, ensuring the user is aware the feature is unsupported in the Go path.
  2. Remove abstraction: Temporarily clear the template_name handling in the Go path until the SDK is updated, rather than recording it in metadata as a lie.
// internal/agent/sandbox/aliyun.go
if templateName != "" && !p.canApplyTemplate {
    return nil, fmt.Errorf("aliyun: template selection (%s) is not supported by Go SDK v5.8.4", templateName)
}

[large_code_change_1/1]

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

In `@internal/agent/sandbox/aliyun.go` around lines 216 - 224, The Go sandbox path
is silently ignoring `templateName` in `CreateInstance`, causing behavior to
diverge from the Python `Sandbox.create(template_name=...)` flow. Update the
`aliyun.go` `CreateInstance` logic to stop pretending the template was applied:
either return a clear error when `templateName` is set and
`CreateCodeInterpreterInput` cannot support it, or remove the `template_name`
metadata fallback entirely until the SDK exposes it. Keep the fix centered on
the `templateName` handling around `CreateCodeInterpreter` so the user is not
misled.
internal/service/agent.go (1)

691-696: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Don't log the full user_input payload from RunAgent.

This debug statement persists the raw prompt/form payload after the handler already accepted arbitrary user content. That expands PII/secret exposure into another log stream for little diagnostic value. Log presence/type/size instead of the 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 `@internal/service/agent.go` around lines 691 - 696, The RunAgent debug log is
exposing the full raw user_input payload, which should not be persisted in logs.
Update the common.Debug call in RunAgent to stop logging the content of
root["user_input"] and instead log only safe metadata such as whether it is
present, its type, or its size/length; keep the existing canvasID, userID,
sessionID, and tenantID fields unchanged.
web/src/hooks/use-send-message.ts (1)

188-212: 🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Remove production SSE debug logs.

val can include streamed chat content, user inputs, and identifiers; logging every event exposes sensitive conversation data in the browser console.

Proposed cleanup
             const { done, value } = x;
             if (done) {
-              console.log('agent chat sse reader done');
               break;
             }
@@
               if (payload === '[DONE]') {
-                console.log('agent chat sse done sentinel');
                 break;
               }
               const val = normalizeAgentEvent(JSON.parse(payload));
-              console.log('agent chat sse event', val);
🤖 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-send-message.ts` around lines 188 - 212, Remove the
production SSE debug logging from use-send-message so streamed chat payloads are
not exposed in the browser console. In the reader loop, delete the console.log
calls around the agent chat SSE flow, especially the logs for reader completion,
done sentinel, and parsed events after normalizeAgentEvent(JSON.parse(payload)).
Keep the SSE parsing and [DONE] handling intact, but do not emit val or other
event data to logs.
🧹 Nitpick comments (6)
test/testcases/test_web_api/test_canvas_app/test_list_operations_unit.py (1)

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

Cover the default-to-nth branch too.

The helper now has two new behaviors: aliasing topN and falling back to nth for None/blank input, but this test only locks down the alias case. A small parametrized test for None, "", and " " would cover the more regression-prone branch.

🤖 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 `@test/testcases/test_web_api/test_canvas_app/test_list_operations_unit.py`
around lines 194 - 201, The ListOperationsParam.check coverage only validates
the topN alias normalization and misses the new default-to-nth fallback. Add a
small parametrized test alongside test_topn_operation_alias_normalizes_to_head
that exercises ListOperationsParam.check with None, empty string, and
whitespace-only operations, and assert each case normalizes to nth so the
fallback branch stays covered.
agent/component/list_operations.py (1)

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

Log the normalization path in check().

check() now rewrites incoming operation names before validation, but that new branch is silent. Please add a debug log for the raw and normalized values so alias/default rewrites are traceable when canvas validation surprises callers. As per coding guidelines, **/*.py: Add logging for new flows.

🤖 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/component/list_operations.py` around lines 42 - 51, The new
normalization branch in check() is silent, so add a debug log there to trace how
incoming operation names are rewritten. In ListOperations.check(), capture the
raw self.operations value before calling _normalize_operation_name(), then log
both the original and normalized values after normalization so alias/default
conversions like topn or empty input are visible during canvas validation. Keep
the logging localized to the check() flow and use the existing
_normalize_operation_name helper to locate the rewrite path.

Source: Coding guidelines

test/unit_test/api/db/services/test_tenant_model_service_instance_fallback.py (1)

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

Cover the non-fallback error paths too.

This only locks in the single-active success case. _resolve_instance_for_model() also has zero-active and multi-active branches, and those are the ones that prevent "default" from silently binding to the wrong instance after future changes.

🤖 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
`@test/unit_test/api/db/services/test_tenant_model_service_instance_fallback.py`
around lines 23 - 48, The test for _resolve_instance_for_model() only covers the
fallback path where a default instance resolves to a single active tenant
instance. Add assertions for the other non-fallback branches in the same test
module by exercising the zero-active and multi-active cases through
TenantModelInstanceService.get_by_provider_id_and_instance_name and
get_all_by_provider_id, and verify the function fails or returns the expected
error behavior instead of binding "default" incorrectly.
agent/component/fillup.py (1)

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

Add trace logging around the new input merge/resolution flow.

This introduces a new execution path for auto-consuming sys.query and resolving file-backed inputs, but there is no log point when that path is taken. That will make resume/debugging much harder. As per coding guidelines, **/*.py: Add logging for new flows.

Also applies to: 112-118

🤖 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/component/fillup.py` around lines 42 - 84, Add trace logging to the new
auto-merge and input-resolution path in _merge_runtime_inputs and
_resolve_input_value. Log when sys.query is consumed, when a dict query is
filtered into runtime inputs, when a single-field query is auto-mapped, and when
file-backed values are sent through FileService.get_files. Keep the log points
near the existing checks in FillUp so the flow is easy to trace during
resume/debugging.

Source: Coding guidelines

test/testcases/test_web_api/test_canvas_app/test_iteration_runtime_unit.py (1)

254-258: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Assert the resumed input reaches the message content.

The Message test double leaves {UserFillUp:1@value} unresolved, so the resume test passes on “some message event exists” without proving "hello" was propagated. Resolve refs like Probe does, then assert the message content.

Proposed test hardening
     class Message(base_mod.ComponentBase):
         component_name = "Message"
 
         def _invoke(self, **kwargs):
-            self.set_output("content", self.string_format(self._param.content, {}))
+            vars_map = self.get_input_elements_from_text(self._param.content)
+            self.set_output(
+                "content",
+                self.string_format(
+                    self._param.content,
+                    {key: value["value"] for key, value in vars_map.items()},
+                ),
+            )
     resumed_kinds = [event["event"] for event in resumed_events]
     assert resumed_kinds[0] == "node_started"
     assert "workflow_started" not in resumed_kinds
     assert "message" in resumed_kinds
+    assert any(
+        event["event"] == "message" and event["data"].get("content") == "hello"
+        for event in resumed_events
+    )
     assert resumed_kinds[-1] == "workflow_finished"

Also applies to: 511-514

🤖 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 `@test/testcases/test_web_api/test_canvas_app/test_iteration_runtime_unit.py`
around lines 254 - 258, The Message test double currently sets output content
without resolving referenced inputs, so the resume test can pass without proving
the resumed value reached the message body. Update Message._invoke to resolve
placeholders the same way Probe does before calling set_output, then strengthen
the affected assertions in test_iteration_runtime_unit so they verify the
Message content contains the resumed value (for example, the propagated “hello”)
instead of only checking that some message event exists.
agent/canvas.py (1)

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

Add a lightweight log for the resume branch.

This new flow skips begin and workflow_started, but there is no server-side signal when that path is taken. Log only low-cardinality metadata like task_id and the resume node, not user input. As per coding guidelines, **/*.py: Add logging for new flows.

Proposed change
         self.globals["sys.conversation_turns"] += 1
         is_resume = bool(self.path) and self.path[0].lower().find("userfillup") >= 0
+        if is_resume:
+            logging.info(
+                "Canvas resume detected for task %s at node %s; skipping workflow_started",
+                self.task_id,
+                self.path[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/canvas.py` around lines 418 - 440, The resume path in the workflow
setup currently skips the normal start markers without any server-side trace;
add a lightweight log inside the resume branch around the logic in canvas.py
where is_resume is computed and begin/workflow_started are bypassed. Use only
low-cardinality metadata such as self.task_id and the resume node from
self.path[0], and avoid logging inputs or other user data. Keep the change
minimal and consistent with the existing logging style near the cancellation and
workflow start handling.

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/canvas.py`:
- Around line 746-759: The input satisfaction check in _is_input_field_satisfied
is rejecting optional file uploads too early by returning False whenever value
is None. Update this helper to recognize optional file fields before the generic
None check, consistent with UserFillUp._resolve_input_value and the optional
file-input contract in fillup.py, so empty optional file values are treated as
satisfied while required ones still fail. Use the existing field dict shape and
the field_type file check to keep the behavior limited to file inputs.

In `@agent/component/fillup.py`:
- Around line 57-63: The initial query is being marked consumed in UserFillUp
before confirming this node actually uses any matching fields, which causes
later fill-up nodes to miss structured input. In UserFillUp’s query-handling
path, delay setting _INITIAL_USER_INPUT_CONSUMED_KEY until after the dict is
filtered and you know at least one key matched the component’s declared fields.
Keep the check aligned with the logic in agent/canvas.py that builds
another_inputs so sys.query is only burned by the first fill-up node that
actually consumes it.

In `@api/utils/validation_utils.py`:
- Around line 323-325: The UUID conversion in the validation helper is allowing
non-UUID inputs like bytes or bytearray to reach the return path and expose the
.hex method instead of a hex string. Update the UUID-handling logic in the
validation utility function that currently does UUID(v) and returns uuid_obj.hex
so it accepts only UUID or string inputs, and explicitly reject any other types
before returning. Make sure the final branch cannot pass through raw non-UUID
objects.

In `@internal/agent/canvas/runner.go`:
- Around line 224-225: The resume path in Run still treats "" as the only “no
resume payload” sentinel, which breaks blank user submissions now that userInput
is any. Update the resume injection logic in Run to use an explicit presence
check for whether input was provided, rather than comparing userInput against an
empty string, so intentional empty values can still resume a waiting run.

In `@internal/agent/component/production_chain_fixes_test.go`:
- Around line 200-212: In the test setup that opens the SQLite in-memory
database for the production chain fixes cases, replace the private in-memory DSN
with a shared-cache in-memory DSN and restrict the GORM/sql.DB pool to a single
connection so migrations and later queries use the same database state. Apply
this change in each setup block around the db initialization used with dao.DB,
including the ones in the shared test helpers for the production chain fixes
scenarios. Ensure the existing gorm.Open and subsequent AutoMigrate calls still
work deterministically after the connection-pool limit is applied.

In `@internal/agent/component/switch_test.go`:
- Around line 343-377: The test only covers the nil upstream “start with” path,
so a regression in the “end with” branch could still slip through. Update
TestSwitch_NilUpstreamStartWithEndWithDoNotCrash in switch_test.go to also
exercise the `end with` operator, ideally as a separate assertion or subtest
alongside the existing `start with` case, using the same `NewSwitchComponent`,
`Invoke`, and `nextTargets` flow.

In `@internal/agent/component/universe_a_wrappers.go`:
- Around line 390-396: The user-visibility fallback in universe_a_wrappers.go
can resolve a dataset from an invalid knowledgebase because the
GetKBByNameAndUserID path does not enforce the same valid-status check used
elsewhere. Update the fallback inside the user_id branch in the KB resolution
logic to only return a KB when it is valid (for example by checking the KB
status before using kbs[0].ID, or by switching to a DAO/query path that already
filters to valid records). Keep the existing common.Debug logging and return
flow in the same resolution block.
- Around line 308-336: The early return in normalizeStructuredRetrievalInputs is
skipping query normalization whenever dataset_ids is already set, which causes
structured retrieval inputs from state["UserFillUp:KBInput"] to be dropped.
Remove or narrow that guard so the helper still reads and propagates the query
field even when applyDefaults has already populated dataset_ids, while
preserving any existing dataset_ids value.

In `@internal/agent/tool/keenable.go`:
- Around line 144-168: resolveKeenableBaseURL currently allows KEENABLE_API_URL
values with query or fragment parts, which can later break InvokableRun when it
concatenates baseURL with a path. Update resolveKeenableBaseURL to reject any
input parsed by neturl.Parse that contains a non-empty RawQuery or Fragment, and
return a clear validation error alongside the existing scheme/host checks. Keep
the fix localized to resolveKeenableBaseURL and ensure the allowed values remain
only clean base URLs used by InvokableRun.

In `@internal/agent/tool/registry.go`:
- Line 45: The KeenableTool registry wiring exposes api_key as a model-facing
argument without any safe server-side configuration path, so update the registry
and tool setup to remove secret handling from prompt/runtime args. Add a
config-backed initialization path for NewKeenableTool through the registry
instead of using noConfig, and adjust KeenableTool.Info() so api_key is not
advertised as a tool argument while keeping the tool usable via server-provided
credentials.

In `@internal/agent/tool/retrieval_nlp.go`:
- Around line 183-188: The retrieval path is widening `TenantIDs` from raw
`req.DatasetIDs` in `retrieval_nlp.go`, which can let an unvalidated dataset ID
add another tenant to the search scope. Update the `GetByIDs`/`appendTenantID`
block in `retrieveNLP` so tenant IDs are only added after validating the caller
is allowed to see each KB, or stop deriving tenant scope from `dataset_ids`
entirely and keep the search constrained to the already-authorized tenant
context.

In `@internal/handler/agent.go`:
- Around line 951-960: The request and failure logs in the agent chat flow are
recording raw user-provided content, which should be removed. Update the logging
around the agent chat completion path in internal/handler/agent.go, including
the request received and error handling in the same flow, so it logs only
metadata such as field presence, counts, lengths, and flags instead of req.Query
or the derived userInput payload. Use the existing common.Debug/common.Error
logging points in the agent chat handler and keep the logs useful for tracing
without emitting prompt or form-answer contents.

In `@web/src/hooks/use-send-message.ts`:
- Around line 90-99: The normalizeAgentEvent helper only remaps the top-level
event field for WaitingForUser, but the Go runner’s waiting_for_user payload is
still nested as a JSON string, so downstream findInputFromList() can get a
string instead of the expected inputs/tips object. Update normalizeAgentEvent in
use-send-message.ts to detect the waiting-for-user payload, parse and normalize
the nested data as part of the UserInputs shape, and make sure the object passed
onward has the expected structure rather than leaving the payload string intact.

In `@web/src/pages/agent/chat/use-send-agent-message.ts`:
- Around line 457-459: The chat message effect in use-send-agent-message.ts
still contains a debug console.log that prints answerList on every update, which
can leak streamed answers and user data to the browser console. Remove the
logging from the useEffect that reads answerList, and keep the rest of the
message-processing logic unchanged so the effect still handles content, id,
attachment, audio_binary, and downloads normally.

---

Outside diff comments:
In `@cmd/server_main.go`:
- Around line 94-118: The default log level in server startup should remain info
rather than debug. Update the initialization flow in server_main so that when
config.Log.Level is empty, the fallback used before reinitializing the logger is
info, while still honoring any explicit level from server.GetConfig() and the
existing common.Init/common.Fatal path.

In `@internal/agent/sandbox/aliyun.go`:
- Around line 216-224: The Go sandbox path is silently ignoring `templateName`
in `CreateInstance`, causing behavior to diverge from the Python
`Sandbox.create(template_name=...)` flow. Update the `aliyun.go`
`CreateInstance` logic to stop pretending the template was applied: either
return a clear error when `templateName` is set and `CreateCodeInterpreterInput`
cannot support it, or remove the `template_name` metadata fallback entirely
until the SDK exposes it. Keep the fix centered on the `templateName` handling
around `CreateCodeInterpreter` so the user is not misled.

In `@internal/service/agent.go`:
- Around line 691-696: The RunAgent debug log is exposing the full raw
user_input payload, which should not be persisted in logs. Update the
common.Debug call in RunAgent to stop logging the content of root["user_input"]
and instead log only safe metadata such as whether it is present, its type, or
its size/length; keep the existing canvasID, userID, sessionID, and tenantID
fields unchanged.

In `@web/src/hooks/use-send-message.ts`:
- Around line 188-212: Remove the production SSE debug logging from
use-send-message so streamed chat payloads are not exposed in the browser
console. In the reader loop, delete the console.log calls around the agent chat
SSE flow, especially the logs for reader completion, done sentinel, and parsed
events after normalizeAgentEvent(JSON.parse(payload)). Keep the SSE parsing and
[DONE] handling intact, but do not emit val or other event data to logs.

---

Nitpick comments:
In `@agent/canvas.py`:
- Around line 418-440: The resume path in the workflow setup currently skips the
normal start markers without any server-side trace; add a lightweight log inside
the resume branch around the logic in canvas.py where is_resume is computed and
begin/workflow_started are bypassed. Use only low-cardinality metadata such as
self.task_id and the resume node from self.path[0], and avoid logging inputs or
other user data. Keep the change minimal and consistent with the existing
logging style near the cancellation and workflow start handling.

In `@agent/component/fillup.py`:
- Around line 42-84: Add trace logging to the new auto-merge and
input-resolution path in _merge_runtime_inputs and _resolve_input_value. Log
when sys.query is consumed, when a dict query is filtered into runtime inputs,
when a single-field query is auto-mapped, and when file-backed values are sent
through FileService.get_files. Keep the log points near the existing checks in
FillUp so the flow is easy to trace during resume/debugging.

In `@agent/component/list_operations.py`:
- Around line 42-51: The new normalization branch in check() is silent, so add a
debug log there to trace how incoming operation names are rewritten. In
ListOperations.check(), capture the raw self.operations value before calling
_normalize_operation_name(), then log both the original and normalized values
after normalization so alias/default conversions like topn or empty input are
visible during canvas validation. Keep the logging localized to the check() flow
and use the existing _normalize_operation_name helper to locate the rewrite
path.

In `@test/testcases/test_web_api/test_canvas_app/test_iteration_runtime_unit.py`:
- Around line 254-258: The Message test double currently sets output content
without resolving referenced inputs, so the resume test can pass without proving
the resumed value reached the message body. Update Message._invoke to resolve
placeholders the same way Probe does before calling set_output, then strengthen
the affected assertions in test_iteration_runtime_unit so they verify the
Message content contains the resumed value (for example, the propagated “hello”)
instead of only checking that some message event exists.

In `@test/testcases/test_web_api/test_canvas_app/test_list_operations_unit.py`:
- Around line 194-201: The ListOperationsParam.check coverage only validates the
topN alias normalization and misses the new default-to-nth fallback. Add a small
parametrized test alongside test_topn_operation_alias_normalizes_to_head that
exercises ListOperationsParam.check with None, empty string, and whitespace-only
operations, and assert each case normalizes to nth so the fallback branch stays
covered.

In
`@test/unit_test/api/db/services/test_tenant_model_service_instance_fallback.py`:
- Around line 23-48: The test for _resolve_instance_for_model() only covers the
fallback path where a default instance resolves to a single active tenant
instance. Add assertions for the other non-fallback branches in the same test
module by exercising the zero-active and multi-active cases through
TenantModelInstanceService.get_by_provider_id_and_instance_name and
get_all_by_provider_id, and verify the function fails or returns the expected
error behavior instead of binding "default" incorrectly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: be178c36-ddf1-45b4-b63f-b5c43e9e9ccc

📥 Commits

Reviewing files that changed from the base of the PR and between 9d18f33 and 5a7307b.

⛔ Files ignored due to path filters (2)
  • go.sum is excluded by !**/*.sum
  • uv.lock is excluded by !**/*.lock
📒 Files selected for processing (41)
  • agent/canvas.py
  • agent/component/begin.py
  • agent/component/fillup.py
  • agent/component/list_operations.py
  • agent/sandbox/providers/aliyun_codeinterpreter.py
  • agent/sandbox/tests/test_aliyun_codeinterpreter.py
  • api/db/joint_services/tenant_model_service.py
  • api/utils/validation_utils.py
  • cmd/server_main.go
  • go.mod
  • internal/agent/canvas/interrupt_resume.go
  • internal/agent/canvas/interrupt_resume_test.go
  • internal/agent/canvas/runner.go
  • internal/agent/component/production_chain_fixes_test.go
  • internal/agent/component/switch.go
  • internal/agent/component/switch_test.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/sandbox/aliyun.go
  • internal/agent/tool/keenable.go
  • internal/agent/tool/keenable_test.go
  • internal/agent/tool/registry.go
  • internal/agent/tool/retrieval.go
  • internal/agent/tool/retrieval_nlp.go
  • internal/agent/tool/retrieval_nlp_test.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/service/agent.go
  • internal/service/model_service.go
  • pyproject.toml
  • test/testcases/restful_api/test_datasets.py
  • test/testcases/test_http_api/test_dataset_management/test_delete_datasets.py
  • test/testcases/test_http_api/test_dataset_management/test_list_datasets.py
  • test/testcases/test_http_api/test_dataset_management/test_update_dataset.py
  • test/testcases/test_sdk_api/test_dataset_mangement/test_delete_datasets.py
  • test/testcases/test_sdk_api/test_dataset_mangement/test_list_datasets.py
  • test/testcases/test_web_api/test_canvas_app/test_fillup_unit.py
  • test/testcases/test_web_api/test_canvas_app/test_iteration_runtime_unit.py
  • test/testcases/test_web_api/test_canvas_app/test_list_operations_unit.py
  • test/unit_test/api/db/services/test_tenant_model_service_instance_fallback.py
  • web/src/hooks/use-send-message.ts
  • web/src/pages/agent/chat/use-send-agent-message.ts

Comment thread agent/canvas.py Resolved
Comment thread agent/component/fillup.py Resolved
Comment thread api/utils/validation_utils.py Resolved
Comment thread internal/agent/canvas/runner.go Resolved
Comment thread internal/agent/tool/registry.go Resolved
Comment thread internal/agent/tool/retrieval_nlp.go Resolved
Comment thread internal/handler/agent.go Resolved
Comment thread web/src/hooks/use-send-message.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
internal/agent/tool/retrieval_nlp.go (1)

76-80: 📐 Maintainability & Code Quality | 🟠 Major

Remove unused kbDAO field and knowledgebaseLookup interface.

The kbDAO field is initialized in the constructors (lines 88, 102) but never used within internal/agent/tool/retrieval_nlp.go. The knowledgebaseLookup interface is defined but has no implementations or callers across the entire codebase. Since the tenant-widening logic it supported was removed, this code is dead.

Delete the following:

  • The kbDAO knowledgebaseLookup field in the ToolNLP struct (line 76).
  • The knowledgebaseLookup interface definition (lines 79-80).
  • The kbDAO: dao.NewKnowledgebaseDAO() assignments in both constructors (lines 88, 102).
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/agent/tool/retrieval_nlp.go` around lines 76 - 80, The ToolNLP code
still carries dead knowledgebase lookup plumbing that is no longer used: remove
the kbDAO field from ToolNLP, delete the knowledgebaseLookup interface, and drop
the kbDAO: dao.NewKnowledgebaseDAO() initialization from both constructors so
retrieval_nlp.go only keeps the dependencies it actually uses.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/agent/tool/registry.go`:
- Around line 120-126: The Keenable tool constructor path in the registry is
accepting api_key without validation, so missing or non-string values become an
empty key and create a misconfigured tool. Update the parameter handling in the
registry logic around apiKey and NewKeenableToolWithAPIKey to explicitly verify
api_key exists, is a non-empty string, and reject invalid configs before
constructing the tool. Keep the existing node-level param check intact, but
return a clear error for bad api_key values rather than silently building a
keyless tool.

---

Outside diff comments:
In `@internal/agent/tool/retrieval_nlp.go`:
- Around line 76-80: The ToolNLP code still carries dead knowledgebase lookup
plumbing that is no longer used: remove the kbDAO field from ToolNLP, delete the
knowledgebaseLookup interface, and drop the kbDAO: dao.NewKnowledgebaseDAO()
initialization from both constructors so retrieval_nlp.go only keeps the
dependencies it actually uses.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

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

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 6050a0b7-b49c-491b-ba35-18fc328d6f1c

📥 Commits

Reviewing files that changed from the base of the PR and between 2af3b95 and 3ed10c4.

📒 Files selected for processing (19)
  • agent/canvas.py
  • agent/component/fillup.py
  • api/utils/validation_utils.py
  • internal/agent/canvas/runner.go
  • internal/agent/component/production_chain_fixes_test.go
  • internal/agent/component/switch_test.go
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/tool/keenable.go
  • internal/agent/tool/keenable_test.go
  • internal/agent/tool/registry.go
  • internal/agent/tool/registry_test.go
  • internal/agent/tool/retrieval_nlp.go
  • internal/agent/tool/retrieval_nlp_test.go
  • internal/handler/agent.go
  • internal/handler/agent_test.go
  • internal/handler/agent_wait_for_user_test.go
  • internal/service/agent.go
  • test/testcases/test_web_api/test_canvas_app/test_fillup_unit.py
  • web/src/hooks/use-send-message.ts
🚧 Files skipped from review as they are similar to previous changes (12)
  • internal/agent/canvas/runner.go
  • internal/agent/component/switch_test.go
  • test/testcases/test_web_api/test_canvas_app/test_fillup_unit.py
  • internal/agent/component/universe_a_wrappers.go
  • internal/agent/tool/keenable_test.go
  • agent/component/fillup.py
  • internal/handler/agent_test.go
  • agent/canvas.py
  • api/utils/validation_utils.py
  • internal/handler/agent.go
  • internal/service/agent.go
  • web/src/hooks/use-send-message.ts

Comment thread internal/agent/tool/registry.go Resolved
@codecov

codecov Bot commented Jun 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.16%. Comparing base (9d18f33) to head (398db97).

Additional details and impacted files
@@           Coverage Diff           @@
##             main   #16396   +/-   ##
=======================================
  Coverage   93.16%   93.16%           
=======================================
  Files          10       10           
  Lines         717      717           
  Branches      118      118           
=======================================
  Hits          668      668           
  Misses         29       29           
  Partials       20       20           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@yuzhichang
yuzhichang merged commit 70546ea into infiniflow:main Jun 26, 2026
3 checks passed
yuzhichang added a commit that referenced this pull request Jun 29, 2026
…#16396)

Ported retrieval node, added Keenable web search tool
- [x] New Feature (non-breaking change which adds functionality)
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).
yuzhichang added a commit to ondery/ragflow that referenced this pull request Jul 1, 2026
…sion/user + input/output to Langfuse for agent runs

Rebuilt on current upstream/main after force-push; cherry-pick of the 7
PR-original commits collapsed into a single net diff to avoid conflicts
with intervening commits pulled in by repeated merges of upstream/main.

Original PR work (commits dropped during rebuild because their content
already lives on upstream/main or was a merge of upstream/main):
  c7339ae Enhance LLMService with token usage reporting
  0266cf0 Implement token usage tracking and Langfuse integration
  ab2b267 Include session_id in run_kwargs
  8bf937c Implement token usage tracking in chat model
  c955988 Enhance token tracking with context variables and functions
  3e88ed5 fix(agent): address CodeRabbit review on token usage tracking
  74b8c8c fix(agent): address CodeRabbit follow-up review

Forced-upstream duplicates dropped (already merged to main):
  70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405),
  730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410),
  c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436),
  ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609),
  2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985),
  bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426),
  4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145)

Plus 18 'Merge branch main into main' commits dropped (polluted topology).

Co-authored-by: yzc <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. size:XL This PR changes 500-999 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant