From d074ec7b0b63903f117543e09deb31f5f3d19ecb Mon Sep 17 00:00:00 2001 From: Jundong Zhang <673235694@qq.com> Date: Sat, 10 Oct 2026 10:25:40 +0800 Subject: [PATCH] fix(websearch): return results for non-webpage Metaso scopes (#4010) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(websearch): return results for non-webpage Metaso scopes Metaso 把结果放在与 scope 同名的键下(webpage→webpages、scholar→scholars…), 而 Search() 只读 response.Webpages,导致 extra_config.scope 配成 document / scholar / podcast / video / image 时永远返回 0 条。validMetasoScopes 与 website-docs/03-features/11-web-search.md 都把 6 个 scope 列为可用,属于 "文档承诺了、代码没实现"。 - 新增 itemsForScope:按 scope 选取对应结果数组,未知 scope 回退到首个非空数组并告警 - 新增 location():依次回退 link → url → imageUrl。image 条目只有 imageUrl, 只认 link 会让这些条目在 agent 侧的 URL 校验里被全部丢弃 - parseMetasoDate 补 "2006年01月02日"、"2006/01/02" 两种实测格式 - metasoWebpage 只建模真正会被读取的字段:多声明一个类型不符的键,整次搜索就会因 反序列化失败而返回 0 条。补 TestMetasoProviderToleratesUnmodelledFields 锁死这一点 - 日志补 scope= / array= 维度,便于区分"provider 没结果"与"读错了数组" - 文档补充结果数组键名与 scope 的对应关系 测试:go test ./internal/infrastructure/web_search/... -count=1 * fix(websearch): scope Metaso result arrays only Follow-up to the review. This change now does exactly one thing: read the result array whose key matches the configured scope, and log which array was read. Removed — all of it added by the original commit, none of it supported by a captured response: - the `url` and `imageUrl` fields on metasoWebpage, and the location() helper. Neither key appears in the document, scholar or image responses, and a real image entry carries no `link` at all. - the fallback to the first non-empty array when the target array is empty. Real responses key each array strictly by scope, so for any scope that passed validation this branch cannot be reached. - the unknown-scope warning. NewMetasoProvider rejects unknown scopes before a provider is ever constructed. - the "2006年01月02日" and "2006/01/02" date layouts. Neither format appears in any captured response, so parseMetasoDate is back to main. The accompanying TestMetasoParseDate was introduced with them and is removed too. Tests: the TestMetasoProviderSearch fixture now returns `scholars` for a scholar-scoped request — the previous fixture answered `webpages`, which is what let the bug through. The document and scholar cases in TestMetasoProviderScopeArrays are built from sanitised real responses, and two new cases pin that `url`/`imageUrl` stay undeclared and that image scope returns entries with an empty URL. Comments are English again, matching the rest of the file. The image scope limitation is unchanged from main and is now documented: image entries carry no `link`, so the provider produces an empty URL and the agent drops the result. * style(websearch): drop added comments and revert doc paragraph The PR is scoped to reading the result array that matches the scope, so the extra doc comment blocks and the website-docs paragraph are noise. Remove the 12 comment lines added to metaso.go and the 29 added to metaso_test.go, and restore website-docs/03-features/11-web-search.md to main (zero diff). No behaviour change. --- internal/infrastructure/web_search/metaso.go | 33 +++- .../infrastructure/web_search/metaso_test.go | 154 +++++++++++++++++- 2 files changed, 181 insertions(+), 6 deletions(-) diff --git a/internal/infrastructure/web_search/metaso.go b/internal/infrastructure/web_search/metaso.go index e3fa5f05..2cee9de6 100644 --- a/internal/infrastructure/web_search/metaso.go +++ b/internal/infrastructure/web_search/metaso.go @@ -116,8 +116,9 @@ func (p *MetasoProvider) Search(ctx context.Context, query string, maxResults in if err := json.Unmarshal(respBody, &response); err != nil { return nil, fmt.Errorf("failed to unmarshal Metaso response: %w", err) } - results := make([]*types.WebSearchResult, 0, len(response.Webpages)) - for _, item := range response.Webpages { + items, arrayName := response.itemsForScope(p.scope) + results := make([]*types.WebSearchResult, 0, len(items)) + for _, item := range items { if strings.TrimSpace(item.Title) == "" && strings.TrimSpace(item.Link) == "" { continue } @@ -136,7 +137,8 @@ func (p *MetasoProvider) Search(ctx context.Context, query string, maxResults in break } } - logger.Infof(ctx, "[WebSearch][Metaso] returned %d results", len(results)) + logger.Infof(ctx, "[WebSearch][Metaso] scope=%s array=%s returned=%d", + p.scope, arrayName, len(results)) return results, nil } @@ -194,7 +196,30 @@ type metasoSearchRequest struct { } type metasoSearchResponse struct { - Webpages []metasoWebpage `json:"webpages"` + Webpages []metasoWebpage `json:"webpages"` + Documents []metasoWebpage `json:"documents"` + Scholars []metasoWebpage `json:"scholars"` + Podcasts []metasoWebpage `json:"podcasts"` + Videos []metasoWebpage `json:"videos"` + Images []metasoWebpage `json:"images"` +} + +func (r metasoSearchResponse) itemsForScope(scope string) ([]metasoWebpage, string) { + switch scope { + case "document": + return r.Documents, "documents" + case "scholar": + return r.Scholars, "scholars" + case "podcast": + return r.Podcasts, "podcasts" + case "video": + return r.Videos, "videos" + case "image": + return r.Images, "images" + case "webpage": + return r.Webpages, "webpages" + } + return nil, "webpages" } type metasoWebpage struct { diff --git a/internal/infrastructure/web_search/metaso_test.go b/internal/infrastructure/web_search/metaso_test.go index 0ceed0bf..4d88fd8e 100644 --- a/internal/infrastructure/web_search/metaso_test.go +++ b/internal/infrastructure/web_search/metaso_test.go @@ -31,8 +31,10 @@ func TestMetasoProviderSearch(t *testing.T) { t.Fatalf("unexpected content options: %+v", request) } w.Header().Set("Content-Type", "application/json") - _, _ = w.Write([]byte(`{"webpages":[ - {"title":"First","link":"https://example.com/1","summary":"Summary","snippet":"Snippet","date":"2026-08-09"}, + _, _ = w.Write([]byte(`{"credits":3,"searchParameters":{"q":"WeKnora","scope":"scholar"}, + "total":3,"scholars":[ + {"title":"First","link":"https://example.com/1","score":"high","position":1, + "summary":"Summary","snippet":"Snippet","date":"2026-08-09","authors":["Author"]}, {"title":"Second","link":"https://example.com/2","snippet":"Fallback snippet","date":"invalid"}, {"title":"Third","link":"https://example.com/3","snippet":"must be capped"} ]}`)) @@ -61,6 +63,154 @@ func TestMetasoProviderSearch(t *testing.T) { } } +func TestMetasoProviderScopeArrays(t *testing.T) { + fixtures := map[string]struct { + payload string + want int + }{ + "webpage": { + payload: `{"total":1,"webpages":[{"title":"W","link":"https://example.com/w", + "score":"high","position":1,"summary":"网页摘要","date":"2026-08-09"}]}`, + want: 1, + }, + "document": { + payload: `{"credits":3,"searchParameters":{"q":"1","scope":"document"},"total":15, + "documents":[ + {"title":"文档标题一","link":"https://example.com/doc/1","score":"high", + "snippet":"文档片段一","position":1,"authors":["作者甲"]}, + {"title":"文档标题二","link":"https://example.com/doc/2 with space","score":"medium", + "snippet":"文档片段二","position":2,"authors":["作者乙"]} + ]}`, + want: 2, + }, + "scholar": { + payload: `{"credits":3,"searchParameters":{"q":"1","scope":"scholar"},"total":43, + "scholars":[ + {"title":"学术标题一","link":"https://example.com/paper?q=1","score":"high", + "snippet":"学术片段一","position":1,"authors":["作者甲"],"date":"2012-10-15"}, + {"title":"学术标题二","link":"https://example.com/paper?q=2","score":"medium", + "snippet":"","position":2,"date":"2011-10-05"} + ]}`, + want: 2, + }, + "podcast": { + payload: `{"total":1,"podcasts":[{"title":"P","link":"https://example.com/p", + "score":"medium","position":1,"snippet":"播客片段","authors":["主播"], + "date":"2022-10-13","duration":"299"}]}`, + want: 1, + }, + "video": { + payload: `{"total":1,"videos":[{"title":"V","link":"https://example.com/v", + "score":"medium","position":1,"snippet":"视频片段","authors":["UP"], + "date":"2024-06-17","duration":"497","coverImage":"https://example.com/v.jpg"}]}`, + want: 1, + }, + } + for scope, fixture := range fixtures { + t.Run(scope, func(t *testing.T) { + body := fixture.payload + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(body)) + })) + defer server.Close() + + metaso := &MetasoProvider{ + client: server.Client(), baseURL: server.URL, + apiKey: "mk-test", scope: scope, + } + results, err := metaso.Search(context.Background(), "q", 5, true) + if err != nil { + t.Fatal(err) + } + if len(results) != fixture.want { + t.Fatalf("scope=%s len(results) = %d, want %d", scope, len(results), fixture.want) + } + if results[0].Title == "" { + t.Fatalf("scope=%s title is empty", scope) + } + if results[0].URL == "" { + t.Fatalf("scope=%s URL is empty", scope) + } + if results[0].Snippet == "" { + t.Fatalf("scope=%s snippet is empty", scope) + } + }) + } +} + +func TestMetasoProviderImageScopeHasNoLink(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"credits":3,"searchParameters":{"q":"1","scope":"image"},"total":31, + "images":[{"title":"图片一","score":"low","position":1, + "imageUrl":"https://example.com/i.jpg","imageWidth":800,"imageHeight":600}]}`)) + })) + defer server.Close() + + metaso := &MetasoProvider{ + client: server.Client(), baseURL: server.URL, + apiKey: "mk-test", scope: "image", + } + results, err := metaso.Search(context.Background(), "q", 5, false) + if err != nil { + t.Fatal(err) + } + if len(results) != 1 { + t.Fatalf("len(results) = %d, want 1", len(results)) + } + if results[0].Title == "" { + t.Fatalf("title is empty: %+v", results[0]) + } + if results[0].URL != "" { + t.Fatalf("URL = %q, want empty: image entries have no link", results[0].URL) + } +} + +func TestMetasoProviderToleratesNonStringURLFields(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"total":1,"webpages":[{"title":"W","link":"https://example.com/w", + "snippet":"片段","url":{"href":"https://example.com/obj"}, + "imageUrl":{"href":"https://example.com/img"}}]}`)) + })) + defer server.Close() + + metaso := &MetasoProvider{ + client: server.Client(), baseURL: server.URL, + apiKey: "mk-test", scope: "webpage", + } + results, err := metaso.Search(context.Background(), "q", 5, false) + if err != nil { + t.Fatalf("non-string url fields must not fail the search: %v", err) + } + if len(results) != 1 || results[0].URL != "https://example.com/w" { + t.Fatalf("results = %+v, want one result for https://example.com/w", results) + } +} + +func TestMetasoProviderToleratesUnmodelledFields(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"total":3,"pageSize":10,"webpages":[ + {"title":"W","link":"https://example.com/w","snippet":"片段", + "score":123,"position":"1","authors":null,"unknownNested":{"a":[1,2]}}]}`)) + })) + defer server.Close() + + metaso := &MetasoProvider{ + client: server.Client(), baseURL: server.URL, + apiKey: "mk-test", scope: "webpage", + } + results, err := metaso.Search(context.Background(), "q", 5, false) + if err != nil { + t.Fatalf("unmodelled fields must not fail the search: %v", err) + } + if len(results) != 1 || results[0].URL != "https://example.com/w" { + t.Fatalf("results = %+v, want one result for https://example.com/w", results) + } +} + func TestValidateMetasoParameters(t *testing.T) { if err := ValidateMetasoParameters(types.WebSearchProviderParameters{}); err == nil { t.Fatal("expected missing API key error")