Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions packages/cli/src/utils/apiPreconnect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof import('undici')>();
return {
...actual,
fetch: mockFetch,
};
});
vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
const actual =
await importOriginal<typeof import('@qwen-code/qwen-code-core')>();
Expand Down Expand Up @@ -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();
});

Expand Down
11 changes: 8 additions & 3 deletions packages/cli/src/utils/apiPreconnect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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');
})
Expand Down
37 changes: 37 additions & 0 deletions packages/core/src/utils/runtimeFetchOptions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ vi.mock('./debugLogger.js', () => ({
mockWarn,
}));

const { mockUndiciFetch } = vi.hoisted(() => ({
mockUndiciFetch: vi.fn(),
}));

vi.mock('undici', () => {
class MockAgent {
options: UndiciOptions;
Expand All @@ -47,6 +51,7 @@ vi.mock('undici', () => {
return {
Agent: MockAgent,
ProxyAgent: MockProxyAgent,
fetch: mockUndiciFetch,
};
});

Expand Down Expand Up @@ -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();

Comment thread
ideal marked this conversation as resolved.
Resolved
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
Expand Down
17 changes: 15 additions & 2 deletions packages/core/src/utils/runtimeFetchOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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;

Expand Down Expand Up @@ -596,7 +603,13 @@ function buildFetchOptionsWithDispatcher(
// 300s bodyTimeout. This is sufficient for all current model streaming responses.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Anthropic SDK 静默丢弃 fetchOptions.dispatcher。

buildFetchOptionsWithDispatcher 为两个 SDK 都返回 { fetchOptions: { dispatcher }, fetch: undiciFetch },但 Anthropic SDK(@anthropic-ai/sdk)构造函数不支持 fetchOptions——它只存储 fetch。dispatcher 被 Anthropic 路径静默丢弃。

这不是此 PR 引入的问题(PR 之前 dispatcher 就已经被返回了),但 fetch: undiciFetch 的显式添加使这种不对称性更加明显——未来维护者可能会看到这段代码,并认为 Anthropic 的代理路径是正常的,而实际上并非如此。

Suggested change
// 300s bodyTimeout. This is sufficient for all current model streaming responses.
// Note: Anthropic SDK does not support constructor-level fetchOptions,
// so the dispatcher is only effective for OpenAI SDK calls.
return { fetchOptions: { dispatcher }, fetch: undiciFetch };

— DeepSeek/deepseek-v4-pro via Qwen Code /review

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 };

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Missing success-path debug log. buildFetchOptionsWithDispatcher logs failures extensively (debugLogger.warn + console.error), but when dispatcher creation succeeds and fetch is pinned to undiciFetch, no log is emitted. When debugging proxy issues in production, there's no way to confirm the fetch override was injected without reading source code.

Consider adding a debug log before the return:

Suggested change
return { fetchOptions: { dispatcher }, fetch: undiciFetch };
debugLogger.debug(
`Proxy dispatcher created for ${extractHostnameFromProxyUrl(proxyUrl)}, fetch pinned to bundled undici`,
);
return { fetchOptions: { dispatcher }, fetch: undiciFetch };

— qwen-latest-series-invite-beta-v34 via Qwen Code /review

} catch (error) {
// Log dispatcher creation failure - requests will fallback to direct connection
// bypassing the configured proxy. This is important for environments requiring
Expand Down
Loading