From df387e627dd0d9bd8ac697bab2a37d69a18d5fb6 Mon Sep 17 00:00:00 2001 From: ideal Date: Sun, 17 May 2026 17:01:05 +0800 Subject: [PATCH 1/4] fix: pin fetch to bundled undici for Node.js 26 (undici 8.x) compat Node.js 26 bundles undici 8.x, which differs from the project's undici 6.x. Using Node's built-in fetch mixed with ProxyAgent/Client from the bundled undici causes handler-interface mismatches (e.g. 'invalid onError method'). --- packages/cli/src/utils/apiPreconnect.ts | 11 ++++++++--- .../core/openaiContentGenerator/provider/default.ts | 6 ++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/packages/cli/src/utils/apiPreconnect.ts b/packages/cli/src/utils/apiPreconnect.ts index 7661ba69a9c4..7be28e417f46 100644 --- a/packages/cli/src/utils/apiPreconnect.ts +++ b/packages/cli/src/utils/apiPreconnect.ts @@ -21,6 +21,7 @@ import { getOrCreateSharedDispatcher, redactProxyCredentials, } from '@qwen-code/qwen-code-core'; +import { fetch as undiciFetch } from 'undici'; import { getAllProviderBaseUrls } from '../auth/allProviders.js'; @@ -194,15 +195,19 @@ export function preconnectApi( // so the warmed TCP+TLS connection is reused by subsequent API calls. const dispatcher = getOrCreateSharedDispatcher(proxy); - // Fire HEAD request to warm connection (fire-and-forget) - fetch(targetUrl, { + // Fire HEAD request to warm connection (fire-and-forget). + // Use undici's own fetch (not Node's built-in fetch) so the dispatcher + // and fetch come from the same undici version — Node's bundled undici + // may differ in major version from the bundled one (e.g. v8 vs v6), + // causing handler-interface mismatches like `invalid onError method`. + undiciFetch(targetUrl, { method: 'HEAD', signal: AbortSignal.timeout(5_000), headers: { 'User-Agent': 'QwenCode-Preconnect/1.0', }, dispatcher, - } as RequestInit) + }) .then(() => { debugLogger.debug('Preconnect completed'); }) diff --git a/packages/core/src/core/openaiContentGenerator/provider/default.ts b/packages/core/src/core/openaiContentGenerator/provider/default.ts index 9ddd8d6b01fc..f8678d19db1e 100644 --- a/packages/core/src/core/openaiContentGenerator/provider/default.ts +++ b/packages/core/src/core/openaiContentGenerator/provider/default.ts @@ -1,4 +1,5 @@ import OpenAI from 'openai'; +import { fetch as undiciFetch } from 'undici'; import type { GenerateContentConfig } from '@google/genai'; import type { Config } from '../../../config/config.js'; import type { ContentGeneratorConfig } from '../../contentGenerator.js'; @@ -94,6 +95,11 @@ export class DefaultOpenAICompatibleProvider timeout, maxRetries, defaultHeaders, + // Pin fetch to undici's own implementation so it shares a version with + // the dispatcher built in `runtimeOptions`. Mixing Node's built-in + // fetch (newer undici) with a ProxyAgent from the bundled undici + // (e.g. v6) trips handler-interface checks like `invalid onError method`. + fetch: undiciFetch as unknown as typeof fetch, ...(runtimeOptions || {}), }); } From bd6c84a247daba99a0f26177c95cfbc9100b97e4 Mon Sep 17 00:00:00 2001 From: ideal Date: Mon, 18 May 2026 10:35:33 +0800 Subject: [PATCH 2/4] fix(core): export undici fetch alongside proxy dispatcher to avoid version mismatch for review of #4238 When a custom dispatcher (ProxyAgent) is passed, pin fetch to the bundled undici's implementation so both share the same undici version. Without this, Node's built-in fetch (e.g. undici v8) rejects a ProxyAgent from the bundled undici (e.g. v6) with "invalid onError method". --- packages/cli/src/utils/apiPreconnect.test.ts | 17 ++++++--- .../src/utils/runtimeFetchOptions.test.ts | 36 +++++++++++++++++++ .../core/src/utils/runtimeFetchOptions.ts | 17 +++++++-- 3 files changed, 64 insertions(+), 6 deletions(-) diff --git a/packages/cli/src/utils/apiPreconnect.test.ts b/packages/cli/src/utils/apiPreconnect.test.ts index 5b0400d2a470..a1f98faa41fb 100644 --- a/packages/cli/src/utils/apiPreconnect.test.ts +++ b/packages/cli/src/utils/apiPreconnect.test.ts @@ -17,8 +17,19 @@ const { mockGetOrCreateSharedDispatcher, mockDebugLogger } = vi.hoisted(() => { }; }); -// Mock fetch -const mockFetch = vi.fn().mockResolvedValue(undefined); +// Mock fetch. apiPreconnect.ts now uses `import { fetch } from 'undici'` +// rather than the global fetch, so we have to intercept the module export — +// vi.stubGlobal('fetch', …) would not catch the named import. +const { mockFetch } = vi.hoisted(() => ({ + mockFetch: vi.fn().mockResolvedValue(undefined), +})); +vi.mock('undici', async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + fetch: mockFetch, + }; +}); vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => { const actual = await importOriginal(); @@ -50,11 +61,9 @@ describe('apiPreconnect', () => { delete process.env['QWEN_CODE_DISABLE_PRECONNECT']; delete process.env['NODE_EXTRA_CA_CERTS']; delete process.env['SANDBOX']; - vi.stubGlobal('fetch', mockFetch); }); afterEach(() => { - vi.unstubAllGlobals(); vi.restoreAllMocks(); }); diff --git a/packages/core/src/utils/runtimeFetchOptions.test.ts b/packages/core/src/utils/runtimeFetchOptions.test.ts index b03809850c5d..187f966c6ba5 100644 --- a/packages/core/src/utils/runtimeFetchOptions.test.ts +++ b/packages/core/src/utils/runtimeFetchOptions.test.ts @@ -22,6 +22,10 @@ vi.mock('./debugLogger.js', () => ({ mockWarn, })); +const { mockUndiciFetch } = vi.hoisted(() => ({ + mockUndiciFetch: vi.fn(), +})); + vi.mock('undici', () => { class MockAgent { options: UndiciOptions; @@ -47,6 +51,7 @@ vi.mock('undici', () => { return { Agent: MockAgent, ProxyAgent: MockProxyAgent, + fetch: mockUndiciFetch, }; }); @@ -114,6 +119,37 @@ describe('buildRuntimeFetchOptions (node runtime)', () => { }); }); + it('pins fetch to undici when proxy is set so dispatcher and fetch share a version', () => { + // Regression for `invalid onError method`: Node's built-in fetch (newer + // undici) cannot accept a ProxyAgent built from a different undici major. + // The function must hand back the bundled undici's fetch alongside the + // dispatcher. + const openaiResult = buildRuntimeFetchOptions( + 'openai', + 'http://proxy.local', + ); + expect((openaiResult as { fetch?: unknown }).fetch).toBe(mockUndiciFetch); + + const anthropicResult = buildRuntimeFetchOptions( + 'anthropic', + 'http://proxy.local', + ); + expect((anthropicResult as { fetch?: unknown }).fetch).toBe( + mockUndiciFetch, + ); + }); + + it('does not inject a fetch override when no proxy is set', () => { + // No-proxy path must stay on the runtime's built-in fetch — see the + // comment in runtimeFetchOptions.ts:586 about avoiding version-mismatch + // issues on code paths that don't need a custom dispatcher. + const openaiResult = buildRuntimeFetchOptions('openai'); + expect(openaiResult).toBeUndefined(); + + const anthropicResult = buildRuntimeFetchOptions('anthropic'); + expect((anthropicResult as { fetch?: unknown }).fetch).toBeUndefined(); + }); + it('returns undefined for OpenAI when dispatcher creation fails', () => { const result = buildRuntimeFetchOptions('openai', 'http://invalid-proxy'); // Should fallback to undefined (no dispatcher) on error diff --git a/packages/core/src/utils/runtimeFetchOptions.ts b/packages/core/src/utils/runtimeFetchOptions.ts index 011850e28e6b..012bc1e80361 100644 --- a/packages/core/src/utils/runtimeFetchOptions.ts +++ b/packages/core/src/utils/runtimeFetchOptions.ts @@ -4,7 +4,7 @@ * SPDX-License-Identifier: Apache-2.0 */ -import { ProxyAgent, type Dispatcher } from 'undici'; +import { ProxyAgent, fetch as undiciFetch, type Dispatcher } from 'undici'; import { createDebugLogger } from './debugLogger.js'; @@ -37,6 +37,13 @@ export type OpenAIRuntimeFetchOptions = dispatcher?: Dispatcher; timeout?: false; }; + // Optional fetch override. When a custom dispatcher is being passed, + // we pin this to the bundled undici's fetch so the dispatcher and + // fetch share a single undici version — otherwise Node's built-in + // fetch (newer undici) rejects a ProxyAgent from the bundled undici + // (e.g. v6) with `invalid onError method`. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + fetch?: any; } | undefined; @@ -596,7 +603,13 @@ function buildFetchOptionsWithDispatcher( // 300s bodyTimeout. This is sufficient for all current model streaming responses. try { const dispatcher = getOrCreateSharedDispatcher(proxyUrl); - return { fetchOptions: { dispatcher } }; + // Pin fetch to undici's own implementation so the dispatcher and fetch + // come from the same undici version. Node's bundled undici may differ in + // major version from the project's bundled one (e.g. v8 vs v6), which + // breaks dispatcher handler-interface checks (`invalid onError method`). + // The no-proxy branch above intentionally skips this so the runtime's + // built-in fetch continues to be used when no dispatcher is involved. + return { fetchOptions: { dispatcher }, fetch: undiciFetch }; } catch (error) { // Log dispatcher creation failure - requests will fallback to direct connection // bypassing the configured proxy. This is important for environments requiring From 632e0b03cf26686c29a9af73a12b4d13a25fa66a Mon Sep 17 00:00:00 2001 From: ideal Date: Mon, 18 May 2026 11:07:05 +0800 Subject: [PATCH 3/4] fix: move pinning fetch alongside with dispatcher in runtimeOptions, change back default.ts --- .../src/core/openaiContentGenerator/provider/default.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/packages/core/src/core/openaiContentGenerator/provider/default.ts b/packages/core/src/core/openaiContentGenerator/provider/default.ts index f8678d19db1e..9ddd8d6b01fc 100644 --- a/packages/core/src/core/openaiContentGenerator/provider/default.ts +++ b/packages/core/src/core/openaiContentGenerator/provider/default.ts @@ -1,5 +1,4 @@ import OpenAI from 'openai'; -import { fetch as undiciFetch } from 'undici'; import type { GenerateContentConfig } from '@google/genai'; import type { Config } from '../../../config/config.js'; import type { ContentGeneratorConfig } from '../../contentGenerator.js'; @@ -95,11 +94,6 @@ export class DefaultOpenAICompatibleProvider timeout, maxRetries, defaultHeaders, - // Pin fetch to undici's own implementation so it shares a version with - // the dispatcher built in `runtimeOptions`. Mixing Node's built-in - // fetch (newer undici) with a ProxyAgent from the bundled undici - // (e.g. v6) trips handler-interface checks like `invalid onError method`. - fetch: undiciFetch as unknown as typeof fetch, ...(runtimeOptions || {}), }); } From fa5f896cca0f284b1775020c17de3d3d6b222a02 Mon Sep 17 00:00:00 2001 From: ideal Date: Mon, 18 May 2026 17:20:22 +0800 Subject: [PATCH 4/4] docs(core): update code comment reference in runtimeFetchOptions test --- packages/core/src/utils/runtimeFetchOptions.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/core/src/utils/runtimeFetchOptions.test.ts b/packages/core/src/utils/runtimeFetchOptions.test.ts index 187f966c6ba5..a752f8ec9da2 100644 --- a/packages/core/src/utils/runtimeFetchOptions.test.ts +++ b/packages/core/src/utils/runtimeFetchOptions.test.ts @@ -141,8 +141,9 @@ describe('buildRuntimeFetchOptions (node runtime)', () => { it('does not inject a fetch override when no proxy is set', () => { // No-proxy path must stay on the runtime's built-in fetch — see the - // comment in runtimeFetchOptions.ts:586 about avoiding version-mismatch - // issues on code paths that don't need a custom dispatcher. + // comment in buildFetchOptionsWithDispatcher() in runtimeFetchOptions.ts + // about avoiding version-mismatch issues on code paths + // that don't need a custom dispatcher. const openaiResult = buildRuntimeFetchOptions('openai'); expect(openaiResult).toBeUndefined();