fix(web_fetch): address review follow-ups for structured fetch results

Restore HTTP-only 15s pipeline fetching, reject SPA shell pages when
browser rendering fails, surface per-URL failure fields in the UI, and
keep structured model output when all URLs fail.
main
wizardchen 2026-07-28 22:14:08 +08:00 committed by lyingbug
parent 75a2eabe20
commit b581094c7b
10 changed files with 205 additions and 23 deletions

View File

@ -3413,6 +3413,12 @@ export default {
collapseRaw: 'Collapse original',
expandRaw: 'Expand original',
noWebContent: 'No web content fetched',
webFetchStatusSuccess: 'Fetched',
webFetchStatusFailed: 'Failed',
webFetchStatusSkipped: 'Skipped',
webFetchErrorCode: 'Error code',
webFetchRetryable: 'Retryable',
webFetchSummaryFailed: 'Summary failed',
lengthChars: '{value} characters',
lengthThousands: '{value}k characters',
lengthTenThousands: '{value} ten-thousand characters',

View File

@ -1092,6 +1092,12 @@ export default {
collapseRaw: "收起原文",
expandRaw: "展开原文",
noWebContent: "未获取到网页内容",
webFetchStatusSuccess: "抓取成功",
webFetchStatusFailed: "抓取失败",
webFetchStatusSkipped: "已跳过",
webFetchErrorCode: "错误码",
webFetchRetryable: "可重试",
webFetchSummaryFailed: "摘要失败",
lengthChars: "{value} 字",
lengthThousands: "{value} 千字",
lengthTenThousands: "{value} 万字",

View File

@ -198,10 +198,18 @@ export interface WebSearchResultsData {
export interface WebFetchResultItem {
url: string;
prompt?: string;
status?: 'success' | 'failed' | 'skipped';
retryable?: boolean;
error_code?: string;
error_message?: string;
summary?: string;
summary_status?: string;
summary_error_code?: string;
summary_error_message?: string;
raw_content?: string;
content_length?: number;
method?: string;
/** @deprecated use error_message */
error?: string;
}
@ -210,6 +218,10 @@ export interface WebFetchResultsData {
display_type: 'web_fetch_results';
results: WebFetchResultItem[];
count?: number;
successful_count?: number;
failed_count?: number;
skipped_count?: number;
all_failed?: boolean;
}
// Grep knowledge aggregation item (legacy, grouped by knowledge_id)

View File

@ -22,7 +22,12 @@
<span v-else class="result-domain">{{ $t('chat.unknownLink') }}</span>
</div>
<div class="result-meta">
<span v-if="item.method" class="meta-pill">{{ formatMethod(item.method) }}</span>
<span
v-if="itemStatus(item)"
class="meta-pill"
:class="statusClass(item)"
>{{ statusLabel(item) }}</span>
<span v-if="item.method" class="meta-pill method">{{ formatMethod(item.method) }}</span>
<span v-if="item.content_length" class="meta-text">{{ $t('chat.contentLengthLabel', { value: formatLength(item.content_length) }) }}</span>
<t-icon
:name="isExpanded(index) ? 'chevron-up' : 'chevron-down'"
@ -51,17 +56,36 @@
</div>
</div>
<div v-if="item.error" class="info-section">
<div v-if="itemError(item)" class="info-section">
<div class="info-section-title error">{{ $t('chat.errorMessageLabel') }}</div>
<div class="full-content error-text">{{ item.error }}</div>
<div v-if="item.error_code" class="info-field">
<span class="field-label">{{ $t('chat.webFetchErrorCode') }}</span>
<span class="field-value">{{ item.error_code }}</span>
</div>
<div v-if="item.retryable !== undefined" class="info-field">
<span class="field-label">{{ $t('chat.webFetchRetryable') }}</span>
<span class="field-value">{{ item.retryable ? $t('common.yes') : $t('common.no') }}</span>
</div>
<div class="full-content error-text">{{ itemError(item) }}</div>
</div>
<div v-else>
<div v-else-if="isSuccessItem(item)">
<div v-if="item.summary" class="info-section">
<div class="info-section-title">{{ $t('chat.summaryLabel') }}</div>
<div class="full-content">{{ item.summary }}</div>
</div>
<div v-else-if="item.summary_status === 'failed'" class="info-section">
<div class="info-section-title error">{{ $t('chat.webFetchSummaryFailed') }}</div>
<div v-if="item.summary_error_code" class="info-field">
<span class="field-label">{{ $t('chat.webFetchErrorCode') }}</span>
<span class="field-value">{{ item.summary_error_code }}</span>
</div>
<div v-if="item.summary_error_message" class="full-content error-text">
{{ item.summary_error_message }}
</div>
</div>
<div v-if="item.raw_content" class="info-section">
<div class="info-section-title">
{{ $t('chat.rawTextLabel') }}
@ -117,6 +141,40 @@ watch(
{ immediate: true }
);
const itemStatus = (item: WebFetchResultItem): string | undefined => item.status;
const isSuccessItem = (item: WebFetchResultItem): boolean => {
return !item.status || item.status === 'success';
};
const itemError = (item: WebFetchResultItem): string => {
return item.error_message || item.error || '';
};
const statusLabel = (item: WebFetchResultItem): string => {
switch (item.status) {
case 'failed':
return t('chat.webFetchStatusFailed');
case 'skipped':
return t('chat.webFetchStatusSkipped');
case 'success':
return t('chat.webFetchStatusSuccess');
default:
return t('chat.webFetchStatusSuccess');
}
};
const statusClass = (item: WebFetchResultItem): string => {
switch (item.status) {
case 'failed':
return 'status-failed';
case 'skipped':
return 'status-skipped';
default:
return 'status-success';
}
};
const toggleCard = (index: number) => {
if (expandedCards.value.has(index)) {
expandedCards.value.delete(index);
@ -224,11 +282,29 @@ const indexKey = (index: number, item: WebFetchResultItem): string => {
align-items: center;
padding: 2px 6px;
border-radius: 999px;
background: rgba(7, 192, 95, 0.08);
color: var(--td-success-color);
font-size: 10px;
font-weight: 600;
line-height: 1.4;
&.status-success {
background: rgba(7, 192, 95, 0.08);
color: var(--td-success-color);
}
&.status-failed {
background: var(--td-error-color-light);
color: var(--td-error-color);
}
&.status-skipped {
background: rgba(0, 0, 0, 0.06);
color: var(--td-text-color-secondary);
}
&.method {
background: rgba(7, 192, 95, 0.08);
color: var(--td-success-color);
}
}
.meta-text {
@ -270,4 +346,3 @@ const indexKey = (index: number, item: WebFetchResultItem): string => {
color: var(--td-error-color);
}
</style>

View File

@ -213,8 +213,8 @@ func buildWebFetchToolResult(ctx context.Context, results []*webFetchItemResult)
}
logger.Infof(ctx, "[Tool][WebFetch] completed success=%d failed=%d skipped=%d", successCount, failedCount, skippedCount)
return &types.ToolResult{
Success: true,
toolResult := &types.ToolResult{
Success: successCount > 0,
Output: builder.String(),
Data: map[string]interface{}{
"results": aggregated,
@ -226,6 +226,10 @@ func buildWebFetchToolResult(ctx context.Context, results []*webFetchItemResult)
"display_type": "web_fetch_results",
},
}
if allFailed {
toolResult.Error = "all page fetches failed"
}
return toolResult
}
func (t *WebFetchTool) processWithLLM(ctx context.Context, item WebFetchItem, content string) (string, error) {
@ -269,7 +273,7 @@ func buildWebFetchOutput(item WebFetchItem, content, summary string, summaryErr
}
func canonicalFetchURL(rawURL string) string {
trimmed := strings.TrimSpace(rawURL)
trimmed := normalizeGitHubURL(strings.TrimSpace(rawURL))
parsedURL, err := url.Parse(trimmed)
if err != nil || parsedURL.Host == "" {
return trimmed

View File

@ -88,7 +88,7 @@ func TestWebFetchToolAllFailuresReturnStructuredFallback(t *testing.T) {
))
require.NoError(t, err)
require.True(t, result.Success, "structured fetch failures must not fail the whole tool call")
require.False(t, result.Success, "all-failed batches should not report tool success")
assert.Equal(t, true, result.Data["all_failed"])
assert.Equal(t, 0, result.Data["successful_count"])
assert.Contains(t, result.Output, "answer from existing web_search titles, URLs, and snippets")
@ -113,6 +113,22 @@ func TestWebFetchToolDeduplicatesURLsWithinBatch(t *testing.T) {
assert.Equal(t, "duplicate_url", items[1]["error_code"])
}
func TestWebFetchToolDeduplicatesGitHubBlobAndRawURLs(t *testing.T) {
const blobURL = "https://github.com/org/repo/blob/main/README.md"
const rawURL = "https://raw.githubusercontent.com/org/repo/main/README.md"
fetcher := newStubWebContentFetcher(map[string]string{rawURL: "readme content"}, nil)
tool := newWebFetchTool(nil, fetcher)
result, err := tool.Execute(context.Background(), webFetchArgs(
WebFetchItem{URL: blobURL, Prompt: "extract facts"},
WebFetchItem{URL: rawURL, Prompt: "extract facts"},
))
require.NoError(t, err)
assert.Equal(t, 1, fetcher.callCount[rawURL]+fetcher.callCount[blobURL])
assert.Equal(t, 1, result.Data["skipped_count"])
}
func newStubWebContentFetcher(contents map[string]string, failures map[string]error) *stubWebContentFetcher {
return &stubWebContentFetcher{
contents: contents,

View File

@ -21,8 +21,9 @@ import (
)
const (
fetchTimeout = 60 * time.Second
maxBodySize = 100 * 1024
fetchTimeout = 60 * time.Second
pipelineFetchTimeout = 15 * time.Second
maxBodySize = 100 * 1024
)
// ErrorCode identifies the stage and class of a fetch failure.
@ -106,16 +107,26 @@ type httpFetchResult struct {
// NewFetcher creates a production fetcher with DNS and redirect SSRF guards.
func NewFetcher() *Fetcher {
return newFetcher(fetchTimeout, renderWithChromium)
}
// NewPipelineFetcher creates an HTTP-only fetcher for the chat pipeline.
// It keeps the pre-refactor 15s timeout and does not launch Chromium.
func NewPipelineFetcher() *Fetcher {
return newFetcher(pipelineFetchTimeout, nil)
}
func newFetcher(timeout time.Duration, renderBrowser func(context.Context, pinnedTarget) (string, error)) *Fetcher {
config := utils.SSRFSafeHTTPClientConfig{
Timeout: fetchTimeout,
Timeout: timeout,
MaxRedirects: 10,
}
fetcher := &Fetcher{
timeout: fetchTimeout,
timeout: timeout,
maxBodySize: maxBodySize,
validateURL: utils.ValidateURLForSSRF,
resolveIPs: lookupPublicDNS,
renderBrowser: renderWithChromium,
renderBrowser: renderBrowser,
}
transport := utils.NewSSRFSafeTransport(config)
transport.DialContext = fetcher.pinnedDialContext()
@ -123,9 +134,9 @@ func NewFetcher() *Fetcher {
return fetcher
}
// FetchURLContent preserves the existing package-level API.
// FetchURLContent preserves the existing package-level API for the chat pipeline.
func FetchURLContent(ctx context.Context, rawURL string) (string, error) {
return NewFetcher().Fetch(ctx, rawURL)
return NewPipelineFetcher().Fetch(ctx, rawURL)
}
// Fetch downloads a page and returns clean text content.
@ -149,7 +160,8 @@ func (f *Fetcher) Fetch(ctx context.Context, rawURL string) (string, error) {
httpResult, httpErr := f.fetchHTTP(requestCtx, rawURL, parsedURL)
if httpErr == nil {
content, parseErr := htmlToText(string(httpResult.body))
if parseErr == nil && strings.TrimSpace(content) != "" && !needsBrowserFallback(content, httpResult.body) {
requiresBrowser := parseErr == nil && needsBrowserFallback(content, httpResult.body)
if parseErr == nil && strings.TrimSpace(content) != "" && !requiresBrowser {
logger.Infof(ctx, "[WebFetch] fetched %s → %d chars", rawURL, len(content))
return content, nil
}
@ -166,7 +178,7 @@ func (f *Fetcher) Fetch(ctx context.Context, rawURL string) (string, error) {
if parseErr != nil {
return "", parseErr
}
if strings.TrimSpace(content) == "" {
if strings.TrimSpace(content) == "" || requiresBrowser {
return "", newFetchError(ErrorEmptyContent, false, "page contains no readable text")
}
return content, nil

View File

@ -136,6 +136,32 @@ func TestNewFetcherKeepsAgentCompatibleTimeout(t *testing.T) {
assert.Equal(t, 60*time.Second, NewFetcher().timeout)
}
func TestNewPipelineFetcherUsesHTTPOnlyAndLegacyTimeout(t *testing.T) {
fetcher := NewPipelineFetcher()
assert.Equal(t, 15*time.Second, fetcher.timeout)
assert.Nil(t, fetcher.renderBrowser)
}
func TestFetcherReturnsErrorWhenBrowserFallbackFailsOnSPA(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, _ *http.Request) {
_, _ = writer.Write([]byte(`<html><body><div id="app">Loading...</div><script>render()</script></body></html>`))
}))
defer server.Close()
fetcher := newTestFetcher(server.Client())
fetcher.resolveIPs = func(context.Context, string) ([]net.IP, error) {
return []net.IP{net.ParseIP("93.184.216.34")}, nil
}
fetcher.renderBrowser = func(context.Context, pinnedTarget) (string, error) {
return "", errors.New("browser unavailable")
}
_, err := fetcher.Fetch(context.Background(), server.URL)
code, retryable, _ := ErrorDetails(err)
assert.Equal(t, ErrorEmptyContent, code)
assert.False(t, retryable)
}
func TestFetcherClassifiesInvalidAndSSRFURLs(t *testing.T) {
fetcher := NewFetcher()
_, invalidErr := fetcher.Fetch(context.Background(), "not-a-url")

View File

@ -22,13 +22,16 @@ func (r *sourceRegistry) ModelOutput(result *types.ToolResult) string {
if result == nil {
return ""
}
displayType := stringValue(result.Data, "display_type")
if displayType == "web_fetch_results" {
return r.modelWebFetchOutput(mapsValue(result.Data["results"]), result.Output)
}
if !result.Success {
if result.Error != "" {
return "Error: " + r.CompactKnownText(result.Error)
}
return "Error: tool call failed"
}
displayType := stringValue(result.Data, "display_type")
switch displayType {
case "grep_results":
return r.modelKnowledgeOutput("keyword", mapsValue(result.Data["chunk_results"]), result.Output)
@ -42,8 +45,6 @@ func (r *sourceRegistry) ModelOutput(result *types.ToolResult) string {
return r.modelKnowledgeOutput("graph", mapsValue(result.Data["results"]), result.Output)
case "web_search_results":
return r.modelWebSearchOutput(mapsValue(result.Data["results"]), result.Output)
case "web_fetch_results":
return r.modelWebFetchOutput(mapsValue(result.Data["results"]), result.Output)
case "database_query":
return r.modelDatabaseQueryOutput(mapsValue(result.Data["rows"]), result.Output)
default:

View File

@ -376,6 +376,30 @@ func TestModelOutputWebFetchAllFailuresIncludeSearchFallback(t *testing.T) {
require.Contains(t, output, "page content was not verified")
}
func TestModelOutputWebFetchAllFailuresStillStructuredWhenToolNotSuccessful(t *testing.T) {
registry := newSourceRegistry()
output := registry.ModelOutput(&types.ToolResult{
Success: false,
Error: "all page fetches failed",
Data: map[string]interface{}{
"display_type": "web_fetch_results",
"results": []map[string]interface{}{
{
"url": "https://example.com/dns",
"status": "failed",
"retryable": true,
"error_code": "dns_failed",
"error_message": "DNS lookup failed",
},
},
},
})
require.Contains(t, output, `status="failed" retryable="true" error_code="dns_failed"`)
require.Contains(t, output, "Stop expanding web searches")
require.NotContains(t, output, "Error: all page fetches failed")
}
func TestModelOutputWebFetchKeepsContentWhenSummaryFails(t *testing.T) {
registry := newSourceRegistry()
output := registry.ModelOutput(&types.ToolResult{