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/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/utils/runtimeFetchOptions.test.ts b/packages/core/src/utils/runtimeFetchOptions.test.ts index b03809850c5d..a752f8ec9da2 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,38 @@ 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 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(); + + 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