Repository navigation
fix(go-agent): align Go DuckDuckGo component with canvas input form - #16775
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughDuckDuckGo now performs general HTML and news searches, returning normalized result envelopes. A Canvas component adapts these results into ChangesDuckDuckGo scraping tool and canvas integration
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant Canvas
participant duckDuckGoComponent
participant DuckDuckGoTool
participant DuckDuckGoEndpoints
Canvas->>duckDuckGoComponent: Invoke query, channel, top_n
duckDuckGoComponent->>DuckDuckGoTool: InvokableRun normalized JSON
DuckDuckGoTool->>DuckDuckGoEndpoints: Fetch search results
DuckDuckGoEndpoints-->>DuckDuckGoTool: Return HTML or news JSON
DuckDuckGoTool-->>duckDuckGoComponent: Return results envelope
duckDuckGoComponent-->>Canvas: Return formalized_content and json
Suggested labels: Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
internal/agent/component/duckduckgo_component_test.go (1)
28-37: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd tests for the Invoke error paths.
The
Invokemethod has two untested error branches: whenInvokableRunreturns an error with a parseable envelope (returns_ERRORin the output map), and when it returns an error without one (returns a wrapped Go error). A configurable fake invoker would cover both.♻️ Suggested error path tests
type fakeDuckDuckGoInvoker struct { args map[string]any } func (f *fakeDuckDuckGoInvoker) InvokableRun(_ context.Context, argsJSON string, _ ...einotool.Option) (string, error) { if err := json.Unmarshal([]byte(argsJSON), &f.args); err != nil { return "", err } return `{"results":[{"title":"RAGFlow","url":"https://ragflow.io","body":"Open source RAG engine"}]}`, nil } + +type fakeDuckDuckGoErrorInvoker struct { + errJSON string + err error +} + +func (f *fakeDuckDuckGoErrorInvoker) InvokableRun(_ context.Context, _ string, _ ...einotool.Option) (string, error) { + return f.errJSON, f.err +} + +func TestDuckDuckGo_InvokeErrorWithEnvelopeReturnsErrorInOutput(t *testing.T) { + t.Parallel() + c := newDuckDuckGoComponentWithInvoker(&fakeDuckDuckGoErrorInvoker{ + errJSON: `{"_ERROR":"upstream failure"}`, + err: fmt.Errorf("upstream failure"), + }) + out, err := c.Invoke(context.Background(), map[string]any{"query": "test"}) + if err != nil { + t.Fatalf("Invoke should return nil error when envelope has _ERROR, got: %v", err) + } + if out["_ERROR"] == nil { + t.Fatal("output missing _ERROR") + } + if got := out["formalized_content"]; got != "" { + t.Errorf("formalized_content = %v, want empty", got) + } +} + +func TestDuckDuckGo_InvokeErrorWithoutEnvelopeReturnsGoError(t *testing.T) { + t.Parallel() + c := newDuckDuckGoComponentWithInvoker(&fakeDuckDuckGoErrorInvoker{ + err: fmt.Errorf("network failure"), + }) + _, err := c.Invoke(context.Background(), map[string]any{"query": "test"}) + if err == nil { + t.Fatal("Invoke should return error when no envelope and err != nil") + } +}🤖 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/component/duckduckgo_component_test.go` around lines 28 - 37, Add tests for duckduckgo_component_test.go that exercise the two Invoke error branches in the DuckDuckGo component. Make fakeDuckDuckGoInvoker configurable so InvokableRun can return either a parseable error envelope or a plain Go error, then assert the Invoke path returns _ERROR for the envelope case and a wrapped error for the non-envelope case. Use the existing fakeDuckDuckGoInvoker and the component’s Invoke/InvokableRun flow to locate the code.internal/agent/tool/duckduckgo.go (4)
292-294: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
io.Readerinstead of an inline anonymous interface.
iois already imported; the anonymousinterface { Read(...) }is equivalent toio.Readerand just obscures the signature.♻️ Proposed change
-func parseDuckDuckGoHTML(body interface { - Read(p []byte) (int, error) -}, channel string, topN int) ([]duckduckgoResult, error) { +func parseDuckDuckGoHTML(body io.Reader, channel string, topN int) ([]duckduckgoResult, error) {🤖 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/duckduckgo.go` around lines 292 - 294, The parseDuckDuckGoHTML function currently uses an inline Read-only anonymous interface, which is equivalent to io.Reader and makes the signature harder to read. Update parseDuckDuckGoHTML to accept io.Reader directly, and keep the rest of the parsing logic unchanged; io is already imported, so this is just a signature cleanup for clarity.
302-307: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚖️ Poor tradeoffRemove the unreachable news fallback in
parseDuckDuckGoHTML.
InvokableRunsendschannel == newstorunNewsSearchbefore this parser runs, so theduckduckgoChannelNewsbranch here — andextractDuckDuckGoNewsResults,extractDuckDuckGoNewsResult,dedupeDuckDuckGoResults— is dead code. Delete it or add a real HTML news fallback.🤖 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/duckduckgo.go` around lines 302 - 307, Remove the dead news-specific fallback from parseDuckDuckGoHTML since InvokableRun already routes news queries through runNewsSearch before this parser is reached. Delete the duckduckgoChannelNews branch and any now-unused news extraction helpers it only serves, or replace it with a real HTML news fallback if that path is meant to be supported. Use parseDuckDuckGoHTML, InvokableRun, and the duckduckgoChannelNews handling to locate the code.
515-520: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse the builtin
minhere
internal/agent/tool/duckduckgo.go:515— this helper is redundant and shadows the predeclaredminfor the whole package. Replace the two call sites with the builtin and drop this function.🤖 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/duckduckgo.go` around lines 515 - 520, The custom min helper in duckduckgo.go is redundant and shadows the predeclared min across the package. Update the two call sites that currently use min to call the builtin min directly, then remove the local min function entirely from the duckduckgo-related code.
494-504: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick winUse
html.UnescapeStringhere.htmlUnescapeonly decodes a small fixed table;golang.org/x/net/htmlalready exportsUnescapeString, which handles numeric and additional named entities like’and .🤖 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/duckduckgo.go` around lines 494 - 504, The htmlUnescape helper only handles a small hardcoded entity map, so update it to use the existing html.UnescapeString behavior instead. In internal/agent/tool/duckduckgo.go, replace the custom strings.NewReplacer logic inside htmlUnescape with the standard unescape function from golang.org/x/net/html so it correctly handles numeric and additional named entities like &`#8217`; and .
🤖 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/duckduckgo_test.go`:
- Around line 149-162: In the HTTP handler used by duckduckgo_test.go, replace
the direct test termination calls in the handler goroutine with non-fatal
reporting so the parent test can fail reliably. Update the "/news.js" case and
the default branch in the handler to use t.Errorf for unexpected vqd or path
values, then return immediately after logging the error. Keep the changes
localized to the handler logic around the news.js response and the default
switch branch.
---
Nitpick comments:
In `@internal/agent/component/duckduckgo_component_test.go`:
- Around line 28-37: Add tests for duckduckgo_component_test.go that exercise
the two Invoke error branches in the DuckDuckGo component. Make
fakeDuckDuckGoInvoker configurable so InvokableRun can return either a parseable
error envelope or a plain Go error, then assert the Invoke path returns _ERROR
for the envelope case and a wrapped error for the non-envelope case. Use the
existing fakeDuckDuckGoInvoker and the component’s Invoke/InvokableRun flow to
locate the code.
In `@internal/agent/tool/duckduckgo.go`:
- Around line 292-294: The parseDuckDuckGoHTML function currently uses an inline
Read-only anonymous interface, which is equivalent to io.Reader and makes the
signature harder to read. Update parseDuckDuckGoHTML to accept io.Reader
directly, and keep the rest of the parsing logic unchanged; io is already
imported, so this is just a signature cleanup for clarity.
- Around line 302-307: Remove the dead news-specific fallback from
parseDuckDuckGoHTML since InvokableRun already routes news queries through
runNewsSearch before this parser is reached. Delete the duckduckgoChannelNews
branch and any now-unused news extraction helpers it only serves, or replace it
with a real HTML news fallback if that path is meant to be supported. Use
parseDuckDuckGoHTML, InvokableRun, and the duckduckgoChannelNews handling to
locate the code.
- Around line 515-520: The custom min helper in duckduckgo.go is redundant and
shadows the predeclared min across the package. Update the two call sites that
currently use min to call the builtin min directly, then remove the local min
function entirely from the duckduckgo-related code.
- Around line 494-504: The htmlUnescape helper only handles a small hardcoded
entity map, so update it to use the existing html.UnescapeString behavior
instead. In internal/agent/tool/duckduckgo.go, replace the custom
strings.NewReplacer logic inside htmlUnescape with the standard unescape
function from golang.org/x/net/html so it correctly handles numeric and
additional named entities like &`#8217`; and .
🪄 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: f08d8698-1a08-4cef-a97e-8ac86e52ae16
📒 Files selected for processing (6)
internal/agent/component/duckduckgo_component_test.gointernal/agent/component/fixture_stubs.gointernal/agent/component/universe_a_wrappers.gointernal/agent/component/verify_p1_test.gointernal/agent/tool/duckduckgo.gointernal/agent/tool/duckduckgo_test.go
| case "/news.js": | ||
| if got := r.URL.Query().Get("vqd"); got != "test-vqd-1" { | ||
| t.Fatalf("vqd = %q, want test-vqd-1", got) | ||
| } | ||
| w.Header().Set("Content-Type", "application/json") | ||
| _, _ = w.Write([]byte(`{ | ||
| "results": [ | ||
| {"title":"Story One","url":"https://news.example.com/story-1","excerpt":"Breaking update one"}, | ||
| {"title":"Story Two","url":"https://news.example.com/story-2","excerpt":"Breaking & update two"} | ||
| ] | ||
| }`)) | ||
| default: | ||
| t.Fatalf("unexpected path: %s", r.URL.Path) | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win
Use t.Errorf (+ return) instead of t.Fatalf inside the HTTP handler.
Lines 151 and 161 call t.Fatalf from the server's handler goroutine. t.Fatalf calls runtime.Goexit() on that goroutine only, so it may not fail the test reliably. Use t.Errorf and return.
💚 Proposed change
case "/news.js":
if got := r.URL.Query().Get("vqd"); got != "test-vqd-1" {
- t.Fatalf("vqd = %q, want test-vqd-1", got)
+ t.Errorf("vqd = %q, want test-vqd-1", got)
+ return
}
@@
default:
- t.Fatalf("unexpected path: %s", r.URL.Path)
+ t.Errorf("unexpected path: %s", r.URL.Path)
}Based on learnings: inside an http.HandlerFunc handler goroutine, use t.Errorf instead of t.Fatalf since t.Fatalf's runtime.Goexit() only affects the handler goroutine.
📝 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.
| case "/news.js": | |
| if got := r.URL.Query().Get("vqd"); got != "test-vqd-1" { | |
| t.Fatalf("vqd = %q, want test-vqd-1", got) | |
| } | |
| w.Header().Set("Content-Type", "application/json") | |
| _, _ = w.Write([]byte(`{ | |
| "results": [ | |
| {"title":"Story One","url":"https://news.example.com/story-1","excerpt":"Breaking update one"}, | |
| {"title":"Story Two","url":"https://news.example.com/story-2","excerpt":"Breaking & update two"} | |
| ] | |
| }`)) | |
| default: | |
| t.Fatalf("unexpected path: %s", r.URL.Path) | |
| } | |
| case "/news.js": | |
| if got := r.URL.Query().Get("vqd"); got != "test-vqd-1" { | |
| t.Errorf("vqd = %q, want test-vqd-1", got) | |
| return | |
| } | |
| w.Header().Set("Content-Type", "application/json") | |
| _, _ = w.Write([]byte(`{ | |
| "results": [ | |
| {"title":"Story One","url":"https://news.example.com/story-1","excerpt":"Breaking update one"}, | |
| {"title":"Story Two","url":"https://news.example.com/story-2","excerpt":"Breaking & update two"} | |
| ] | |
| }`)) | |
| default: | |
| t.Errorf("unexpected path: %s", r.URL.Path) | |
| } |
🤖 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/duckduckgo_test.go` around lines 149 - 162, In the HTTP
handler used by duckduckgo_test.go, replace the direct test termination calls in
the handler goroutine with non-fatal reporting so the parent test can fail
reliably. Update the "/news.js" case and the default branch in the handler to
use t.Errorf for unexpected vqd or path values, then return immediately after
logging the error. Keep the changes localized to the handler logic around the
news.js response and the default switch branch.
Source: Learnings
| if got := r.URL.Path; got != "/" { | ||
| // keep old behavior impossible to hit if search endpoint override works incorrectly | ||
| } | ||
| if got := r.URL.Query().Get("o"); got != "" { | ||
| t.Fatalf("o = %q, want empty for general search html endpoint", got) | ||
| } |
There was a problem hiding this comment.
📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win
No-op if block and handler-goroutine t.Fatalf.
Lines 199-201 are a dead if with an empty body — drop it. Line 203's t.Fatalf also runs on the handler goroutine; prefer t.Errorf + return for reliable failure.
💚 Proposed change
- if got := r.URL.Path; got != "/" {
- // keep old behavior impossible to hit if search endpoint override works incorrectly
- }
if got := r.URL.Query().Get("o"); got != "" {
- t.Fatalf("o = %q, want empty for general search html endpoint", got)
+ t.Errorf("o = %q, want empty for general search html endpoint", got)
+ return
}Based on learnings: inside an http.HandlerFunc handler goroutine, use t.Errorf instead of t.Fatalf.
📝 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.
| if got := r.URL.Path; got != "/" { | |
| // keep old behavior impossible to hit if search endpoint override works incorrectly | |
| } | |
| if got := r.URL.Query().Get("o"); got != "" { | |
| t.Fatalf("o = %q, want empty for general search html endpoint", got) | |
| } | |
| if got := r.URL.Query().Get("o"); got != "" { | |
| t.Errorf("o = %q, want empty for general search html endpoint", got) | |
| return | |
| } |
Source: Learnings
There was a problem hiding this comment.
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/duckduckgo.go (1)
306-324: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick winSkip sponsored DuckDuckGo cards in general results
internal/agent/tool/duckduckgo.go:306-324—result--adcards still matchhasClassToken(n, "result"), so they can be parsed and returned alongside organic results. Filter out ad cards before appending.🤖 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/duckduckgo.go` around lines 306 - 324, The general DuckDuckGo result walker is still collecting sponsored cards because `extractDuckDuckGoGeneralResults` matches any node with the `result` class. Update this function to explicitly exclude ad cards (for example, nodes with `result--ad`) before calling `extractDuckDuckGoGeneralResult` and appending to `results`, while keeping the existing topN limit and traversal behavior intact.
🧹 Nitpick comments (1)
internal/agent/tool/duckduckgo.go (1)
293-304: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
io.Readerinstead of an inline anonymous interface.The anonymous
interface { Read(p []byte) (int, error) }is exactlyio.Reader;xhtml.Parsealready acceptsio.Reader, so this adds noise without adding constraint.♻️ Proposed simplification
-func parseDuckDuckGoHTML(body interface { - Read(p []byte) (int, error) -}, topN int) ([]duckduckgoResult, error) { +func parseDuckDuckGoHTML(body io.Reader, topN int) ([]duckduckgoResult, error) {(ensure
iois imported)🤖 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/duckduckgo.go` around lines 293 - 304, `parseDuckDuckGoHTML` is using an inline reader interface that duplicates `io.Reader`; simplify the function signature to take `io.Reader` directly, since `xhtml.Parse` already works with that type. Update the `duckduckgo.go` imports to include `io` and remove the anonymous interface from `parseDuckDuckGoHTML` so the type constraint is clearer and less noisy.
🤖 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.
Outside diff comments:
In `@internal/agent/tool/duckduckgo.go`:
- Around line 306-324: The general DuckDuckGo result walker is still collecting
sponsored cards because `extractDuckDuckGoGeneralResults` matches any node with
the `result` class. Update this function to explicitly exclude ad cards (for
example, nodes with `result--ad`) before calling
`extractDuckDuckGoGeneralResult` and appending to `results`, while keeping the
existing topN limit and traversal behavior intact.
---
Nitpick comments:
In `@internal/agent/tool/duckduckgo.go`:
- Around line 293-304: `parseDuckDuckGoHTML` is using an inline reader interface
that duplicates `io.Reader`; simplify the function signature to take `io.Reader`
directly, since `xhtml.Parse` already works with that type. Update the
`duckduckgo.go` imports to include `io` and remove the anonymous interface from
`parseDuckDuckGoHTML` so the type constraint is clearer and less noisy.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 163bfe5d-53fd-43b4-8d2c-fcfdd9f159c9
📒 Files selected for processing (1)
internal/agent/tool/duckduckgo.go
Summary
DuckDuckGocanvas component and restore its dynamic input form metadataquery,channel, andtop_nvqdtoken before callingnews.js, and add targeted regression testsTesting
Passed:
bash build.sh --test ./internal/agent/tool/... -run 'DuckDuckGo'bash build.sh --test ./internal/agent/component/... -run 'DuckDuckGo|TestVerifyRegistration_P1'bash build.sh --test ./internal/agent/component/... -run 'DuckDuckGo'Not run: