From c20a2bee3a06ed919bf2f168cd50d7b741a9f63f Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 7 Nov 2026 23:12:28 +0800 Subject: [PATCH] feat(web-fetch-http): classify transport failures and show localized causes in the web_fetch row Co-authored-by: Elevator14B <219823454+Elevator14B@users.noreply.github.com> --- apps/web/tests/web-fetch-failure-row.e2e.ts | 75 ++++++++ docs/subsystems/web.i18n.yaml | 4 +- docs/subsystems/web.md | 2 +- docs/subsystems/web.zh.md | 2 +- .../guide.i18n.yaml | 16 ++ .../web-fetch-transport-error-codes/guide.md | 18 ++ .../guide.zh.md | 18 ++ .../ui-conversation/src/client/locales.ts | 56 ++++++ packages/client/ui-tool/README.i18n.yaml | 4 +- packages/client/ui-tool/README.md | 2 +- packages/client/ui-tool/README.zh.md | 2 +- .../src/client/tool/toolviews/web-row.tsx | 23 ++- .../ui-tool/tests/web-card.client.spec.tsx | 38 ++++ packages/web/web-fetch-http/README.i18n.yaml | 12 +- packages/web/web-fetch-http/README.md | 5 +- packages/web/web-fetch-http/README.zh.md | 5 +- packages/web/web-fetch-http/src/provider.ts | 40 +---- .../web-fetch-http/src/transport-failure.ts | 121 +++++++++++++ .../web-fetch-http/tests/fetch-http.spec.ts | 6 +- .../tests/network-error.spec.ts | 162 +++++++++++++----- .../web/web-fetch-http/tests/proxy.spec.ts | 5 +- .../session.v4.jsonl | 2 +- .../web/web-fetch-failure-row/snapshot.yml | 9 + .../web/web-fetch-failure-row/ui.expected.md | 33 ++++ 24 files changed, 558 insertions(+), 102 deletions(-) create mode 100644 apps/web/tests/web-fetch-failure-row.e2e.ts create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.i18n.yaml create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md create mode 100644 docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.zh.md create mode 100644 packages/web/web-fetch-http/src/transport-failure.ts create mode 100644 snapshots/web/web-fetch-failure-row/snapshot.yml create mode 100644 snapshots/web/web-fetch-failure-row/ui.expected.md diff --git a/apps/web/tests/web-fetch-failure-row.e2e.ts b/apps/web/tests/web-fetch-failure-row.e2e.ts new file mode 100644 index 0000000000..f5716088db --- /dev/null +++ b/apps/web/tests/web-fetch-failure-row.e2e.ts @@ -0,0 +1,75 @@ +// Web e2e scenario: a web_fetch transport failure leads its collapsed row with the +// localized failure summary and keeps the recorded code and detail in the expanded +// output. Borrow the headless transport-failure fixture without any model call. +import { readFile } from 'node:fs/promises' +import { fileURLToPath } from 'node:url' +import { join } from 'node:path' +import type { Browser, Page } from 'playwright' +import { chromium } from 'playwright' +import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' +import { + assertFixtureInventory, captureStableAria, compareOrRefreshGolden, fixtureUserPrompts, + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, +} from './scaffold.ts' +import { expandTurnProcesses, newEnglishPage, saveFailureShot, WEB_FIXTURE_TIME } from './support.ts' + +const FIXTURE = fileURLToPath(new URL('../../../snapshots/session/web-fetch-transport-failure/session.v4.jsonl', import.meta.url)) +const SNAPSHOT_DIR = fileURLToPath(new URL('../../../snapshots/web/web-fetch-failure-row', import.meta.url)) +const UI_EXPECTED = join(SNAPSHOT_DIR, 'ui.expected.md') +const MODE = webSnapshotMode() +const SEED_ID = 'web-fetch-failure-row-web-e2e' +const PROMPT = 'Use the web_fetch tool exactly once to fetch http://public.test:43117/menu.html, then reply with exactly DONE. Do not describe the content.' +const SUMMARY = 'Connection interrupted. Try again later.' +const DETAIL = 'Error: web fetch failed: the connection was interrupted (UND_ERR_SOCKET): other side closed' + +describe.skipIf(MODE === 'record')('web e2e: web_fetch transport failure row', () => { + let scaffold: WebScaffold + let browser: Browser + let page: Page + let tripwire: ReturnType + + beforeAll(async () => { + const fixture = await readFile(FIXTURE, 'utf8') + expect(fixtureUserPrompts(fixture)).toEqual([PROMPT]) + scaffold = await launchWebScaffold({}) + await seedSession(scaffold, fixture, SEED_ID, undefined, { createdAt: WEB_FIXTURE_TIME }) + browser = await chromium.launch() + page = await newEnglishPage(browser) + await page.clock.setFixedTime(WEB_FIXTURE_TIME) + tripwire = watchConsole(page) + await page.goto(scaffold.authenticatedUrl, { waitUntil: 'load' }) + await page.waitForSelector('[class*="frame"]', { timeout: 30_000 }) + + const groupRow = page.locator('[role="treeitem"]').first() + await groupRow.waitFor({ timeout: 15_000 }) + await groupRow.click() + const sessionRow = page.locator('[role="treeitem"]').nth(1) + await sessionRow.waitFor({ timeout: 10_000 }) + await sessionRow.click() + await expandTurnProcesses(page) + await page.getByText(SUMMARY, { exact: true }).waitFor({ timeout: 15_000 }) + }, 120_000) + + afterAll(async () => { + await browser?.close() + await scaffold?.close() + }) + + it('leads with the localized summary and expands to the recorded detail', async () => { + onTestFailed(() => saveFailureShot(page, 'web-e2e-web-fetch-failure-row')) + const summary = page.getByText(SUMMARY, { exact: true }) + expect(await page.getByText(DETAIL, { exact: true }).count()).toBe(0) + await summary.click() + await page.getByText(DETAIL, { exact: true }).waitFor() + + const snapshot = (await captureStableAria(page, '[class*="centerCol"]', scaffold.workspaceCwd)) + .split(SEED_ID).join('{{seededId}}') + await compareOrRefreshGolden(UI_EXPECTED, snapshot, MODE) + expect(tripwire.pageErrors).toEqual([]) + expect(tripwire.warnings).toEqual([]) + }, 60_000) + + it('keeps its snapshot inventory closed', async () => { + await assertFixtureInventory(SNAPSHOT_DIR, ['ui.expected.md']) + }) +}) diff --git a/docs/subsystems/web.i18n.yaml b/docs/subsystems/web.i18n.yaml index 55cee3b518..409796b80c 100644 --- a/docs/subsystems/web.i18n.yaml +++ b/docs/subsystems/web.i18n.yaml @@ -21,8 +21,8 @@ en: 6851874be5841d90 zh: dc085bf3b82d77df /web-access/errors: - en: b07c04f462b4a0d9 - zh: de5f09cd2fb0324c + en: cda399e195258b07 + zh: c544c11fa7f7d217 /web-access/the-service: en: c9e7dc85c08e64e1 zh: 277c52aac58f42dc diff --git a/docs/subsystems/web.md b/docs/subsystems/web.md index 097b388fd1..0513c0dc35 100644 --- a/docs/subsystems/web.md +++ b/docs/subsystems/web.md @@ -137,7 +137,7 @@ The HTTP provider does not restrict destination addresses: `web_fetch` reaches l ## Errors -`WebError extends HarnessError` ([core.md](core.md) error taxonomy) with a `code: string` (open, like every other seam's error — `LlmError`, `SubagentError`), not a closed union: a provider may raise its own codes without editing `dsh-web`, and consumers must tolerate an unknown code. The codes split by owner. Seam-neutral codes are raised by the shared `WebRuntime` contract: `WEB_PROVIDER_UNAVAILABLE`, `WEB_PROVIDER_CONFIGURED_MISSING`, `WEB_PROVIDER_CONFIGURED_UNAVAILABLE`, `WEB_PROVIDER_AMBIGUOUS`, `WEB_DUPLICATE_PROVIDER` (a registration-time programming error, the analogue of `LlmRuntime`'s `DUPLICATE_ADAPTER`), `WEB_ABORTED`, and `WEB_PROVIDER_ERROR` (the catch-all for a provider's own failure surfaced through the seam, including network/transport failure — DNS, connection refused, TLS). Fetch-transport codes are owned by the `dsh-web-fetch-http` implementation and a different fetch backend need not raise them: `WEB_INVALID_URL`, `WEB_BLOCKED_URL`, `WEB_REDIRECT_BLOCKED`, `WEB_FETCH_TOO_LARGE`, `WEB_FETCH_TIMEOUT`, `WEB_UNSUPPORTED_CONTENT_TYPE`. +`WebError extends HarnessError` ([core.md](core.md) error taxonomy) with a `code: string` (open, like every other seam's error — `LlmError`, `SubagentError`), not a closed union: a provider may raise its own codes without editing `dsh-web`, and consumers must tolerate an unknown code. The codes split by owner. Seam-neutral codes are raised by the shared `WebRuntime` contract: `WEB_PROVIDER_UNAVAILABLE`, `WEB_PROVIDER_CONFIGURED_MISSING`, `WEB_PROVIDER_CONFIGURED_UNAVAILABLE`, `WEB_PROVIDER_AMBIGUOUS`, `WEB_DUPLICATE_PROVIDER` (a registration-time programming error, the analogue of `LlmRuntime`'s `DUPLICATE_ADAPTER`), `WEB_ABORTED`, and `WEB_PROVIDER_ERROR` (the catch-all for a provider's own failure surfaced through the seam). Fetch-transport codes are owned by the `dsh-web-fetch-http` implementation and a different fetch backend need not raise them: `WEB_INVALID_URL`, `WEB_BLOCKED_URL`, `WEB_REDIRECT_BLOCKED`, `WEB_FETCH_TOO_LARGE`, `WEB_FETCH_TIMEOUT`, `WEB_UNSUPPORTED_CONTENT_TYPE`, and the network failure classes `WEB_FETCH_DNS_FAILED`, `WEB_FETCH_CONNECTION_REFUSED`, `WEB_FETCH_CONNECTION_TIMEOUT`, `WEB_FETCH_CERTIFICATE_INVALID`, `WEB_FETCH_CONNECTION_INTERRUPTED`, `WEB_FETCH_NETWORK_UNREACHABLE`, and `WEB_FETCH_NETWORK_ERROR`. The Web `web_fetch` row shows a localized summary for a network failure class and keeps the recorded message in its output. ## The service diff --git a/docs/subsystems/web.zh.md b/docs/subsystems/web.zh.md index 38a1b088f4..cca07c0f16 100644 --- a/docs/subsystems/web.zh.md +++ b/docs/subsystems/web.zh.md @@ -137,7 +137,7 @@ HTTP 提供方不限制目的地址:`web_fetch` 会像访问其他主机一样 ## 错误 -`WebError extends HarnessError`([core.md](core.zh.md) 错误分类体系),带有 `code: string`(开放式,与其他 seam 的错误一致——`LlmError`、`SubagentError`),而非封闭联合类型:提供方可以在不修改 `dsh-web` 的情况下抛出自己的错误代码,消费方必须容忍未知错误代码。错误代码按所有者划分。共享的 `WebRuntime` 约定会抛出与 seam 无关的错误代码:`WEB_PROVIDER_UNAVAILABLE`、`WEB_PROVIDER_CONFIGURED_MISSING`、`WEB_PROVIDER_CONFIGURED_UNAVAILABLE`、`WEB_PROVIDER_AMBIGUOUS`、`WEB_DUPLICATE_PROVIDER`(注册时的编程错误,类似 `LlmRuntime` 的 `DUPLICATE_ADAPTER`)、`WEB_ABORTED`,以及 `WEB_PROVIDER_ERROR`(提供方自身故障经 seam 暴露时使用的兜底代码,包括 DNS、连接被拒绝、TLS 等网络或传输故障)。抓取传输层错误代码由 `dsh-web-fetch-http` 实现拥有,不同的抓取后端无需抛出它们:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_REDIRECT_BLOCKED`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_UNSUPPORTED_CONTENT_TYPE`。 +`WebError extends HarnessError`([core.md](core.zh.md) 错误分类体系),带有 `code: string`(开放式,与其他 seam 的错误一致——`LlmError`、`SubagentError`),而非封闭联合类型:提供方可以在不修改 `dsh-web` 的情况下抛出自己的错误代码,消费方必须容忍未知错误代码。错误代码按所有者划分。共享的 `WebRuntime` 约定会抛出与 seam 无关的错误代码:`WEB_PROVIDER_UNAVAILABLE`、`WEB_PROVIDER_CONFIGURED_MISSING`、`WEB_PROVIDER_CONFIGURED_UNAVAILABLE`、`WEB_PROVIDER_AMBIGUOUS`、`WEB_DUPLICATE_PROVIDER`(注册时的编程错误,类似 `LlmRuntime` 的 `DUPLICATE_ADAPTER`)、`WEB_ABORTED`,以及 `WEB_PROVIDER_ERROR`(提供方自身故障经 seam 暴露时使用的兜底代码)。抓取传输层错误代码由 `dsh-web-fetch-http` 实现拥有,不同的抓取后端无需抛出它们:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_REDIRECT_BLOCKED`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_UNSUPPORTED_CONTENT_TYPE`,以及网络故障类别 `WEB_FETCH_DNS_FAILED`、`WEB_FETCH_CONNECTION_REFUSED`、`WEB_FETCH_CONNECTION_TIMEOUT`、`WEB_FETCH_CERTIFICATE_INVALID`、`WEB_FETCH_CONNECTION_INTERRUPTED`、`WEB_FETCH_NETWORK_UNREACHABLE` 和 `WEB_FETCH_NETWORK_ERROR`。Web 中的 `web_fetch` 行会为网络故障类别显示本地化摘要,并在输出中保留记录的消息。 ## 服务 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.i18n.yaml b/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.i18n.yaml new file mode 100644 index 0000000000..47e95ff056 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.i18n.yaml @@ -0,0 +1,16 @@ +# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md +/: + en: 35ed3b25ea3d40d7 + zh: 2b037f8b2ef608e7 +/local-http-fetch-transport-failures-use-classified-codes: + en: 3897971fd31f36fe + zh: a8ef921a842e618e +/local-http-fetch-transport-failures-use-classified-codes/change: + en: ad6f5c7df983668c + zh: 43a1abab550cd7c4 +/local-http-fetch-transport-failures-use-classified-codes/migration: + en: ac5fd3b3b803d45a + zh: bef35af54771b9b7 diff --git a/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md b/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md new file mode 100644 index 0000000000..9a01f603d9 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "Local HTTP fetch transport failures raise classified WEB_FETCH_* codes instead of WEB_PROVIDER_ERROR." +--- + +# Local HTTP fetch transport failures use classified codes + +English | [中文](guide.zh.md) + +## Change + +The local HTTP fetch provider (`dsh-web-fetch-http`) previously raised `WEB_PROVIDER_ERROR` with the text `web fetch failed: TypeError: fetch failed` for every network failure before or during the response. It now raises one of `WEB_FETCH_DNS_FAILED`, `WEB_FETCH_CONNECTION_REFUSED`, `WEB_FETCH_CONNECTION_TIMEOUT`, `WEB_FETCH_CERTIFICATE_INVALID`, `WEB_FETCH_CONNECTION_INTERRUPTED`, `WEB_FETCH_NETWORK_UNREACHABLE`, or `WEB_FETCH_NETWORK_ERROR` for an unrecognized failure. The message names the failure class, the system error code, and the underlying error. The same code appears in the `error.code` of new `web_fetch` tool results. Callers of `ctx.web.fetch()` and readers of tool-result error codes that match `WEB_PROVIDER_ERROR` for network failures are affected. Other providers, and other `dsh-web-fetch-http` failures, are unchanged. + +## Migration + +1. Where code routes local fetch network failures on `WEB_PROVIDER_ERROR`, match the seven codes above instead. +2. Do not parse the message text; it is diagnostic and may change. +3. Confirm by fetching an unresolvable host, such as `http://example.invalid/`, and checking that the error code is `WEB_FETCH_DNS_FAILED`. diff --git a/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.zh.md b/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.zh.md new file mode 100644 index 0000000000..b734b41ff5 --- /dev/null +++ b/docs/upgrade-guide/v0.2.2-rc.1/web-fetch-transport-error-codes/guide.zh.md @@ -0,0 +1,18 @@ +--- +kind: upgrade-guide +description: "本地 HTTP 抓取的传输故障改为抛出分类后的 WEB_FETCH_* 代码,而不是 WEB_PROVIDER_ERROR。" +--- + +# 本地 HTTP 抓取的传输故障使用分类代码 + +[English](guide.md) | 中文 + +## 变更 + +本地 HTTP 抓取提供方(`dsh-web-fetch-http`)以前在响应之前或响应期间遇到任何网络故障时,都会抛出 `WEB_PROVIDER_ERROR`,文本为 `web fetch failed: TypeError: fetch failed`。现在它会抛出 `WEB_FETCH_DNS_FAILED`、`WEB_FETCH_CONNECTION_REFUSED`、`WEB_FETCH_CONNECTION_TIMEOUT`、`WEB_FETCH_CERTIFICATE_INVALID`、`WEB_FETCH_CONNECTION_INTERRUPTED`、`WEB_FETCH_NETWORK_UNREACHABLE` 之一;无法识别的故障则抛出 `WEB_FETCH_NETWORK_ERROR`。错误消息会写明故障类别、系统错误码和底层错误。新的 `web_fetch` 工具结果的 `error.code` 中也会出现相同的代码。受影响的是 `ctx.web.fetch()` 的调用方,以及对网络故障匹配 `WEB_PROVIDER_ERROR` 的工具结果错误码读取方。其他提供方,以及 `dsh-web-fetch-http` 的其他故障,均不受影响。 + +## 迁移 + +1. 如果代码按 `WEB_PROVIDER_ERROR` 路由本地抓取的网络故障,改为匹配上述七个代码。 +2. 不要解析错误消息文本;它仅用于诊断,可能会变化。 +3. 抓取一个无法解析的主机(例如 `http://example.invalid/`),确认错误码为 `WEB_FETCH_DNS_FAILED`。 diff --git a/packages/client/ui-conversation/src/client/locales.ts b/packages/client/ui-conversation/src/client/locales.ts index eb3c04782a..192446b712 100644 --- a/packages/client/ui-conversation/src/client/locales.ts +++ b/packages/client/ui-conversation/src/client/locales.ts @@ -350,6 +350,13 @@ export const zh = { 'tool.title.glob': '查找文件', 'tool.title.webSearch': '网页搜索', 'tool.title.webFetch': '网页获取', + 'tool.webFetch.failure.dns': '无法解析域名,请检查网络、代理或 DNS 设置', + 'tool.webFetch.failure.refused': '连接被拒绝,请检查地址、端口或代理', + 'tool.webFetch.failure.connectionTimeout': '连接超时,请检查网络或代理后重试', + 'tool.webFetch.failure.certificate': '安全证书校验失败,请检查系统时间、代理或证书配置', + 'tool.webFetch.failure.interrupted': '连接中断,请稍后重试', + 'tool.webFetch.failure.unreachable': '网络或主机不可达,请检查网络连接或代理', + 'tool.webFetch.failure.network': '网络请求失败,详情见输出', 'tool.autoReviewRejected': 'Auto review 已拒绝', 'tool.autoReviewNotExecuted': '工具未执行。原因:{reason}', 'tool.autoReviewReasonFallback': 'Auto review 未授权此次操作', @@ -749,6 +756,13 @@ export const en = { 'tool.title.glob': 'Glob', 'tool.title.webSearch': 'Search', 'tool.title.webFetch': 'Fetch', + 'tool.webFetch.failure.dns': 'Couldn\'t resolve the host name. Check your network, proxy, or DNS settings.', + 'tool.webFetch.failure.refused': 'Connection refused. Check the address, port, or proxy.', + 'tool.webFetch.failure.connectionTimeout': 'Connection timed out. Check your network or proxy, then retry.', + 'tool.webFetch.failure.certificate': 'Certificate verification failed. Check the system clock, proxy, or certificates.', + 'tool.webFetch.failure.interrupted': 'Connection interrupted. Try again later.', + 'tool.webFetch.failure.unreachable': 'Network or host unreachable. Check your network connection or proxy.', + 'tool.webFetch.failure.network': 'Network request failed. See the output for details.', 'tool.autoReviewRejected': 'Rejected by Auto review', 'tool.autoReviewNotExecuted': 'Tool was not executed. Reason: {reason}', 'tool.autoReviewReasonFallback': 'Auto review did not authorize this action', @@ -1147,6 +1161,13 @@ export const ja = { 'tool.title.glob': 'Glob', 'tool.title.webSearch': '検索', 'tool.title.webFetch': '取得', + 'tool.webFetch.failure.dns': 'ホスト名を解決できませんでした。ネットワーク、プロキシ、または DNS の設定を確認してください。', + 'tool.webFetch.failure.refused': '接続が拒否されました。アドレス、ポート、またはプロキシを確認してください。', + 'tool.webFetch.failure.connectionTimeout': '接続がタイムアウトしました。ネットワークまたはプロキシを確認してから再試行してください。', + 'tool.webFetch.failure.certificate': '証明書の検証に失敗しました。システムの時刻、プロキシ、または証明書を確認してください。', + 'tool.webFetch.failure.interrupted': '接続が中断されました。しばらくしてから再試行してください。', + 'tool.webFetch.failure.unreachable': 'ネットワークまたはホストに到達できません。ネットワーク接続またはプロキシを確認してください。', + 'tool.webFetch.failure.network': 'ネットワークリクエストに失敗しました。詳細は出力を確認してください。', 'tool.autoReviewRejected': '自動認可レビューにより拒否されました', 'tool.autoReviewNotExecuted': 'ツールは実行されませんでした。理由: {reason}', 'tool.autoReviewReasonFallback': '自動認可レビューがこの操作を承認しませんでした', @@ -1538,6 +1559,13 @@ export const es = { 'tool.title.glob': 'globo', 'tool.title.webSearch': 'Buscar', 'tool.title.webFetch': 'buscar', + 'tool.webFetch.failure.dns': 'No se pudo resolver el nombre de host. Revisa la configuración de red, proxy o DNS.', + 'tool.webFetch.failure.refused': 'Conexión rechazada. Revisa la dirección, el puerto o el proxy.', + 'tool.webFetch.failure.connectionTimeout': 'Se agotó el tiempo de conexión. Revisa tu red o proxy y vuelve a intentarlo.', + 'tool.webFetch.failure.certificate': 'Error al verificar el certificado. Revisa el reloj del sistema, el proxy o los certificados.', + 'tool.webFetch.failure.interrupted': 'Conexión interrumpida. Vuelve a intentarlo más tarde.', + 'tool.webFetch.failure.unreachable': 'Red o host inaccesible. Revisa tu conexión de red o el proxy.', + 'tool.webFetch.failure.network': 'Error en la solicitud de red. Consulta la salida para ver los detalles.', 'tool.autoReviewRejected': 'Rechazado por Auto review', 'tool.autoReviewNotExecuted': 'La herramienta no fue ejecutada. Razón: {reason}', 'tool.autoReviewReasonFallback': 'Auto review no autorizó esta acción', @@ -1936,6 +1964,13 @@ export const fr = { 'tool.title.glob': 'Glob', 'tool.title.webSearch': 'Rechercher', 'tool.title.webFetch': 'Récupérer', + 'tool.webFetch.failure.dns': 'Impossible de résoudre le nom d’hôte. Vérifiez vos paramètres réseau, proxy ou DNS.', + 'tool.webFetch.failure.refused': 'Connexion refusée. Vérifiez l’adresse, le port ou le proxy.', + 'tool.webFetch.failure.connectionTimeout': 'Délai de connexion dépassé. Vérifiez votre réseau ou votre proxy, puis réessayez.', + 'tool.webFetch.failure.certificate': 'Échec de la vérification du certificat. Vérifiez l’horloge système, le proxy ou les certificats.', + 'tool.webFetch.failure.interrupted': 'Connexion interrompue. Réessayez plus tard.', + 'tool.webFetch.failure.unreachable': 'Réseau ou hôte injoignable. Vérifiez votre connexion réseau ou votre proxy.', + 'tool.webFetch.failure.network': 'Échec de la requête réseau. Consultez la sortie pour plus de détails.', 'tool.autoReviewRejected': 'Rejeté par Auto review', 'tool.autoReviewNotExecuted': "L'outil n'a pas été exécuté. Raison : {reason}", 'tool.autoReviewReasonFallback': "Auto review n'a pas autorisé cette action", @@ -2334,6 +2369,13 @@ export const de = { 'tool.title.glob': 'Globus', 'tool.title.webSearch': 'Suchen', 'tool.title.webFetch': 'Holen', + 'tool.webFetch.failure.dns': 'Hostname konnte nicht aufgelöst werden. Prüfen Sie Ihre Netzwerk-, Proxy- oder DNS-Einstellungen.', + 'tool.webFetch.failure.refused': 'Verbindung abgelehnt. Überprüfen Sie Adresse, Port oder Proxy.', + 'tool.webFetch.failure.connectionTimeout': 'Zeitüberschreitung der Verbindung. Überprüfen Sie Ihr Netzwerk oder Ihren Proxy und versuchen Sie es erneut.', + 'tool.webFetch.failure.certificate': 'Zertifikatsprüfung fehlgeschlagen. Prüfen Sie die Systemzeit, den Proxy oder die Zertifikate.', + 'tool.webFetch.failure.interrupted': 'Verbindung unterbrochen. Versuchen Sie es später erneut.', + 'tool.webFetch.failure.unreachable': 'Netzwerk oder Host nicht erreichbar. Überprüfen Sie Ihre Netzwerkverbindung oder Ihren Proxy.', + 'tool.webFetch.failure.network': 'Netzwerkanfrage fehlgeschlagen. Details finden Sie in der Ausgabe.', 'tool.autoReviewRejected': 'Abgelehnt von Auto review', 'tool.autoReviewNotExecuted': 'Werkzeug wurde nicht ausgeführt. Grund: {reason}', 'tool.autoReviewReasonFallback': 'Auto review hat diese Aktion nicht autorisiert', @@ -2732,6 +2774,13 @@ export const ru = { 'tool.title.glob': 'Глоб', 'tool.title.webSearch': 'Поиск', 'tool.title.webFetch': 'Получить', + 'tool.webFetch.failure.dns': 'Не удалось разрешить имя хоста. Проверьте настройки сети, прокси или DNS.', + 'tool.webFetch.failure.refused': 'Соединение отклонено. Проверьте адрес, порт или прокси.', + 'tool.webFetch.failure.connectionTimeout': 'Истекло время ожидания соединения. Проверьте сеть или прокси и повторите попытку.', + 'tool.webFetch.failure.certificate': 'Не удалось проверить сертификат. Проверьте системное время, прокси или сертификаты.', + 'tool.webFetch.failure.interrupted': 'Подключение прервано. Повторите попытку позже.', + 'tool.webFetch.failure.unreachable': 'Сеть или хост недоступны. Проверьте сетевое подключение или прокси.', + 'tool.webFetch.failure.network': 'Сетевой запрос не выполнен. Подробности см. в выводе.', 'tool.autoReviewRejected': 'Отклонено Auto review', 'tool.autoReviewNotExecuted': 'Инструмент не был выполнен. Причина: {reason}', 'tool.autoReviewReasonFallback': 'Auto review не санкционировал это действие', @@ -3130,6 +3179,13 @@ export const pt = { 'tool.title.glob': 'globo', 'tool.title.webSearch': 'Pesquisar', 'tool.title.webFetch': 'Buscar', + 'tool.webFetch.failure.dns': 'Não foi possível resolver o nome do host. Verifique as configurações de rede, proxy ou DNS.', + 'tool.webFetch.failure.refused': 'Conexão recusada. Verifique o endereço, a porta ou o proxy.', + 'tool.webFetch.failure.connectionTimeout': 'A conexão expirou. Verifique sua rede ou proxy e tente novamente.', + 'tool.webFetch.failure.certificate': 'Falha na verificação do certificado. Verifique o relógio do sistema, o proxy ou os certificados.', + 'tool.webFetch.failure.interrupted': 'Conexão interrompida. Tente novamente mais tarde.', + 'tool.webFetch.failure.unreachable': 'Rede ou host inacessível. Verifique sua conexão de rede ou proxy.', + 'tool.webFetch.failure.network': 'Falha na solicitação de rede. Consulte a saída para ver os detalhes.', 'tool.autoReviewRejected': 'Rejeitado por Auto review', 'tool.autoReviewNotExecuted': 'A ferramenta não foi executada. Motivo: {reason}', 'tool.autoReviewReasonFallback': 'Auto review não autorizou esta ação', diff --git a/packages/client/ui-tool/README.i18n.yaml b/packages/client/ui-tool/README.i18n.yaml index 4182c93cfe..a4890ba430 100644 --- a/packages/client/ui-tool/README.i18n.yaml +++ b/packages/client/ui-tool/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-client-ui-tool/use-this-package: - en: 09231e7cc6515a01 - zh: c306bb141cf9bf9d + en: e80ef2d1f6c57a17 + zh: 69a150aa994537ab /deepseek-ai-dsh-client-ui-tool/use-this-package/registering-a-business-tool-view: en: e458aff61e634190 zh: 650e417f450b3edf diff --git a/packages/client/ui-tool/README.md b/packages/client/ui-tool/README.md index b460da0f8f..5d1fc53afd 100644 --- a/packages/client/ui-tool/README.md +++ b/packages/client/ui-tool/README.md @@ -25,7 +25,7 @@ English | [中文](README.zh.md) ## Use this package -Tool calls appear in the conversation as cards: a root call tree with its nested subcalls, each atomic call rendered by its owning view. Every lifecycle state retains the tool's ordinary business glyph; failure and interruption remain explicit through the frozen call/result state, accessible status text, and failure summary. Users can open files or inspect calls through the Host callbacks. A collapsed `web_fetch` row links its http(s) URL, which opens in a new browser tab. Control receipts display the agent name supplied by the recorded call, or the agent ID in historical calls. Text agent lists show each agent name, or the historical ID, above a single-line description, with compact spacing and recorded status. Click the description to expand or collapse its full text; its accessible name follows the selected locale. +Tool calls appear in the conversation as cards: a root call tree with its nested subcalls, each atomic call rendered by its owning view. Every lifecycle state retains the tool's ordinary business glyph; failure and interruption remain explicit through the frozen call/result state, accessible status text, and failure summary. Users can open files or inspect calls through the Host callbacks. A collapsed `web_fetch` row links its http(s) URL, which opens in a new browser tab; a failed fetch with a classified network failure code shows a localized cause and hint as its failure summary, and its output keeps the recorded message. Control receipts display the agent name supplied by the recorded call, or the agent ID in historical calls. Text agent lists show each agent name, or the historical ID, above a single-line description, with compact spacing and recorded status. Click the description to expand or collapse its full text; its accessible name follows the selected locale. Settled foreground commands with a nonzero exit code, a terminating signal, or an explicit missing exit code keep their description in the ordinary gray text and show a neutral capsule with a red dot immediately after it. The capsule displays only the recorded code, signal, or localized missing-code status and stays on the same line; the description truncates with an ellipsis to reserve its space. Running, successful, and background calls omit it. Generic execution errors and stopped summaries retain their error and warning colors, including on hover. diff --git a/packages/client/ui-tool/README.zh.md b/packages/client/ui-tool/README.zh.md index 3b7811a823..d52609994c 100644 --- a/packages/client/ui-tool/README.zh.md +++ b/packages/client/ui-tool/README.zh.md @@ -25,7 +25,7 @@ kind: "package-reference" ## 使用本包 -工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。折叠的 `web_fetch` 行把其 http(s) URL 显示为链接,在新浏览器标签页中打开。控制工具回执显示记录的调用所提供的智能体名称,历史调用则显示智能体 ID。文本形式的智能体列表以紧凑间距展示智能体名称(历史记录为 ID)、下方的单行描述及记录中的状态。点击描述可展开或收起全文;其无障碍名称使用当前语言。 +工具调用在对话中显示为卡片:一个根调用树带其嵌套子调用,每个原子调用由所属视图渲染。所有生命周期状态都保留工具的普通业务图标;失败与中断仍通过冻结调用/结果状态、无障碍状态文本和失败摘要明确表达。用户可通过宿主回调打开文件或检查调用。折叠的 `web_fetch` 行把其 http(s) URL 显示为链接,在新浏览器标签页中打开;带有已分类网络故障错误码的失败抓取以本地化的原因和建议作为失败摘要,其输出保留记录的消息。控制工具回执显示记录的调用所提供的智能体名称,历史调用则显示智能体 ID。文本形式的智能体列表以紧凑间距展示智能体名称(历史记录为 ID)、下方的单行描述及记录中的状态。点击描述可展开或收起全文;其无障碍名称使用当前语言。 已结束的前台命令若返回非零退出码、终止信号,或明确记录为无退出码,描述保持普通灰色,后面紧接带红点的中性胶囊。胶囊仅显示记录的退出码、信号或本地化的“未正常退出”状态,并保持在同一行;描述超出可用宽度时显示省略号,为胶囊预留空间。运行中、成功和后台调用不显示胶囊。通用执行错误与停止摘要仍保留错误色和警告色,悬停时也不改变。 diff --git a/packages/client/ui-tool/src/client/tool/toolviews/web-row.tsx b/packages/client/ui-tool/src/client/tool/toolviews/web-row.tsx index 452eb0593b..c03b524dec 100644 --- a/packages/client/ui-tool/src/client/tool/toolviews/web-row.tsx +++ b/packages/client/ui-tool/src/client/tool/toolviews/web-row.tsx @@ -14,12 +14,33 @@ const WEB_TITLE_KEYS = { web_fetch: 'tool.title.webFetch', } as const +/** Collapsed-row summaries for the transport failure codes of `dsh-web-fetch-http` (`src/transport-failure.ts`). */ +const WEB_FETCH_FAILURE_KEYS = { + WEB_FETCH_DNS_FAILED: 'tool.webFetch.failure.dns', + WEB_FETCH_CONNECTION_REFUSED: 'tool.webFetch.failure.refused', + WEB_FETCH_CONNECTION_TIMEOUT: 'tool.webFetch.failure.connectionTimeout', + WEB_FETCH_CERTIFICATE_INVALID: 'tool.webFetch.failure.certificate', + WEB_FETCH_CONNECTION_INTERRUPTED: 'tool.webFetch.failure.interrupted', + WEB_FETCH_NETWORK_UNREACHABLE: 'tool.webFetch.failure.unreachable', + WEB_FETCH_NETWORK_ERROR: 'tool.webFetch.failure.network', +} as const + +/** Whether a recorded error code is a web_fetch transport failure code. */ +function isFetchFailureCode(code: string): code is keyof typeof WEB_FETCH_FAILURE_KEYS { + return Object.hasOwn(WEB_FETCH_FAILURE_KEYS, code) +} + /** Lets users expand a completed web search or fetch result. */ export function WebRow({ toolName, block, useContextMenu, sessionId, inspect, useDisclosure, t }: WebRowProps) { const { getTriggerProps } = useContextMenu() const href = webFetchHref(block) const model = toolRowModel(toolName, block) const web = webCardModel(block) + // A classified transport failure leads with its localized summary; the expanded output keeps the code and detail. + const code = 'kind' in block ? block.error?.code : undefined + const failureKey = model.state === 'error' && toolName === 'web_fetch' && code !== undefined && isFetchFailureCode(code) + ? WEB_FETCH_FAILURE_KEYS[code] + : undefined const icon = toolName === 'web_fetch' ? : return ( { expect(view.queryByRole('link')).toBeNull() }) + /** A settled web_fetch transport failure as the provider records it. */ + const transportFailure = (code: string, text: string, toolName = 'web_fetch') => settledFetch({ + call: { name: toolName, argsRaw: FETCH_ARGS }, + isError: true, + content: [{ type: 'text', text }], + meta: undefined, + error: { name: 'WebError', code }, + }) + + it.each([ + ['WEB_FETCH_DNS_FAILED', 'could not resolve the host name (ENOTFOUND): getaddrinfo ENOTFOUND example.com', '无法解析域名,请检查网络、代理或 DNS 设置'], + ['WEB_FETCH_CONNECTION_REFUSED', 'the server refused the connection (ECONNREFUSED): connect ECONNREFUSED 127.0.0.1:8080', '连接被拒绝,请检查地址、端口或代理'], + ['WEB_FETCH_CONNECTION_TIMEOUT', 'the connection timed out (UND_ERR_CONNECT_TIMEOUT): Connect Timeout Error', '连接超时,请检查网络或代理后重试'], + ['WEB_FETCH_CERTIFICATE_INVALID', 'the server certificate could not be verified (CERT_HAS_EXPIRED): certificate has expired', '安全证书校验失败,请检查系统时间、代理或证书配置'], + ['WEB_FETCH_CONNECTION_INTERRUPTED', 'the connection was interrupted (UND_ERR_SOCKET): other side closed', '连接中断,请稍后重试'], + ['WEB_FETCH_NETWORK_UNREACHABLE', 'the network or host is unreachable (ENETUNREACH): connect ENETUNREACH 10.0.0.1:443', '网络或主机不可达,请检查网络连接或代理'], + ['WEB_FETCH_NETWORK_ERROR', 'the network request failed (EPROTO): write EPROTO', '网络请求失败,详情见输出'], + ])('a %s web fetch leads with its localized summary and keeps the detail in the output', (code, detail, summary) => { + const text = `Error: web fetch failed: ${detail}` + const view = render() + expect(view.getByText(summary)).toBeTruthy() + expect(view.queryByText(text)).toBeNull() + toggleRow(view) + expect(view.getByText(text)).toBeTruthy() + }) + + it('a failure without a transport failure code keeps the recorded first line', () => { + const text = 'Error: unsupported content type "image/png"' + const view = render() + expect(view.getByText(text)).toBeTruthy() + }) + + it('a web search failure keeps the recorded first line even with a fetch failure code', () => { + const text = 'Error: web search failed' + const view = render() + expect(view.getByText(text)).toBeTruthy() + }) + it('a running web call is the summary row alone, with nothing to expand', () => { const view = render() expect(view.getByText('网页搜索')).toBeTruthy() diff --git a/packages/web/web-fetch-http/README.i18n.yaml b/packages/web/web-fetch-http/README.i18n.yaml index 9010001d0c..a456901b31 100644 --- a/packages/web/web-fetch-http/README.i18n.yaml +++ b/packages/web/web-fetch-http/README.i18n.yaml @@ -30,8 +30,8 @@ en: 4c5618124337446e zh: 45c7378c8b0bba45 /deepseek-ai-dsh-web-fetch-http/use-this-package/failures-and-recovery: - en: e62633ede6519943 - zh: 0970dc75b474e702 + en: c8cc3ab50ee6de0a + zh: 52710e3e2f82cd87 /deepseek-ai-dsh-web-fetch-http/understand-the-implementation: en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb @@ -39,8 +39,8 @@ en: 422128dac5eebdde zh: 25ba5f49b305a056 /deepseek-ai-dsh-web-fetch-http/understand-the-implementation/source-map: - en: 1f355ec2726ff61b - zh: 076a0c259c94f22a + en: 9a60dc44a74f499d + zh: a96991347a773e54 /deepseek-ai-dsh-web-fetch-http/understand-the-implementation/read-path: en: 4836d06bc065477d zh: 5a7ddc805a7c67d8 @@ -48,8 +48,8 @@ en: eeaaf0b455673a1c zh: 0874f9f44ff9a220 /deepseek-ai-dsh-web-fetch-http/model-experience: - en: 5c488f8d23ce3e90 - zh: 3cc8f8dc3ab60b65 + en: 90622667adea8ba3 + zh: 6a38fa2d715fe33a /deepseek-ai-dsh-web-fetch-http/model-experience/kv-cache-effect: en: 40294c1c31b74824 zh: d75d48f485447a74 diff --git a/packages/web/web-fetch-http/README.md b/packages/web/web-fetch-http/README.md index d8233c9429..63532ab02e 100644 --- a/packages/web/web-fetch-http/README.md +++ b/packages/web/web-fetch-http/README.md @@ -67,7 +67,7 @@ A malformed comma- or whitespace-joined charset declaration containing a UTF-8 l ### Failures and recovery -Failures throw `WebError` with a machine-routable code: `WEB_INVALID_URL`, `WEB_BLOCKED_URL`, `WEB_FETCH_TOO_LARGE`, `WEB_FETCH_TIMEOUT`, `WEB_REDIRECT_BLOCKED`, `WEB_UNSUPPORTED_CONTENT_TYPE`, `WEB_ABORTED`, or `WEB_PROVIDER_ERROR`. `WEB_UNSUPPORTED_CONTENT_TYPE` covers unsupported media types, unsupported charset declarations, and invalid UTF-8 during malformed-declaration recovery. A `WEB_PROVIDER_ERROR` from a transport failure names the underlying system error, such as `getaddrinfo ENOTFOUND host`, `connect ECONNREFUSED addr:port`, or a TLS certificate error; it lists at most four connection attempts, counts the rest, and keeps at most 500 characters of the reason. Direct callers can route on the code; the model-facing `web_fetch` tool surfaces the failure text to the model under its own error wrapper. +Failures throw `WebError` with a machine-routable code: `WEB_INVALID_URL`, `WEB_BLOCKED_URL`, `WEB_FETCH_TOO_LARGE`, `WEB_FETCH_TIMEOUT`, `WEB_REDIRECT_BLOCKED`, `WEB_UNSUPPORTED_CONTENT_TYPE`, `WEB_ABORTED`, a transport failure code, or `WEB_PROVIDER_ERROR`. `WEB_UNSUPPORTED_CONTENT_TYPE` covers unsupported media types, unsupported charset declarations, and invalid UTF-8 during malformed-declaration recovery. A network failure before or during the response is classified by its system error code as `WEB_FETCH_DNS_FAILED`, `WEB_FETCH_CONNECTION_REFUSED`, `WEB_FETCH_CONNECTION_TIMEOUT`, `WEB_FETCH_CERTIFICATE_INVALID`, `WEB_FETCH_CONNECTION_INTERRUPTED`, or `WEB_FETCH_NETWORK_UNREACHABLE`; a missing, unrecognized, or mixed code yields `WEB_FETCH_NETWORK_ERROR`. Its message states the class, the system code when known, and the underlying error, for example `web fetch failed: could not resolve the host name (ENOTFOUND): getaddrinfo ENOTFOUND host`. The detail lists at most four connection attempts, counts the rest, and keeps at most 500 characters. Direct callers can route on the code; the model-facing `web_fetch` tool surfaces the failure text to the model under its own error wrapper. ----- @@ -92,6 +92,7 @@ The package is built on one separation and one layered timeout: |---|---| | [`src/index.ts`](src/index.ts) | Plugin entry: config schema, limit validation, provider registration | | [`src/provider.ts`](src/provider.ts) | The `HttpFetchProvider`: transport, redirect following, capped reads, charset decoding | +| [`src/transport-failure.ts`](src/transport-failure.ts) | Transport failure classes: system error code to `WEB_FETCH_*` code, summary, and bounded detail | | [`src/policy.ts`](src/policy.ts) | URL validation, same-origin checks, content-type classification, charset parsing | ### Read path @@ -119,7 +120,7 @@ Read these pages when the package-level contract is not enough. They move from t ## Model Experience -Indirectly, through `dsh-tool-web`, which renders this provider's `maxBodyChars`-bounded decoded text or markdown-shaped HTML under its fetch-result wrapper while redirects, headers, and transport limits remain hidden. +Indirectly, through `dsh-tool-web`, which renders this provider's `maxBodyChars`-bounded decoded text or markdown-shaped HTML under its fetch-result wrapper while redirects, headers, and transport limits remain hidden. A network failure reaches the model as its classified message. #### KV Cache effect diff --git a/packages/web/web-fetch-http/README.zh.md b/packages/web/web-fetch-http/README.zh.md index ca1be3eb39..9116cf3054 100644 --- a/packages/web/web-fetch-http/README.zh.md +++ b/packages/web/web-fetch-http/README.zh.md @@ -67,7 +67,7 @@ const page = await ctx.web.fetch({ url: 'https://example.com' }) ### 失败与恢复 -失败会抛出 `WebError`,其中包含可供程序路由的错误码:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_REDIRECT_BLOCKED`、`WEB_UNSUPPORTED_CONTENT_TYPE`、`WEB_ABORTED` 或 `WEB_PROVIDER_ERROR`。`WEB_UNSUPPORTED_CONTENT_TYPE` 涵盖不支持的媒体类型、不支持的 charset 声明,以及畸形声明恢复过程中遇到的非法 UTF-8。传输失败产生的 `WEB_PROVIDER_ERROR` 会给出底层系统错误,例如 `getaddrinfo ENOTFOUND host`、`connect ECONNREFUSED addr:port` 或 TLS 证书错误;最多列出四次连接尝试,其余只计数,原因文本最多保留 500 个字符。直接调用方可以按错误码路由;面向模型的 `web_fetch` 工具会在自己的错误包装层内把失败文本呈现给模型。 +失败会抛出 `WebError`,其中包含可供程序路由的错误码:`WEB_INVALID_URL`、`WEB_BLOCKED_URL`、`WEB_FETCH_TOO_LARGE`、`WEB_FETCH_TIMEOUT`、`WEB_REDIRECT_BLOCKED`、`WEB_UNSUPPORTED_CONTENT_TYPE`、`WEB_ABORTED`、某个传输故障错误码,或 `WEB_PROVIDER_ERROR`。`WEB_UNSUPPORTED_CONTENT_TYPE` 涵盖不支持的媒体类型、不支持的 charset 声明,以及畸形声明恢复过程中遇到的非法 UTF-8。响应之前或响应期间发生的网络故障会按其系统错误码归类为 `WEB_FETCH_DNS_FAILED`、`WEB_FETCH_CONNECTION_REFUSED`、`WEB_FETCH_CONNECTION_TIMEOUT`、`WEB_FETCH_CERTIFICATE_INVALID`、`WEB_FETCH_CONNECTION_INTERRUPTED` 或 `WEB_FETCH_NETWORK_UNREACHABLE`;系统错误码缺失、无法识别或相互混杂时,结果为 `WEB_FETCH_NETWORK_ERROR`。错误消息会写明故障类别、已知时的系统错误码以及底层错误,例如 `web fetch failed: could not resolve the host name (ENOTFOUND): getaddrinfo ENOTFOUND host`。详情最多列出四次连接尝试,其余尝试只计数,且最多保留 500 个字符。直接调用方可以按错误码路由;面向模型的 `web_fetch` 工具会在自己的错误包装层内把失败文本呈现给模型。 ----- @@ -92,6 +92,7 @@ const page = await ctx.web.fetch({ url: 'https://example.com' }) |---|---| | [`src/index.ts`](src/index.ts) | 插件入口:配置 schema、上限验证、提供方注册 | | [`src/provider.ts`](src/provider.ts) | `HttpFetchProvider`:传输、重定向跟随、有界读取、charset 解码 | +| [`src/transport-failure.ts`](src/transport-failure.ts) | 传输故障类别:系统错误码到 `WEB_FETCH_*` 错误码的映射、摘要和有界详情 | | [`src/policy.ts`](src/policy.ts) | URL 校验、同源检查、内容类型分类、charset 解析 | ### 读取路径 @@ -119,7 +120,7 @@ const page = await ctx.web.fetch({ url: 'https://example.com' }) ## 模型体验 -间接地,通过 `dsh-tool-web`:该工具把本提供方经 `maxBodyChars` 限制的解码文本或由 HTML 转换得到的 markdown 置于抓取结果包装层内,而重定向、标头与传输上限保持隐藏。 +间接地,通过 `dsh-tool-web`:该工具把本提供方经 `maxBodyChars` 限制的解码文本或由 HTML 转换得到的 markdown 置于抓取结果包装层内,而重定向、标头与传输上限保持隐藏。网络故障会以其分类后的消息呈现给模型。 #### KV Cache 影响 diff --git a/packages/web/web-fetch-http/src/provider.ts b/packages/web/web-fetch-http/src/provider.ts index 47616c88ec..553a21c58e 100644 --- a/packages/web/web-fetch-http/src/provider.ts +++ b/packages/web/web-fetch-http/src/provider.ts @@ -10,6 +10,7 @@ import { WebError } from '@deepseek-ai/dsh-web' import type { WebFetchBody, WebFetchProvider, WebFetchRequest, WebFetchResult } from '@deepseek-ai/dsh-web' import { deadline, timeoutOf } from '@deepseek-ai/dsh-timeout' import type { Response } from 'undici' +import { classifyTransportFailure } from './transport-failure.ts' import { classifyContentType, decoderForCharset, isSameOrigin, parseCharset, validateFetchUrl } from './policy.ts' /** Resolved provider limits (the plugin's schemastery Config supplies defaults). */ @@ -249,45 +250,12 @@ function resolveRedirect(location: string, base: URL): URL { * recovering OUR reason means our timeout fired (`WEB_FETCH_TIMEOUT`); any other * abort — an upstream cancel, or a foreign/outer deadline's timeout under * nesting — is `WEB_ABORTED`; a throw with the signal NOT aborted is a - * transport/network failure (`WEB_PROVIDER_ERROR`). + * transport failure, classified by {@link classifyTransportFailure}. */ function translateAbortOrNetwork(error: unknown, signal: AbortSignal): WebError { const timeout = timeoutOf(signal, 'WEB_FETCH_TIMEOUT') if (timeout !== undefined) return new WebError('web fetch timed out', 'WEB_FETCH_TIMEOUT', { cause: timeout }) if (signal.aborted) return new WebError('web fetch aborted', 'WEB_ABORTED', { cause: error }) - const reason = networkReason(error) - const bounded = reason.length > MAX_REASON_CHARS ? `${reason.slice(0, MAX_REASON_CHARS)}…` : reason - return new WebError(`web fetch failed: ${bounded}`, 'WEB_PROVIDER_ERROR', { cause: error }) -} - -/** Cause hops followed below a transport rejection; a deeper or cyclic chain is cut there. */ -const MAX_CAUSE_HOPS = 4 - -/** `AggregateError` members named in a transport failure; the rest are counted. */ -const MAX_ATTEMPTS = 4 - -/** Characters of a transport failure reason kept in the model-visible message. */ -const MAX_REASON_CHARS = 500 - -/** - * Name the innermost cause of a transport failure. Undici rejects with a generic - * `TypeError: fetch failed` whose `cause` holds the system error, such as - * `getaddrinfo ENOTFOUND host` or `connect ECONNREFUSED addr:port`; a connection - * attempt across several resolved addresses nests those errors in an `AggregateError`, - * whose members are expanded one level deep. An empty innermost message falls back to - * the rejection itself. - * @param error - the rejection or one `AggregateError` member. - * @param nested - whether `error` is an `AggregateError` member. - * @returns the failure reason, before the caller's character cap. - */ -function networkReason(error: unknown, nested = false): string { - let current = error - for (let hop = 0; hop < MAX_CAUSE_HOPS && current instanceof Error && current.cause !== undefined; hop++) current = current.cause - if (!nested && current instanceof AggregateError && current.errors.length > 0) { - const named = current.errors.slice(0, MAX_ATTEMPTS).map(member => networkReason(member, true)) - const rest = current.errors.length - named.length - return named.join('; ') + (rest > 0 ? `; ${rest} more` : '') - } - const message = current instanceof Error ? current.message : String(current) - return message === '' ? String(error) : message + const failure = classifyTransportFailure(error) + return new WebError(`web fetch failed: ${failure.message}`, failure.code, { cause: error }) } diff --git a/packages/web/web-fetch-http/src/transport-failure.ts b/packages/web/web-fetch-http/src/transport-failure.ts new file mode 100644 index 0000000000..45a5a477a8 --- /dev/null +++ b/packages/web/web-fetch-http/src/transport-failure.ts @@ -0,0 +1,121 @@ +/** + * Classification of fetch transport failures: maps the system or undici error code found in a + * rejection's cause chain to a stable `WebError` code and a short model-visible summary, and keeps + * a bounded technical detail. + * @module @deepseek-ai/dsh-web-fetch-http/transport-failure + */ + +/** A classified transport failure. */ +export interface TransportFailure { + /** Stable `WebError` code of the failure class. */ + code: string + /** Model-visible text: the class summary, the system code when known, and the bounded detail. */ + message: string +} + +/** One failure class: its `WebError` code, summary, and the system codes it covers. */ +interface FailureClass { + readonly code: string + readonly summary: string + readonly systemCodes: readonly string[] +} + +/** The class a dual-stack connection attempt yields when its address family has no route. */ +const UNREACHABLE: FailureClass = { + code: 'WEB_FETCH_NETWORK_UNREACHABLE', + summary: 'the network or host is unreachable', + systemCodes: ['ENETUNREACH', 'EHOSTUNREACH', 'ENETDOWN', 'EHOSTDOWN'], +} + +const FAILURE_CLASSES: readonly FailureClass[] = [ + { + code: 'WEB_FETCH_DNS_FAILED', + summary: 'could not resolve the host name', + systemCodes: ['ENOTFOUND', 'EAI_AGAIN', 'EAI_FAIL', 'EAI_NONAME', 'EAI_NODATA'], + }, + { code: 'WEB_FETCH_CONNECTION_REFUSED', summary: 'the server refused the connection', systemCodes: ['ECONNREFUSED'] }, + { code: 'WEB_FETCH_CONNECTION_TIMEOUT', summary: 'the connection timed out', systemCodes: ['ETIMEDOUT', 'UND_ERR_CONNECT_TIMEOUT'] }, + { + code: 'WEB_FETCH_CERTIFICATE_INVALID', + summary: 'the server certificate could not be verified', + systemCodes: [ + 'CERT_HAS_EXPIRED', 'CERT_NOT_YET_VALID', 'CERT_REVOKED', 'CERT_UNTRUSTED', 'CERT_REJECTED', + 'CERT_SIGNATURE_FAILURE', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'SELF_SIGNED_CERT_IN_CHAIN', + 'UNABLE_TO_GET_ISSUER_CERT', 'UNABLE_TO_GET_ISSUER_CERT_LOCALLY', 'UNABLE_TO_VERIFY_LEAF_SIGNATURE', + 'UNABLE_TO_DECRYPT_CERT_SIGNATURE', 'CERT_CHAIN_TOO_LONG', 'INVALID_CA', 'HOSTNAME_MISMATCH', + 'ERR_TLS_CERT_ALTNAME_INVALID', + ], + }, + { + code: 'WEB_FETCH_CONNECTION_INTERRUPTED', + summary: 'the connection was interrupted', + systemCodes: ['ECONNRESET', 'ECONNABORTED', 'EPIPE', 'UND_ERR_SOCKET'], + }, + UNREACHABLE, +] + +/** Code and summary of a failure whose system code is missing, mixed, or unrecognized. */ +const UNCLASSIFIED = { code: 'WEB_FETCH_NETWORK_ERROR', summary: 'the network request failed' } as const + +/** Cause hops followed below a transport rejection; a deeper or cyclic chain is cut there. */ +const MAX_CAUSE_HOPS = 4 + +/** `AggregateError` members named in a transport failure; the rest are counted. */ +const MAX_ATTEMPTS = 4 + +/** Characters of the technical detail kept in the message; the summary is never cut. */ +const MAX_DETAIL_CHARS = 500 + +/** + * Classify a transport rejection. Undici rejects with a generic `TypeError: fetch failed` whose + * `cause` holds the system error, such as `getaddrinfo ENOTFOUND host`; a connection attempt across + * several resolved addresses nests those errors in an `AggregateError`. A failure is classified only + * when its code, or every attempt's code, belongs to one class; an unreachable attempt beside attempts + * of one other class, as an IPv6 attempt on an IPv4-only network, takes that other class. + * @param error - the rejection of the request or body read. + * @returns the failure's code and model-visible message. + */ +export function classifyTransportFailure(error: unknown): TransportFailure { + const innermost = innermostCause(error) + const aggregate = innermost instanceof AggregateError && innermost.errors.length > 0 + const attempts = aggregate ? innermost.errors.map(innermostCause) : [innermost] + const systemCodes = attempts.map(systemCodeOf) + const classes = new Set(systemCodes.map(code => FAILURE_CLASSES.find(entry => code !== undefined && entry.systemCodes.includes(code)))) + if (classes.size === 2) classes.delete(UNREACHABLE) + const [only] = classes + const failure = classes.size === 1 && only !== undefined ? only : UNCLASSIFIED + const systemCode = new Set(systemCodes).size === 1 ? systemCodes[0] : undefined + const detail = bounded(aggregate ? attemptsDetail(attempts, error) : messageOf(innermost, error)) + return { code: failure.code, message: `${failure.summary}${systemCode === undefined ? '' : ` (${systemCode})`}: ${detail}` } +} + +/** Follow `cause` up to the hop cap. */ +function innermostCause(error: unknown): unknown { + let current = error + for (let hop = 0; hop < MAX_CAUSE_HOPS && current instanceof Error && current.cause !== undefined; hop++) current = current.cause + return current +} + +/** The string `code` property Node and undici attach to system errors. */ +function systemCodeOf(error: unknown): string | undefined { + if (!(error instanceof Error) || !('code' in error)) return undefined + return typeof error.code === 'string' ? error.code : undefined +} + +/** Name at most `MAX_ATTEMPTS` attempts and count the rest. */ +function attemptsDetail(attempts: readonly unknown[], fallback: unknown): string { + const named = attempts.slice(0, MAX_ATTEMPTS).map(attempt => messageOf(attempt, fallback)) + const rest = attempts.length - named.length + return named.join('; ') + (rest > 0 ? `; ${rest} more` : '') +} + +/** An error's message, or the rejection's text when the message is empty. */ +function messageOf(error: unknown, fallback: unknown): string { + const message = error instanceof Error ? error.message : String(error) + return message === '' ? String(fallback) : message +} + +/** Cut a detail to `MAX_DETAIL_CHARS`. */ +function bounded(detail: string): string { + return detail.length > MAX_DETAIL_CHARS ? `${detail.slice(0, MAX_DETAIL_CHARS)}…` : detail +} diff --git a/packages/web/web-fetch-http/tests/fetch-http.spec.ts b/packages/web/web-fetch-http/tests/fetch-http.spec.ts index 96dbf6cab5..ea51fd12ea 100644 --- a/packages/web/web-fetch-http/tests/fetch-http.spec.ts +++ b/packages/web/web-fetch-http/tests/fetch-http.spec.ts @@ -452,15 +452,15 @@ describe('HttpFetchProvider invalid URLs and abort', () => { .rejects.toThrow(expect.objectContaining({ code: 'WEB_FETCH_TIMEOUT' })) }) - it('maps a connection failure to WEB_PROVIDER_ERROR naming the transport error', async () => { + it('classifies a closed connection and names the transport error', async () => { // The test owns this listener throughout; it closes each connection once the request arrives. const closing = createNetServer(socket => socket.once('data', () => socket.end())) await new Promise(resolve => closing.listen(0, '127.0.0.1', resolve)) const { port } = closing.address() as AddressInfo try { await expect(provider().fetch({ url: `http://127.0.0.1:${port}/` })).rejects.toThrow(expect.objectContaining({ - code: 'WEB_PROVIDER_ERROR', - message: 'web fetch failed: other side closed', + code: 'WEB_FETCH_CONNECTION_INTERRUPTED', + message: 'web fetch failed: the connection was interrupted (UND_ERR_SOCKET): other side closed', })) } finally { await new Promise(resolve => closing.close(() => { resolve() })) diff --git a/packages/web/web-fetch-http/tests/network-error.spec.ts b/packages/web/web-fetch-http/tests/network-error.spec.ts index 6fa4575d25..61bca8c704 100644 --- a/packages/web/web-fetch-http/tests/network-error.spec.ts +++ b/packages/web/web-fetch-http/tests/network-error.spec.ts @@ -15,73 +15,151 @@ const provider = new HttpFetchProvider({ userAgent: 'test-agent/1.0', }) -async function messageFor(error: unknown): Promise { - failure.value = error - const rejection = await provider.fetch({ url: 'http://origin.test/' }).then(() => undefined, (thrown: unknown) => thrown) - expect(rejection).toMatchObject({ code: 'WEB_PROVIDER_ERROR' }) - return (rejection as Error).message +/** A Node-style system error carrying `code`. */ +function systemError(message: string, code: string): Error { + return Object.assign(new Error(message), { code }) } -describe('HttpFetchProvider transport failure text', () => { - it('names every address of a multi-address connection failure', async () => { +/** Undici's generic rejection around a cause. */ +function fetchFailed(cause: unknown): TypeError { + return new TypeError('fetch failed', { cause }) +} + +async function rejectionFor(error: unknown): Promise<{ code: string; message: string }> { + failure.value = error + const rejection = await provider.fetch({ url: 'http://origin.test/' }).then(() => undefined, (thrown: unknown) => thrown) + expect(rejection).toBeInstanceOf(Error) + const { code, message } = rejection as Error & { code: string } + return { code, message } +} + +describe('HttpFetchProvider transport failure classes', () => { + it.each([ + ['getaddrinfo ENOTFOUND origin.test', 'ENOTFOUND', 'WEB_FETCH_DNS_FAILED', 'could not resolve the host name'], + ['getaddrinfo EAI_AGAIN origin.test', 'EAI_AGAIN', 'WEB_FETCH_DNS_FAILED', 'could not resolve the host name'], + ['connect ECONNREFUSED 127.0.0.1:8080', 'ECONNREFUSED', 'WEB_FETCH_CONNECTION_REFUSED', 'the server refused the connection'], + ['Connect Timeout Error', 'UND_ERR_CONNECT_TIMEOUT', 'WEB_FETCH_CONNECTION_TIMEOUT', 'the connection timed out'], + ['read ETIMEDOUT', 'ETIMEDOUT', 'WEB_FETCH_CONNECTION_TIMEOUT', 'the connection timed out'], + ['Hostname mismatch', 'HOSTNAME_MISMATCH', 'WEB_FETCH_CERTIFICATE_INVALID', 'the server certificate could not be verified'], + ['self-signed certificate', 'DEPTH_ZERO_SELF_SIGNED_CERT', 'WEB_FETCH_CERTIFICATE_INVALID', 'the server certificate could not be verified'], + ['certificate has expired', 'CERT_HAS_EXPIRED', 'WEB_FETCH_CERTIFICATE_INVALID', 'the server certificate could not be verified'], + ["Hostname/IP does not match certificate's altnames", 'ERR_TLS_CERT_ALTNAME_INVALID', 'WEB_FETCH_CERTIFICATE_INVALID', 'the server certificate could not be verified'], + ['read ECONNRESET', 'ECONNRESET', 'WEB_FETCH_CONNECTION_INTERRUPTED', 'the connection was interrupted'], + ['other side closed', 'UND_ERR_SOCKET', 'WEB_FETCH_CONNECTION_INTERRUPTED', 'the connection was interrupted'], + ['connect ENETUNREACH 10.0.0.1:443', 'ENETUNREACH', 'WEB_FETCH_NETWORK_UNREACHABLE', 'the network or host is unreachable'], + ['connect EHOSTUNREACH 10.0.0.1:443', 'EHOSTUNREACH', 'WEB_FETCH_NETWORK_UNREACHABLE', 'the network or host is unreachable'], + ])('classifies %s', async (detail, systemCode, code, summary) => { + expect(await rejectionFor(fetchFailed(systemError(detail, systemCode)))).toEqual({ + code, + message: `web fetch failed: ${summary} (${systemCode}): ${detail}`, + }) + }) + + it('reports an unrecognized system code as a generic network failure that keeps the code', async () => { + expect(await rejectionFor(fetchFailed(systemError('write EPROTO', 'EPROTO')))).toEqual({ + code: 'WEB_FETCH_NETWORK_ERROR', + message: 'web fetch failed: the network request failed (EPROTO): write EPROTO', + }) + }) + + it('ignores a non-string code', async () => { + expect(await rejectionFor(fetchFailed(Object.assign(new Error('socket hang up'), { code: -54 })))).toEqual({ + code: 'WEB_FETCH_NETWORK_ERROR', + message: 'web fetch failed: the network request failed: socket hang up', + }) + }) + + it('reports a failure without a system code as a generic network failure', async () => { + expect(await rejectionFor(fetchFailed(new Error('bad port')))).toEqual({ + code: 'WEB_FETCH_NETWORK_ERROR', + message: 'web fetch failed: the network request failed: bad port', + }) + }) +}) + +describe('HttpFetchProvider multi-address transport failures', () => { + it('classifies attempts that share one class and names each address', async () => { const attempts = new AggregateError([ - new Error('connect ECONNREFUSED ::1:8080'), - new Error('connect ECONNREFUSED 127.0.0.1:8080'), + systemError('connect ECONNREFUSED ::1:8080', 'ECONNREFUSED'), + systemError('connect ECONNREFUSED 127.0.0.1:8080', 'ECONNREFUSED'), ]) - expect(await messageFor(new TypeError('fetch failed', { cause: attempts }))) - .toBe('web fetch failed: connect ECONNREFUSED ::1:8080; connect ECONNREFUSED 127.0.0.1:8080') + expect(await rejectionFor(fetchFailed(attempts))).toEqual({ + code: 'WEB_FETCH_CONNECTION_REFUSED', + message: 'web fetch failed: the server refused the connection (ECONNREFUSED): connect ECONNREFUSED ::1:8080; connect ECONNREFUSED 127.0.0.1:8080', + }) }) - it('names a DNS failure', async () => { - const dns = new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND origin.test') }) - expect(await messageFor(dns)).toBe('web fetch failed: getaddrinfo ENOTFOUND origin.test') + it('classifies an unreachable address family attempt by the other attempts', async () => { + const attempts = new AggregateError([ + systemError('connect ENETUNREACH 2001:db8::1:443', 'ENETUNREACH'), + systemError('connect ECONNREFUSED 192.0.2.1:443', 'ECONNREFUSED'), + ]) + expect(await rejectionFor(fetchFailed(attempts))).toEqual({ + code: 'WEB_FETCH_CONNECTION_REFUSED', + message: 'web fetch failed: the server refused the connection: connect ENETUNREACH 2001:db8::1:443; connect ECONNREFUSED 192.0.2.1:443', + }) }) + it('does not classify attempts of two other classes', async () => { + const attempts = new AggregateError([ + systemError('connect ETIMEDOUT 2001:db8::1:443', 'ETIMEDOUT'), + systemError('connect ECONNREFUSED 192.0.2.1:443', 'ECONNREFUSED'), + ]) + expect(await rejectionFor(fetchFailed(attempts))).toEqual({ + code: 'WEB_FETCH_NETWORK_ERROR', + message: 'web fetch failed: the network request failed: connect ETIMEDOUT 2001:db8::1:443; connect ECONNREFUSED 192.0.2.1:443', + }) + }) + + it('names exactly four attempts without a count', async () => { + const attempts = new AggregateError([1, 2, 3, 4].map(n => new Error(`attempt ${n}`))) + expect((await rejectionFor(fetchFailed(attempts))).message) + .toBe('web fetch failed: the network request failed: attempt 1; attempt 2; attempt 3; attempt 4') + }) + + it('names four of five attempts and counts the rest', async () => { + const attempts = new AggregateError([1, 2, 3, 4, 5].map(n => new Error(`attempt ${n}`))) + expect((await rejectionFor(fetchFailed(attempts))).message) + .toBe('web fetch failed: the network request failed: attempt 1; attempt 2; attempt 3; attempt 4; 1 more') + }) + + it('does not expand an AggregateError nested in an attempt', async () => { + const inner = new AggregateError([new Error('deep')], 'inner attempts') + expect((await rejectionFor(new AggregateError([inner]))).message).toBe('web fetch failed: the network request failed: inner attempts') + }) +}) + +describe('HttpFetchProvider transport failure detail', () => { it('stringifies a non-Error rejection', async () => { - expect(await messageFor('socket closed')).toBe('web fetch failed: socket closed') + expect((await rejectionFor('socket closed')).message).toBe('web fetch failed: the network request failed: socket closed') }) it('stringifies a non-Error innermost cause', async () => { - expect(await messageFor(new TypeError('fetch failed', { cause: 'socket closed' }))).toBe('web fetch failed: socket closed') + expect((await rejectionFor(fetchFailed('socket closed'))).message).toBe('web fetch failed: the network request failed: socket closed') }) it('cuts a cyclic cause chain', async () => { const first = new Error('first') const second = new Error('second', { cause: first }) first.cause = second - expect(await messageFor(first)).toBe('web fetch failed: first') - }) - - it('names exactly four attempts without a count', async () => { - const attempts = new AggregateError([1, 2, 3, 4].map(n => new Error(`attempt ${n}`))) - expect(await messageFor(new TypeError('fetch failed', { cause: attempts }))) - .toBe('web fetch failed: attempt 1; attempt 2; attempt 3; attempt 4') - }) - - it('names four of five attempts and counts the rest', async () => { - const attempts = new AggregateError([1, 2, 3, 4, 5].map(n => new Error(`attempt ${n}`))) - expect(await messageFor(new TypeError('fetch failed', { cause: attempts }))) - .toBe('web fetch failed: attempt 1; attempt 2; attempt 3; attempt 4; 1 more') + expect((await rejectionFor(first)).message).toBe('web fetch failed: the network request failed: first') }) it('follows four cause hops', async () => { let chain = new Error('hop 0') for (let hop = 1; hop <= 5; hop++) chain = new Error(`hop ${hop}`, { cause: chain }) - expect(await messageFor(chain)).toBe('web fetch failed: hop 1') - }) - - it('keeps 500 characters of a long reason', async () => { - expect(await messageFor(new Error('x'.repeat(500)))).toBe(`web fetch failed: ${'x'.repeat(500)}`) - expect(await messageFor(new Error('x'.repeat(501)))).toBe(`web fetch failed: ${'x'.repeat(500)}…`) - }) - - it('does not expand an AggregateError nested in an attempt', async () => { - const inner = new AggregateError([new Error('deep')], 'inner attempts') - expect(await messageFor(new AggregateError([inner]))).toBe('web fetch failed: inner attempts') + expect((await rejectionFor(chain)).message).toBe('web fetch failed: the network request failed: hop 1') }) it('falls back to the rejection when the innermost message is empty', async () => { - expect(await messageFor(new TypeError('fetch failed', { cause: new AggregateError([]) }))) - .toBe('web fetch failed: TypeError: fetch failed') + expect((await rejectionFor(fetchFailed(new AggregateError([])))).message) + .toBe('web fetch failed: the network request failed: TypeError: fetch failed') + }) + + it('keeps the full summary and 500 characters of the detail', async () => { + const long = (length: number) => fetchFailed(systemError('x'.repeat(length), 'ERR_TLS_CERT_ALTNAME_INVALID')) + const prefix = 'web fetch failed: the server certificate could not be verified (ERR_TLS_CERT_ALTNAME_INVALID): ' + expect((await rejectionFor(long(500))).message).toBe(`${prefix}${'x'.repeat(500)}`) + expect((await rejectionFor(long(501))).message).toBe(`${prefix}${'x'.repeat(500)}…`) }) }) diff --git a/packages/web/web-fetch-http/tests/proxy.spec.ts b/packages/web/web-fetch-http/tests/proxy.spec.ts index 3d30630828..1eaacea3e5 100644 --- a/packages/web/web-fetch-http/tests/proxy.spec.ts +++ b/packages/web/web-fetch-http/tests/proxy.spec.ts @@ -116,6 +116,9 @@ describe('fetching through a proxy', () => { const failure = new HttpFetchProvider(limits).fetch({ url: proxyTarget }) - await expect(failure).rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', message: 'web fetch failed: other side closed' })) + await expect(failure).rejects.toThrow(expect.objectContaining({ + code: 'WEB_FETCH_CONNECTION_INTERRUPTED', + message: 'web fetch failed: the connection was interrupted (UND_ERR_SOCKET): other side closed', + })) }) }) diff --git a/snapshots/session/web-fetch-transport-failure/session.v4.jsonl b/snapshots/session/web-fetch-transport-failure/session.v4.jsonl index 47f3191b9d..6d6cfbe5c3 100644 --- a/snapshots/session/web-fetch-transport-failure/session.v4.jsonl +++ b/snapshots/session/web-fetch-transport-failure/session.v4.jsonl @@ -14,7 +14,7 @@ {"type":"session/title","data":{"title":"Use the web_fetch tool exactly","messageSeqs":[8],"source":{"kind":"fallback"}}} {"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user wants me to use the web_fetch tool exactly once to fetch http://public.test:43117/menu.html, then reply with exactly \"DONE\". Let me do that."},{"type":"tool-call","id":"call_00_sxjOyfDYN07koiE7jiIa5326","name":"web_fetch","arguments":"{\"url\": \"http://public.test:43117/menu.html\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"{{message:4}}"},"usage":{"inputTokens":5405,"outputTokens":103,"cacheReadTokens":0,"reasoningTokens":44},"stream":[{"type":"chunk","time":1788699449132,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699449132,"index":0,"dt":[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," wants"," me"," to"," use"," the"," web","_f","etch"," tool"," exactly"," once"," to"," fetch"," http","://","public",".","test",":","431","17","/m","enu",".html",","," then"," reply"," with"," exactly"," \"","D","ONE","\"."," Let"," me"," do"," that","."]},{"type":"chunk","time":1788699449133,"chunk":{"type":"block-start","index":1,"blockType":"tool-call"}},{"type":"tool-call-chunks","time0":1788699449133,"index":1,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"id":"call_00_sxjOyfDYN07koiE7jiIa5326","name":"web_fetch","args":["","{","\"","url","\"",": ","\"","http","://","public",".","test",":","431","17","/m","enu",".html","\"","}"]},{"type":"chunk","time":1788699449133,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user wants me to use the web_fetch tool exactly once to fetch http://public.test:43117/menu.html, then reply with exactly \"DONE\". Let me do that."}}},{"type":"chunk","time":1788699449133,"chunk":{"type":"block-end","index":1,"block":{"type":"tool-call","id":"call_00_sxjOyfDYN07koiE7jiIa5326","name":"web_fetch","arguments":"{\"url\": \"http://public.test:43117/menu.html\"}"}}},{"type":"chunk","time":1788699449133,"chunk":{"type":"usage","usage":{"inputTokens":5405,"outputTokens":103,"cacheReadTokens":0,"reasoningTokens":44}}},{"type":"chunk","time":1788699449133,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"} {"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_00_sxjOyfDYN07koiE7jiIa5326","name":"web_fetch","arguments":"{\"url\": \"http://public.test:43117/menu.html\"}"}} -{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_sxjOyfDYN07koiE7jiIa5326"},"toolCallId":"call_00_sxjOyfDYN07koiE7jiIa5326","content":[{"type":"text","text":"Error: web fetch failed: other side closed"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"WebError","code":"WEB_PROVIDER_ERROR"}},"sourceEventSeqs":[14],"surfaceOp":"append"} +{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_00_sxjOyfDYN07koiE7jiIa5326"},"toolCallId":"call_00_sxjOyfDYN07koiE7jiIa5326","content":[{"type":"text","text":"Error: web fetch failed: the connection was interrupted (UND_ERR_SOCKET): other side closed"}],"isError":true,"id":"{{message:5}}"},"error":{"name":"WebError","code":"WEB_FETCH_CONNECTION_INTERRUPTED"}},"sourceEventSeqs":[14],"surfaceOp":"append"} {"type":"step/end","data":{"turn":1,"step":1}} {"type":"step/start","data":{"turn":1,"step":2}} {"type":"assistant/message","data":{"turn":1,"step":2,"message":{"role":"assistant","content":[{"type":"reasoning","text":"The user asked me to fetch the URL, then reply with exactly \"DONE\". I've fetched it. Now I just reply with \"DONE\"."},{"type":"text","text":"DONE"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-pro"},"id":"{{message:6}}"},"usage":{"inputTokens":239,"outputTokens":34,"cacheReadTokens":5376,"reasoningTokens":31},"stream":[{"type":"chunk","time":1788699449238,"chunk":{"type":"block-start","index":0,"blockType":"reasoning"}},{"type":"reasoning-chunks","time0":1788699449238,"index":0,"dt":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],"texts":["The"," user"," asked"," me"," to"," fetch"," the"," URL",","," then"," reply"," with"," exactly"," \"","D","ONE","\"."," I","'ve"," fetched"," it","."," Now"," I"," just"," reply"," with"," \"","D","ONE","\"."]},{"type":"chunk","time":1788699449238,"chunk":{"type":"block-start","index":1,"blockType":"text"}},{"type":"text-chunks","time0":1788699449238,"index":1,"dt":[0],"texts":["D","ONE"]},{"type":"chunk","time":1788699449238,"chunk":{"type":"block-end","index":0,"block":{"type":"reasoning","text":"The user asked me to fetch the URL, then reply with exactly \"DONE\". I've fetched it. Now I just reply with \"DONE\"."}}},{"type":"chunk","time":1788699449238,"chunk":{"type":"block-end","index":1,"block":{"type":"text","text":"DONE"}}},{"type":"chunk","time":1788699449238,"chunk":{"type":"usage","usage":{"inputTokens":239,"outputTokens":34,"cacheReadTokens":5376,"reasoningTokens":31}}},{"type":"chunk","time":1788699449238,"chunk":{"type":"finish","reason":{"kind":"stop"}}}]},"surfaceOp":"append"} diff --git a/snapshots/web/web-fetch-failure-row/snapshot.yml b/snapshots/web/web-fetch-failure-row/snapshot.yml new file mode 100644 index 0000000000..93ec4ccab9 --- /dev/null +++ b/snapshots/web/web-fetch-failure-row/snapshot.yml @@ -0,0 +1,9 @@ +version: 1 +scenario: web-fetch-failure-row +profile: web +composition: web-fetch-transport-failure +recording: authored +header: + class: web-fetch-transport-failure +session: + source: ../../session/web-fetch-transport-failure/session.v4.jsonl diff --git a/snapshots/web/web-fetch-failure-row/ui.expected.md b/snapshots/web/web-fetch-failure-row/ui.expected.md new file mode 100644 index 0000000000..f6413cbc1c --- /dev/null +++ b/snapshots/web/web-fetch-failure-row/ui.expected.md @@ -0,0 +1,33 @@ +- banner: + - navigation "Session hierarchy": Use the web_fetch tool exactly + - button "More actions" + - button "Open right sidebar" + - tablist: + - tab "Chat" [selected] + - tab "Trajectory" + - button "More conversation views" +- text: Use the web_fetch tool exactly once to fetch http://public.test:43117/menu.html, then reply with exactly DONE. Do not describe the content. 7/26 {{clock}} +- button "Copy" +- status: Completed +- button "Completed in {{duration}}" [expanded] +- button "Visited web pages" [expanded] +- button "Context injection runtime-context" +- button "Think The user wants me to use the web_fetch tool exactly once to fetch http://public.test:43117/menu.html, then reply with exactly \"DONE\". Let me do that." +- text: Failed +- button "Fetch Connection interrupted. Try again later." [expanded] +- text: "OUT Error: web fetch failed: the connection was interrupted (UND_ERR_SOCKET): other side closed" +- button "Inspect" +- button "Think The user asked me to fetch the URL, then reply with exactly \"DONE\". I've fetched it. Now I just reply with \"DONE\"." +- paragraph: DONE +- button "Copy" +- button "Good response" +- button "Bad response" +- button "Branch into a new conversation" +- text: 7/26 {{clock}} +- textbox "Message or run a task, / commands, @ files or sessions" +- button "Add files or run commands" +- 'button "Access mode, current: Workspace Write"': Workspace Write +- button "Select model" +- button "Send message" [disabled] +- button "1 turns 2 steps · {{throughput}} tok/s": 1 turns 2 steps{{throughput}} tok/s +- button "11.2K tok · Cache hit 49%": 11.2K tokCache hit 49%