From 02e5c89fddf37643e2372d45ccafe00e74289a26 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 18:29:53 +0800 Subject: [PATCH 01/15] fix(web-fetch-http): name the underlying cause of transport failures Co-authored-by: Elevator14B <219823454+Elevator14B@users.noreply.github.com> --- packages/web/web-fetch-http/README.i18n.yaml | 4 +- packages/web/web-fetch-http/README.md | 2 +- packages/web/web-fetch-http/README.zh.md | 2 +- packages/web/web-fetch-http/src/provider.ts | 31 +++++++- .../web-fetch-http/tests/fetch-http.spec.ts | 14 ++-- .../tests/network-error.spec.ts | 70 +++++++++++++++++++ 6 files changed, 114 insertions(+), 9 deletions(-) create mode 100644 packages/web/web-fetch-http/tests/network-error.spec.ts diff --git a/packages/web/web-fetch-http/README.i18n.yaml b/packages/web/web-fetch-http/README.i18n.yaml index e38ab6fa9e..cd38c41c24 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: 34095d9d4231d73a - zh: be0ed903adbb124f + en: 7767aae6d0d5d969 + zh: ba93fa27403d4e6f /deepseek-ai-dsh-web-fetch-http/understand-the-implementation: en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb diff --git a/packages/web/web-fetch-http/README.md b/packages/web/web-fetch-http/README.md index 4aecd7b649..7e0ab8897c 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. 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`, 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. 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. ----- diff --git a/packages/web/web-fetch-http/README.zh.md b/packages/web/web-fetch-http/README.zh.md index ba4092e23a..40f97cd6f2 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_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_PROVIDER_ERROR` 会给出底层系统错误,例如 `getaddrinfo ENOTFOUND host`、`connect ECONNREFUSED addr:port` 或 TLS 证书错误。直接调用方可以按错误码路由;面向模型的 `web_fetch` 工具会在自己的错误包装层内把失败文本呈现给模型。 ----- diff --git a/packages/web/web-fetch-http/src/provider.ts b/packages/web/web-fetch-http/src/provider.ts index a8b0217593..487593a107 100644 --- a/packages/web/web-fetch-http/src/provider.ts +++ b/packages/web/web-fetch-http/src/provider.ts @@ -255,5 +255,34 @@ 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 }) - return new WebError(`web fetch failed: ${String(error)}`, 'WEB_PROVIDER_ERROR', { cause: error }) + return new WebError(`web fetch failed: ${networkReason(error)}`, 'WEB_PROVIDER_ERROR', { cause: error }) +} + +/** Causes followed below a transport rejection; a deeper or cyclic chain is cut there. */ +const MAX_CAUSES = 4 + +/** `AggregateError` members named in a transport failure; the rest are counted. */ +const MAX_ATTEMPTS = 4 + +/** + * 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 bounded failure reason. + */ +function networkReason(error: unknown, nested = false): string { + let current = error + for (let hop = 0; hop < MAX_CAUSES && 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 } 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 c66876cc5b..9047969d91 100644 --- a/packages/web/web-fetch-http/tests/fetch-http.spec.ts +++ b/packages/web/web-fetch-http/tests/fetch-http.spec.ts @@ -452,10 +452,16 @@ describe('HttpFetchProvider invalid URLs and abort', () => { .rejects.toThrow(expect.objectContaining({ code: 'WEB_FETCH_TIMEOUT' })) }) - it('maps a connection failure to WEB_PROVIDER_ERROR', async () => { - // Port 1 on loopback is not listening: a real connection failure (not abort). - await expect(provider().fetch({ url: 'http://127.0.0.1:1/' })) - .rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' })) + it('maps a connection failure to WEB_PROVIDER_ERROR naming the system error', async () => { + // A closed listener's port refuses the connection: a real transport failure (not abort). + const closed = createServer() + await new Promise(resolve => closed.listen(0, '127.0.0.1', resolve)) + const { port } = closed.address() as AddressInfo + await new Promise(resolve => closed.close(() => { resolve() })) + await expect(provider().fetch({ url: `http://127.0.0.1:${port}/` })).rejects.toThrow(expect.objectContaining({ + code: 'WEB_PROVIDER_ERROR', + message: `web fetch failed: connect ECONNREFUSED 127.0.0.1:${port}`, + })) }) }) diff --git a/packages/web/web-fetch-http/tests/network-error.spec.ts b/packages/web/web-fetch-http/tests/network-error.spec.ts new file mode 100644 index 0000000000..e8edd37030 --- /dev/null +++ b/packages/web/web-fetch-http/tests/network-error.spec.ts @@ -0,0 +1,70 @@ +import { describe, expect, it, vi } from 'vitest' +import { HttpFetchProvider } from '@deepseek-ai/dsh-web-fetch-http' + +const failure = vi.hoisted(() => ({ value: undefined as unknown })) + +vi.mock('undici', () => ({ + fetch: async () => { throw failure.value }, +})) + +const provider = new HttpFetchProvider({ + maxResponseBytes: 1_000, + maxBodyChars: 1_000, + timeoutMs: 5_000, + maxRedirects: 0, + 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 +} + +describe('HttpFetchProvider transport failure text', () => { + it('names every address of a multi-address connection failure', async () => { + const attempts = new AggregateError([ + new Error('connect ECONNREFUSED ::1:8080'), + new Error('connect ECONNREFUSED 127.0.0.1:8080'), + ]) + expect(await messageFor(new TypeError('fetch failed', { cause: attempts }))) + .toBe('web fetch failed: 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('stringifies a non-Error rejection', async () => { + expect(await messageFor('socket closed')).toBe('web fetch 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') + }) + + 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 at most four attempts and counts the rest', async () => { + const attempts = new AggregateError([1, 2, 3, 4, 5, 6].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; 2 more') + }) + + 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') + }) + + 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') + }) +}) From 38921fcac58a44cafd8b8c100f969bc59c2347e5 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 19:04:52 +0800 Subject: [PATCH 02/15] fix(web-fetch-http): bound the transport failure reason and own the test listener Co-authored-by: Elevator14B <219823454+Elevator14B@users.noreply.github.com> --- packages/web/web-fetch-http/src/provider.ts | 15 +++++++---- .../web-fetch-http/tests/fetch-http.spec.ts | 25 +++++++++++-------- .../tests/network-error.spec.ts | 25 ++++++++++++++++--- 3 files changed, 45 insertions(+), 20 deletions(-) diff --git a/packages/web/web-fetch-http/src/provider.ts b/packages/web/web-fetch-http/src/provider.ts index 487593a107..47616c88ec 100644 --- a/packages/web/web-fetch-http/src/provider.ts +++ b/packages/web/web-fetch-http/src/provider.ts @@ -255,15 +255,20 @@ 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 }) - return new WebError(`web fetch failed: ${networkReason(error)}`, 'WEB_PROVIDER_ERROR', { 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 }) } -/** Causes followed below a transport rejection; a deeper or cyclic chain is cut there. */ -const MAX_CAUSES = 4 +/** 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 @@ -273,11 +278,11 @@ const MAX_ATTEMPTS = 4 * the rejection itself. * @param error - the rejection or one `AggregateError` member. * @param nested - whether `error` is an `AggregateError` member. - * @returns the bounded failure reason. + * @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_CAUSES && current instanceof Error && current.cause !== undefined; hop++) current = current.cause + 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 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 9047969d91..96dbf6cab5 100644 --- a/packages/web/web-fetch-http/tests/fetch-http.spec.ts +++ b/packages/web/web-fetch-http/tests/fetch-http.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http' -import { AddressInfo } from 'node:net' +import { AddressInfo, createServer as createNetServer } from 'node:net' import { Context } from '@deepseek-ai/cordis' import WebRuntime from '@deepseek-ai/dsh-web' import { HttpFetchProvider, LOCAL_FETCH_PROVIDER_ID } from '@deepseek-ai/dsh-web-fetch-http' @@ -452,16 +452,19 @@ 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 system error', async () => { - // A closed listener's port refuses the connection: a real transport failure (not abort). - const closed = createServer() - await new Promise(resolve => closed.listen(0, '127.0.0.1', resolve)) - const { port } = closed.address() as AddressInfo - await new Promise(resolve => closed.close(() => { resolve() })) - await expect(provider().fetch({ url: `http://127.0.0.1:${port}/` })).rejects.toThrow(expect.objectContaining({ - code: 'WEB_PROVIDER_ERROR', - message: `web fetch failed: connect ECONNREFUSED 127.0.0.1:${port}`, - })) + it('maps a connection failure to WEB_PROVIDER_ERROR naming 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', + })) + } 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 e8edd37030..6fa4575d25 100644 --- a/packages/web/web-fetch-http/tests/network-error.spec.ts +++ b/packages/web/web-fetch-http/tests/network-error.spec.ts @@ -1,7 +1,7 @@ import { describe, expect, it, vi } from 'vitest' import { HttpFetchProvider } from '@deepseek-ai/dsh-web-fetch-http' -const failure = vi.hoisted(() => ({ value: undefined as unknown })) +const failure = vi.hoisted((): { value: unknown } => ({ value: undefined })) vi.mock('undici', () => ({ fetch: async () => { throw failure.value }, @@ -52,10 +52,27 @@ describe('HttpFetchProvider transport failure text', () => { expect(await messageFor(first)).toBe('web fetch failed: first') }) - it('names at most four attempts and counts the rest', async () => { - const attempts = new AggregateError([1, 2, 3, 4, 5, 6].map(n => new Error(`attempt ${n}`))) + 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; 2 more') + .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') + }) + + 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 () => { From 2e65fefdd97e5e34840abd5884df1758c03bb6ca Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 19:24:00 +0800 Subject: [PATCH 03/15] test(web-fetch-http): pin proxy failure text and document reason bounds Co-authored-by: Elevator14B <219823454+Elevator14B@users.noreply.github.com> --- packages/web/web-fetch-http/README.i18n.yaml | 4 ++-- packages/web/web-fetch-http/README.md | 2 +- packages/web/web-fetch-http/README.zh.md | 2 +- packages/web/web-fetch-http/tests/proxy.spec.ts | 14 ++++++++++++-- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/web/web-fetch-http/README.i18n.yaml b/packages/web/web-fetch-http/README.i18n.yaml index cd38c41c24..9010001d0c 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: 7767aae6d0d5d969 - zh: ba93fa27403d4e6f + en: e62633ede6519943 + zh: 0970dc75b474e702 /deepseek-ai-dsh-web-fetch-http/understand-the-implementation: en: 9842c69ad3636bb3 zh: 3cdc3f816cbdd0cb diff --git a/packages/web/web-fetch-http/README.md b/packages/web/web-fetch-http/README.md index 7e0ab8897c..d8233c9429 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. 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`, 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. ----- diff --git a/packages/web/web-fetch-http/README.zh.md b/packages/web/web-fetch-http/README.zh.md index 40f97cd6f2..ca1be3eb39 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 证书错误。直接调用方可以按错误码路由;面向模型的 `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_PROVIDER_ERROR` 会给出底层系统错误,例如 `getaddrinfo ENOTFOUND host`、`connect ECONNREFUSED addr:port` 或 TLS 证书错误;最多列出四次连接尝试,其余只计数,原因文本最多保留 500 个字符。直接调用方可以按错误码路由;面向模型的 `web_fetch` 工具会在自己的错误包装层内把失败文本呈现给模型。 ----- diff --git a/packages/web/web-fetch-http/tests/proxy.spec.ts b/packages/web/web-fetch-http/tests/proxy.spec.ts index 88c11883ff..3d30630828 100644 --- a/packages/web/web-fetch-http/tests/proxy.spec.ts +++ b/packages/web/web-fetch-http/tests/proxy.spec.ts @@ -63,8 +63,8 @@ afterEach(async () => { * Install the policy of a user who exported one proxy for both schemes; the fixture disposes it * after every case. */ -async function installProxy(): Promise<() => Promise> { - const env = { get: (name: string) => (name === 'HTTP_PROXY' || name === 'HTTPS_PROXY' ? { value: proxyUrl } : undefined) } +async function installProxy(url = proxyUrl): Promise<() => Promise> { + const env = { get: (name: string) => (name === 'HTTP_PROXY' || name === 'HTTPS_PROXY' ? { value: url } : undefined) } return await installProxyFromEnvironment(env, () => undefined) } @@ -108,4 +108,14 @@ describe('fetching through a proxy', () => { .rejects.toThrow(expect.objectContaining({ code: 'WEB_INVALID_URL' })) expect(proxied).toEqual([]) }) + + it('names a proxy transport failure without the proxy credentials', async () => { + proxy.removeAllListeners('request') + proxy.on('request', (request) => { request.socket.end() }) + disposeProxy = await installProxy(proxyUrl.replace('http://', 'http://proxy-user:proxy-secret@')) + + 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' })) + }) }) From bf483abd120a5f1a7b768f5def40a4436475879b Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 6 Nov 2026 19:34:48 +0800 Subject: [PATCH 04/15] test(snapshots): replay a web_fetch transport failure Co-authored-by: Elevator14B <219823454+Elevator14B@users.noreply.github.com> --- .../cordis.snapshot.yml | 31 +++++++++ .../web-fetch-transport-failure/cordis.yml | 18 +++++ .../session.v4.jsonl | 22 ++++++ .../web-fetch-transport-failure/snapshot.yml | 11 +++ .../web-fetch-transport-failure-fixture.mjs | 69 +++++++++++++++++++ 5 files changed, 151 insertions(+) create mode 100644 snapshots/session/web-fetch-transport-failure/cordis.snapshot.yml create mode 100644 snapshots/session/web-fetch-transport-failure/cordis.yml create mode 100644 snapshots/session/web-fetch-transport-failure/session.v4.jsonl create mode 100644 snapshots/session/web-fetch-transport-failure/snapshot.yml create mode 100644 snapshots/session/web-fetch-transport-failure/web-fetch-transport-failure-fixture.mjs diff --git a/snapshots/session/web-fetch-transport-failure/cordis.snapshot.yml b/snapshots/session/web-fetch-transport-failure/cordis.snapshot.yml new file mode 100644 index 0000000000..286257d304 --- /dev/null +++ b/snapshots/session/web-fetch-transport-failure/cordis.snapshot.yml @@ -0,0 +1,31 @@ +# Keyless replay counterpart: deterministic HTTP remains real; only the model +# adapter is replaced by replay. +- id: llm-deepseek + name: '@deepseek-ai/dsh-llm-deepseek-api-key' + disabled: true + +- insert: + - id: llm-replay + name: '@deepseek-ai/dsh-llm-replay' + config: + providers: + - id: deepseek-official + name: DeepSeek + models: + - id: deepseek-v4-flash + - id: deepseek-v4-pro + + - id: web-fetch-transport-failure-fixture + name: './web-fetch-transport-failure-fixture.mjs' + +- id: web + name: '@deepseek-ai/dsh-web' + +- id: web-fetch-http + name: '@deepseek-ai/dsh-web-fetch-http' + disabled: true + +- id: tool-web + name: '@deepseek-ai/dsh-tool-web' + config: + search: false diff --git a/snapshots/session/web-fetch-transport-failure/cordis.yml b/snapshots/session/web-fetch-transport-failure/cordis.yml new file mode 100644 index 0000000000..11568abd92 --- /dev/null +++ b/snapshots/session/web-fetch-transport-failure/cordis.yml @@ -0,0 +1,18 @@ +# Web-fetch composition for the web-fetch-transport-failure snapshot scenario. The base bundle +# supplies the web seam and public HTTP provider; this overlay inserts a +# deterministic failing provider and exposes only fetch. +- insert: + - id: web-fetch-transport-failure-fixture + name: './web-fetch-transport-failure-fixture.mjs' + +- id: web + name: '@deepseek-ai/dsh-web' + +- id: web-fetch-http + name: '@deepseek-ai/dsh-web-fetch-http' + disabled: true + +- id: tool-web + name: '@deepseek-ai/dsh-tool-web' + config: + search: false diff --git a/snapshots/session/web-fetch-transport-failure/session.v4.jsonl b/snapshots/session/web-fetch-transport-failure/session.v4.jsonl new file mode 100644 index 0000000000..47f3191b9d --- /dev/null +++ b/snapshots/session/web-fetch-transport-failure/session.v4.jsonl @@ -0,0 +1,22 @@ +{"type":"session","version":4,"id":"{{session:1}}","createdAt":1785078727712,"cwd":"{{cwd}}","isSeeded":false,"delegationDepth":0} +{"type":"permission/preset","data":{"preset":"workspace-write"}} +{"type":"sandbox/mode","data":{"mode":"workspace-write"}} +{"type":"approval/policy","data":{"policy":"ask"}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"inserted":[{"content":[{"type":"text","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."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"}]}} +{"type":"turn/start","data":{"turn":1}} +{"type":"agent/inbox/spliced","data":{"target":"next-turn","start":0,"removedCount":1,"inserted":[]}} +{"type":"step/start","data":{"turn":1,"step":1}} +{"type":"system/message","data":{"turn":1,"step":1,"message":{"role":"system","content":[{"type":"text","text":"{{system}}"}],"source":{"kind":"system-prompt"},"id":"{{message:2}}"}},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","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."}],"source":{"kind":"user"},"role":"user","id":"{{message:1}}"},"surfaceOp":"append"} +{"type":"user/message","data":{"content":[{"type":"text","text":"\nThe following information describes your current session:\n\nCurrent working directory: \"{{cwd}}\".\n\nCurrent DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable.\n\nApproval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed.\n\nYou are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names.\n"}],"source":{"kind":"runtime-context","form":"snapshot","sections":[{"name":"working-directory:current","text":"Current working directory: \"{{cwd}}\"."},{"name":"sandbox:policy","text":"Current DSH file policy: workspace-write. Any available operation enforced by the DSH file sandbox may modify files under the session workspace: \"{{cwd}}\". Some platform temporary areas may also be writable."},{"name":"approval:policy","text":"Approval prompts are enabled in this session: operations that require approval may ask through the configured answerers; without an available answerer, the request fails closed."},{"name":"subagent:identity","text":"You are the root agent. Your name is \"lead\".\n\nTo message other agents, use send_message({ agent: \"\", message: \"...\" }).\nUse list_agents({}) to find your collaborator agents and their names."}]},"role":"user","id":"{{message:3}}"},"surfaceOp":"append"} +{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-pro"},"tools":"{{tools}}"},"reason":"initial"}} +{"type":"request/context","data":{"provider":"deepseek-official","model":"deepseek-v4-pro"}} +{"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":"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"} +{"type":"step/end","data":{"turn":1,"step":2}} +{"type":"turn/end","data":{"turn":1,"reason":{"kind":"completed"}}} diff --git a/snapshots/session/web-fetch-transport-failure/snapshot.yml b/snapshots/session/web-fetch-transport-failure/snapshot.yml new file mode 100644 index 0000000000..74067c50cd --- /dev/null +++ b/snapshots/session/web-fetch-transport-failure/snapshot.yml @@ -0,0 +1,11 @@ +version: 1 +scenario: web-fetch-transport-failure +profile: headless +composition: web-fetch-transport-failure +recording: authored +permission: workspace-write +header: + class: web-fetch-transport-failure + pin: true + systemPromptSource: web-fetch + toolSchemasSource: web-fetch diff --git a/snapshots/session/web-fetch-transport-failure/web-fetch-transport-failure-fixture.mjs b/snapshots/session/web-fetch-transport-failure/web-fetch-transport-failure-fixture.mjs new file mode 100644 index 0000000000..2823e4b60e --- /dev/null +++ b/snapshots/session/web-fetch-transport-failure/web-fetch-transport-failure-fixture.mjs @@ -0,0 +1,69 @@ +/** + * Deterministic transport failure for the web-fetch-transport-failure snapshot scenario: an + * OS-assigned loopback server closes each connection once the request arrives, behind the real + * HTTP transport. Replay therefore reaches the model-visible failure text without external network + * while retaining the recorded request URL. + */ +import { HttpFetchProvider } from '@deepseek-ai/dsh-web-fetch-http' +import { applyLoopbackServerEffect } from '../loopback-fixture-server.mjs' + +/** Model-visible URL retained by the recorded session. */ +const RECORDED_URL = 'http://public.test:43117/menu.html' + +/** Cordis plugin name. */ +export const name = 'web-fetch-transport-failure-fixture' + +/** Service used by the fixture provider. */ +export const inject = ['web'] + +const LIMITS = { + maxResponseBytes: 5_000_000, + maxBodyChars: 100_000, + timeoutMs: 30_000, + maxRedirects: 5, + userAgent: 'deepseek-harness-snapshot/1.0', +} + +/** + * Register the deterministic provider and start its loopback server. + * @param ctx - Cordis context; the effect disposes the server with the fiber. + */ +export async function apply(ctx) { + const readiness = Promise.withResolvers() + let transportUrl + let startupError + + const provider = new HttpFetchProvider(LIMITS) + const unregister = ctx.web.registerFetchProvider({ + id: provider.id, + available: () => provider.available(), + fetch: async (request, signal) => { + if (request.url !== RECORDED_URL) throw new Error(`unexpected snapshot URL: ${request.url}`) + await readiness.promise + if (startupError !== undefined) throw startupError + const result = await provider.fetch({ url: transportUrl.toString() }, signal) + return { ...result, url: RECORDED_URL } + }, + }) + try { + await applyLoopbackServerEffect(ctx, { + label: 'web-fetch-transport-failure-fixture', + requestListener: (req) => { + req.socket.end() + }, + onListening: (address) => { + transportUrl = new URL(RECORDED_URL) + transportUrl.hostname = '127.0.0.1' + transportUrl.port = String(address.port) + readiness.resolve(undefined) + }, + onCleanup: () => { + unregister() + }, + }) + } catch (cause) { + startupError = cause + readiness.resolve(undefined) + throw cause + } +} From adc9d1bf643ee1628f27b400e0d51b7c6aba978b Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 7 Nov 2026 16:45:28 +0800 Subject: [PATCH 05/15] fix(web): fall back to execCommand when the clipboard write is refused A refused navigator.clipboard.writeText (blocked permission, embedding policy) returned false without trying the execCommand fallback, so copy buttons did nothing. Fall through to the fallback and return focus to the control afterwards. Fixes #8123 --- .../tests/chat-branch-tails.client.spec.tsx | 21 ++++++++++ .../client/ui-primitives/src/clipboard.ts | 17 ++++---- .../tests/terminal-block.client.spec.tsx | 39 ++++++++++++++++++- .../ui-workspace/tests/apply.client.spec.ts | 2 + 4 files changed, 71 insertions(+), 8 deletions(-) diff --git a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx index 88c42d6dc2..dea8285608 100644 --- a/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx +++ b/packages/client/ui-chat/tests/chat-branch-tails.client.spec.tsx @@ -227,11 +227,32 @@ describe('MessageItem arms', () => { expect(exec).toHaveBeenCalledWith('copy') }) + it('user copy succeeds through execCommand when the host refuses the async write', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + const exec = vi.fn().mockReturnValue(true) + Object.defineProperty(document, 'execCommand', { configurable: true, value: exec }) + render( + , + ) + fireEvent.click(screen.getByRole('button', { name: '复制' })) + expect(await screen.findByRole('button', { name: '复制成功' })).toBeTruthy() + expect(exec).toHaveBeenCalledWith('copy') + }) + it('user copy never claims success when the host rejects the write', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => false) }) render( { try { await navigator.clipboard.writeText(text) return true - } catch { - // Denied permissions / iframe policy — do not claim success. - return false + } catch (_error) { + // A denied permission or embedding policy blocks only the async API; try the fallback below. } } - // jsdom and older hosts: best-effort execCommand path when present. // execCommand('copy') is the only clipboard fallback where the async API - // is missing; deprecated but deliberately retained. + // is missing or refused; deprecated but deliberately retained. /* oxlint-disable typescript/no-deprecated */ const exec = typeof document.execCommand === 'function' ? document.execCommand.bind(document) : undefined if (exec === undefined) return false + // Selecting the textarea moves focus; return it so a keyboard user stays on the copy control. + const focused = document.activeElement const el = document.createElement('textarea') el.value = text el.setAttribute('readonly', '') @@ -42,6 +44,7 @@ export async function writeClipboard(text: string): Promise { return false } finally { el.remove() + if (focused instanceof HTMLElement) focused.focus() } /* oxlint-enable typescript/no-deprecated */ } diff --git a/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx b/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx index b801dd6e91..5a6dbd9567 100644 --- a/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx +++ b/packages/client/ui-primitives/tests/terminal-block.client.spec.tsx @@ -448,14 +448,32 @@ describe('writeClipboard', () => { expect(writeText).toHaveBeenCalledWith('payload') }) - it('reports false when the Clipboard API rejects', async () => { + it('reports false when the Clipboard API rejects and no fallback exists', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: undefined }) await expect(writeClipboard('payload')).resolves.toBe(false) }) + it('falls back to execCommand when the Clipboard API rejects', async () => { + Object.defineProperty(navigator, 'clipboard', { + configurable: true, + value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, + }) + let selected: string | undefined + const exec = vi.fn(() => { + selected = document.querySelector('textarea[readonly]')?.value + return true + }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: exec }) + await expect(writeClipboard('payload')).resolves.toBe(true) + expect(exec).toHaveBeenCalledWith('copy') + expect(selected).toBe('payload') + expect(document.querySelector('textarea')).toBeNull() + }) + it('selects a detached textarea for the execCommand fallback and removes it after', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) let selected: string | undefined @@ -470,6 +488,25 @@ describe('writeClipboard', () => { expect(document.querySelector('textarea')).toBeNull() }) + it('returns focus to the copy control after the execCommand fallback', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => true) }) + const button = document.createElement('button') + document.body.appendChild(button) + button.focus() + await expect(writeClipboard('payload')).resolves.toBe(true) + expect(document.activeElement).toBe(button) + button.remove() + }) + + it('copies through the fallback when nothing had focus', async () => { + Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) + Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => true) }) + const activeElement = vi.spyOn(document, 'activeElement', 'get').mockReturnValue(null) + await expect(writeClipboard('payload')).resolves.toBe(true) + activeElement.mockRestore() + }) + it('reports execCommand\'s own refusal verbatim', async () => { Object.defineProperty(navigator, 'clipboard', { configurable: true, value: undefined }) Object.defineProperty(document, 'execCommand', { configurable: true, value: vi.fn(() => false) }) diff --git a/packages/client/ui-workspace/tests/apply.client.spec.ts b/packages/client/ui-workspace/tests/apply.client.spec.ts index d6c18cd763..3007cc8b56 100644 --- a/packages/client/ui-workspace/tests/apply.client.spec.ts +++ b/packages/client/ui-workspace/tests/apply.client.spec.ts @@ -371,6 +371,8 @@ describe('ui-workspace apply', () => { if (!accepted) throw new Error('clipboard denied') }) vi.stubGlobal('navigator', { clipboard: { writeText } }) + // This spec has no DOM; give the fallback a document without execCommand so a refused write stays refused. + vi.stubGlobal('document', {}) onTestFinished(() => { vi.unstubAllGlobals() }) await action.copySessionId(sid('cold-session')) expect(writeText).toHaveBeenCalledExactlyOnceWith('cold-session') From 81ee68dfbaa59ab18437d24b2622048edc8a2b96 Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 7 Nov 2026 17:21:21 +0800 Subject: [PATCH 06/15] fix(web): keep the clipboard fallback total and document its limits --- packages/client/ui-primitives/src/clipboard.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/packages/client/ui-primitives/src/clipboard.ts b/packages/client/ui-primitives/src/clipboard.ts index ae90982fcf..f8331f12e2 100644 --- a/packages/client/ui-primitives/src/clipboard.ts +++ b/packages/client/ui-primitives/src/clipboard.ts @@ -1,12 +1,13 @@ // Host clipboard write shared by Web UI copy controls. Success feedback stays -// with each control; this helper only reports whether the host accepted a write. +// with each control; this helper reports whether the host accepted a write and +// leaves focus where it found it. /** * Write text to the host clipboard, preferring the async Clipboard API and * falling back to `execCommand('copy')` when that API is missing (jsdom, - * insecure contexts) or refuses the write (blocked clipboard permission, - * embedding policy). Call it from a user gesture: the fallback relies on the - * gesture's transient activation. + * insecure contexts) or refuses the write (for example, a denied clipboard + * permission). The fallback replaces the page selection and succeeds only while + * the triggering user gesture's transient activation is still valid. * @param text - the exact text to place on the clipboard. * @returns true only when the host accepted the write. */ @@ -19,7 +20,7 @@ export async function writeClipboard(text: string): Promise { await navigator.clipboard.writeText(text) return true } catch (_error) { - // A denied permission or embedding policy blocks only the async API; try the fallback below. + // A denied permission can block the async API while execCommand still works; try it below. } } // execCommand('copy') is the only clipboard fallback where the async API @@ -36,15 +37,15 @@ export async function writeClipboard(text: string): Promise { el.setAttribute('readonly', '') el.style.position = 'fixed' el.style.left = '-9999px' - document.body.appendChild(el) - el.select() try { + document.body.appendChild(el) + el.select() return exec('copy') } catch { return false } finally { el.remove() - if (focused instanceof HTMLElement) focused.focus() + if (focused instanceof HTMLElement) focused.focus({ preventScroll: true }) } /* oxlint-enable typescript/no-deprecated */ } From c20a2bee3a06ed919bf2f168cd50d7b741a9f63f Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 7 Nov 2026 23:12:28 +0800 Subject: [PATCH 07/15] 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% From 33633756265a12a0be5ac9f8990cc88d92ed365e Mon Sep 17 00:00:00 2001 From: Turtle Date: Sat, 7 Nov 2026 23:25:25 +0800 Subject: [PATCH 08/15] test(web): type-check the web_fetch failure row spec in the host program Co-authored-by: Elevator14B <219823454+Elevator14B@users.noreply.github.com> --- apps/web/tsconfig.json | 1 + tsconfig.host.json | 1 + 2 files changed, 2 insertions(+) diff --git a/apps/web/tsconfig.json b/apps/web/tsconfig.json index a70870d5ec..5aef2ae5cd 100644 --- a/apps/web/tsconfig.json +++ b/apps/web/tsconfig.json @@ -242,6 +242,7 @@ "tests/auto-review-approval.e2e.ts", "tests/auto-review-denial.e2e.ts", "tests/bash-abort-row.e2e.ts", + "tests/web-fetch-failure-row.e2e.ts", "tests/interrupted-turn.e2e.ts", "tests/skill-tool-row.e2e.ts", "tests/tool-details.e2e.ts", diff --git a/tsconfig.host.json b/tsconfig.host.json index 21ad8213c5..bdb79d2f9c 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -226,6 +226,7 @@ "apps/web/tests/jobs-menu-layering.e2e.ts", "apps/web/tests/live-job-stream.e2e.ts", "apps/web/tests/bash-abort-row.e2e.ts", + "apps/web/tests/web-fetch-failure-row.e2e.ts", "apps/web/tests/skill-tool-row.e2e.ts", "apps/web/tests/tool-details.e2e.ts", "apps/web/tests/turn-tail-actions.e2e.ts", From 3d445a7ce6cd66fcb84e5f9f77b494fcbff88b8c Mon Sep 17 00:00:00 2001 From: Turtle Date: Tue, 10 Nov 2026 17:13:14 +0800 Subject: [PATCH 09/15] fix(desktop): close the window with Cmd+W from the Platform page Refs #8244 --- .../client/ui-settings-account/README.i18n.yaml | 4 ++-- packages/client/ui-settings-account/README.md | 2 +- packages/client/ui-settings-account/README.zh.md | 2 +- .../src/client/PlatformOverlay.tsx | 3 ++- .../tests/account.client.spec.tsx | 1 + packages/client/ui-sidebar-right/README.i18n.yaml | 4 ++-- packages/client/ui-sidebar-right/README.md | 2 +- packages/client/ui-sidebar-right/README.zh.md | 2 +- .../ui-sidebar-right/src/client/shortcuts.ts | 4 +++- .../ui-sidebar-right/tests/focus.client.spec.ts | 15 +++++++++++++++ 10 files changed, 29 insertions(+), 10 deletions(-) diff --git a/packages/client/ui-settings-account/README.i18n.yaml b/packages/client/ui-settings-account/README.i18n.yaml index 9e0fff1997..b7dd7357d5 100644 --- a/packages/client/ui-settings-account/README.i18n.yaml +++ b/packages/client/ui-settings-account/README.i18n.yaml @@ -15,8 +15,8 @@ en: c26f81e8adf0128b zh: e11ab371f51f66bc /deepseek-ai-dsh-client-ui-settings-account/use-this-package: - en: ece8b18503977bdd - zh: 2d47640fb8367a3d + en: 9e61a6adc39fddbc + zh: fbcb4852ca4eded1 /deepseek-ai-dsh-client-ui-settings-account/use-this-package/desktop-onboarding: en: 7ae4e68f9491b068 zh: f7478269bf8d28b3 diff --git a/packages/client/ui-settings-account/README.md b/packages/client/ui-settings-account/README.md index e03583cfd3..0585faf254 100644 --- a/packages/client/ui-settings-account/README.md +++ b/packages/client/ui-settings-account/README.md @@ -38,7 +38,7 @@ Account operations carry this UI's client identity to the Host: build version, a Balances use Platform Web currency formatting: two decimal places and digit grouping, positive amounts truncated to cents, positive sub-cent amounts shown as <0.01, and negative amounts rounded with a minimum displayed magnitude of 0.01. Raw Host balance strings remain unchanged. -Desktop usage, top-up, and onboarding recharge actions open one isolated native Platform view below a 48px return bar. The Desktop host owns a single such view, and opening a page destroys the previous one, so the plugin registers one shared host entry in `shell.overlay` and the Account settings page, the account quota notice, and the Desktop onboarding recharge page all request a page through its `PlatformPages` request channel instead of mounting their own container. Each request retires the previous owner before the newer page shows, and its identity-safe release clears only that request, so a stale owner cannot close a page it no longer owns. On Windows Electron the return bar and the native view start below the Desktop caption strip, so the Application and Edit menu text cannot cover the Back to DeepSeek Harness label. Back destroys the view, restores focus before any deferred Modal takes it, and preserves the Account settings page. Leaving a top-up page waits for any read already running and then reads again, because a top-up may have changed what the account holds. The Account settings page and the account quota notice re-read profile and balance and publish an account refresh for extensions; the onboarding recharge return re-reads profile and balance only. Superseding a page, releasing a request, plugin unload, and leaving usage all read nothing. Loading failures retain the return action and show a centered localized error with Retry. Retry reloads the same destination; renderer commands never receive the account token. +Desktop usage, top-up, and onboarding recharge actions open one isolated native Platform view below a 48px return bar. The Desktop host owns a single such view, and opening a page destroys the previous one, so the plugin registers one shared host entry in `shell.overlay` and the Account settings page, the account quota notice, and the Desktop onboarding recharge page all request a page through its `PlatformPages` request channel instead of mounting their own container. Each request retires the previous owner before the newer page shows, and its identity-safe release clears only that request, so a stale owner cannot close a page it no longer owns. On Windows Electron the return bar and the native view start below the Desktop caption strip, so the Application and Edit menu text cannot cover the Back to DeepSeek Harness label. Back destroys the view, restores focus before any deferred Modal takes it, and preserves the Account settings page. The page layer declares shortcut modal `platform` for the [right sidebar close command](../ui-sidebar-right/README.md). Leaving a top-up page waits for any read already running and then reads again, because a top-up may have changed what the account holds. The Account settings page and the account quota notice re-read profile and balance and publish an account refresh for extensions; the onboarding recharge return re-reads profile and balance only. Superseding a page, releasing a request, plugin unload, and leaving usage all read nothing. Loading failures retain the return action and show a centered localized error with Retry. Retry reloads the same destination; renderer commands never receive the account token. Chat offers each live quota failure from a bound Session to the frame-wide `shell.quota-notice` chain from its host in `shell.overlay`, so the notice outlives the Chat panel that reported it. The account entry claims `ACCOUNT_QUOTA`: while an account credential is stored and the shared host entry exists, the Modal offers Cancel and Top up. While a page requested through the shared request channel is showing, the native view covers this document, so the entry paints neither the Modal nor the Toast. A quota failure that arrives while a Settings-opened page is already showing is not retained: it stays subject to newest-notice replacement, and the Modal appears after the viewer returns while that notice is still current. That Modal reports the failure of the original request, not the account's current balance: the top-up re-read is a separate read, and returning neither proves a successful payment nor dismisses the notice on its own. The notice's own Top up is the retained case: it calls `keepOpen()` and requests the `top-up` page through the shared request channel, keeping that notice and its page mounted through later quota failures. With the shared host entry the entry waits for the first account snapshot instead of rendering a Toast that its own timer could discard; a snapshot that reports no stored credential, or a failed account stream with no snapshot, then renders the same neutral warning Toast itself, and without that host entry the entry renders that Toast immediately, instead of relying on the chat host fallback. The entry owns the hold and its page request and releases both when it unmounts, so a later quota failure publishes again without replaying the dropped ones; dismissal or sign-out clears the hold and the page request. Close, Cancel, a sign-out, or leaving the notice's own embedded page takes the notice down without retrying the request. diff --git a/packages/client/ui-settings-account/README.zh.md b/packages/client/ui-settings-account/README.zh.md index c6d7a291b3..4ea576d157 100644 --- a/packages/client/ui-settings-account/README.zh.md +++ b/packages/client/ui-settings-account/README.zh.md @@ -38,7 +38,7 @@ Desktop 与普通 Web 客户端都挂载侧边栏账号菜单、账号设置、 余额沿用 Platform Web 的金额格式:两位小数和千分位分组,正金额截断至分,小于一分的正金额显示为 <0.01,负金额按舍入规则处理且显示绝对值至少为 0.01。Host 返回的原始余额字符串保持不变。 -Desktop 的用量、充值与引导充值操作在 48px 返回栏下方打开同一个隔离的原生 Platform 视图。Desktop 宿主只有一个这样的视图,打开新页面会销毁上一个,因此插件在 `shell.overlay` 注册一个共享宿主条目,Account 设置页、账号欠费提示与 Desktop 引导充值页都通过其 `PlatformPages` 请求通道申请页面,而不再各自挂载容器。新请求会在新页面显示前退掉上一个持有者,其身份安全的释放只清除本次请求,因此过期的持有者无法关闭它已不再持有的页面。在 Windows Electron 中,返回栏与原生视图都从 Desktop 顶栏下方开始,Application 和 Edit 菜单文字不会盖住“返回 DeepSeek Harness”。返回操作销毁视图并保留 Account 设置页,且先恢复焦点,再由任何被延后的 Modal 接管。从充值页返回时会等待任何已在进行的读取结束后再读取,因为充值可能改变账号持有的内容。Account 设置页与账号欠费提示会重读资料、余额,并向扩展发布账号刷新事件;引导充值返回则只重读资料与余额。替换页面、释放请求、插件卸载与从用量页返回均不读取。加载失败时保留返回操作,居中显示本地化错误提示和“重试”按钮。重试重新加载同一目标页面;渲染进程命令不接收账号 token。 +Desktop 的用量、充值与引导充值操作在 48px 返回栏下方打开同一个隔离的原生 Platform 视图。Desktop 宿主只有一个这样的视图,打开新页面会销毁上一个,因此插件在 `shell.overlay` 注册一个共享宿主条目,Account 设置页、账号欠费提示与 Desktop 引导充值页都通过其 `PlatformPages` 请求通道申请页面,而不再各自挂载容器。新请求会在新页面显示前退掉上一个持有者,其身份安全的释放只清除本次请求,因此过期的持有者无法关闭它已不再持有的页面。在 Windows Electron 中,返回栏与原生视图都从 Desktop 顶栏下方开始,Application 和 Edit 菜单文字不会盖住“返回 DeepSeek Harness”。返回操作销毁视图并保留 Account 设置页,且先恢复焦点,再由任何被延后的 Modal 接管。页面层为[右栏关闭命令](../ui-sidebar-right/README.zh.md)声明快捷键弹窗 `platform`。从充值页返回时会等待任何已在进行的读取结束后再读取,因为充值可能改变账号持有的内容。Account 设置页与账号欠费提示会重读资料、余额,并向扩展发布账号刷新事件;引导充值返回则只重读资料与余额。替换页面、释放请求、插件卸载与从用量页返回均不读取。加载失败时保留返回操作,居中显示本地化错误提示和“重试”按钮。重试重新加载同一目标页面;渲染进程命令不接收账号 token。 Chat 通过 `shell.overlay` 中的宿主把已绑定 Session 的实时欠费交给全局 `shell.quota-notice` 链,提示的生命周期因此长于上报它的 Chat 面板。账号条目认领 `ACCOUNT_QUOTA`:已存储账号凭证且存在共享宿主条目时,Modal 提供取消和去充值。只要通过该共享请求通道请求的页面正在显示,原生视图就会盖住本页,因此该条目既不绘制 Modal 也不绘制 Toast。在 Account 设置页已打开页面的情况下新到达的欠费不会被保持:它仍受最新提示替换规则约束,返回后若该提示仍是最新一条就显示 Modal。该 Modal 报告的是原始请求的失败,而不是账号当前余额:返回时的重读是一次独立读取,返回本身既不证明支付成功,也不会自动撤下该提示。提示自身的去充值属于被保持的情形:它调用 `keepOpen()` 并通过共享请求通道申请 `top-up` 页面,使该提示与其页面在后续欠费期间保持挂载。存在共享宿主条目时,该条目会等待首个账号快照,而不是渲染一个可能被自身计时器丢弃的 Toast;快照报告未存储凭证,或账号流失败且无快照时,才由该条目自行渲染同一段中立警告 Toast,缺少该宿主条目时则立即渲染该 Toast,而不依赖 Chat 宿主回退。该条目持有保持与页面请求,并在自身卸载时释放二者,因此后续欠费会重新发布而不重放已丢弃的提示;关闭与退出登录也会清除保持和页面请求。关闭、取消、退出登录或离开该提示自己的内嵌页面都会撤下提示,且不会重试请求。 diff --git a/packages/client/ui-settings-account/src/client/PlatformOverlay.tsx b/packages/client/ui-settings-account/src/client/PlatformOverlay.tsx index 6576a7266a..0da3fa466a 100644 --- a/packages/client/ui-settings-account/src/client/PlatformOverlay.tsx +++ b/packages/client/ui-settings-account/src/client/PlatformOverlay.tsx @@ -66,7 +66,8 @@ export function PlatformOverlay({ bridge, page, backLabel, loadingLabel, failure }) } }, [bridge, page, attempt]) - return createPortal(
+ return createPortal(