Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 出站代理覆盖所有 Node 侧出网(修 Claude 授权 403) (#687)

Dashced0e0547115
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index e83c8b0122..f29bd55711 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -241,6 +241,7 @@ import { getDrizzleDir } from './localDb/migrate';
import { resolveSqliteVecExtPath } from './localDb/sqliteVecLoader';
import { startEmbeddingHost, stopEmbeddingHost, isEmbeddingHostStarted } from './embedding-host';
import { readClaudeApiKey } from './maker-host/auth-adapters';
+import { outboundFetch } from './maker-host/outbound-fetch';
import { registerDevEmbeddingIpc } from './ipc/dev/embedding';
import { onQuit, installQuitHandler } from './lifecycle';
import { initStartupDiagnostics } from './startup-diagnostics';
@@ -760,6 +761,9 @@ function attemptStartEmbeddingHost(): void {
getApiKey: () => readClaudeApiKey(),
// 函数形态:model-access 下发切换 endpoint 后,常驻的 embedding host 无需重启。
gatewayBaseUrl: () => effectiveXdGatewayBaseUrl(),
+ // /v1/embeddings 也要吃系统代理:裸全局 fetch 在「系统代理」模式下裸直连出网
+ // (见 maker-host/outbound-fetch.ts)。
+ fetchImpl: outboundFetch,
log: createSchedulerLogger('embeddingHost'),
});
// chat-history-embedder consumer 注册 + setEnabled(true) 触发 cutoff 落盘。
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 935fc6f76a..9fad8c81be 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -162,6 +162,7 @@ import {
storeGhostSecret,
} from '../secrets/providerSecretStore.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
import {
CINDY_CAPABILITY_KEYS,
readGhostCindyOverrides,
@@ -1881,8 +1882,10 @@ function getGhostOauthAccountManager(): GhostOauthAccountManager {
store: (ghostId, storageKey, value) => storeGhostSecret(ghostId, storageKey, value),
remove: (ghostId, storageKey) => removeGhostSecret(ghostId, storageKey),
},
- // 与 networkSlot 同选型:Node 侧全局 fetch(undici),不吃系统代理。
- fetchImpl: (url, init) => fetch(url, init as RequestInit),
+ // 与 networkSlot 同选型:Node 侧 undici fetch(Chromium 栈的 manual redirect 给
+ // opaqueredirect,守不住逐跳白名单),但经 outboundFetch 拿到系统代理 ——
+ // 意识 OAuth 的 token 端点(Google / Atlassian 等)多在境外。
+ fetchImpl: (url, init) => outboundFetch(url, init as RequestInit),
openExternal: (url) => shell.openExternal(url),
// tokenBroker 声明的意识(仅第一方,门控在装入闸与连接闸)经独立
// oauth-broker 服务换/刷 token:serverApiFetch 自带登录 JWT 注入与
@@ -2139,13 +2142,13 @@ export function getGhostNetworkSlot(): GhostNetworkSlot {
readSecret: (ghostId, secretKey) => readGhostSecret(ghostId, secretKey),
// source:'login-email' 凭证的值来源:现读登录态(切号/登出下一单即生效)。
getLoginEmail: () => getAuthState().user?.email ?? null,
- // 用 Node 侧全局 fetch(undici)而非 Electron net.fetch:redirect:'manual'
- // 在 undici 下如实返回 3xx + Location,本槽据此逐跳校验白名单;Chromium
- // 栈的 manual 会给 opaqueredirect(读不到 Location),无法逐跳守门。
- // 代价是不吃系统代理设置,意识自带服务场景可接受,有诉求再评估。
+ // 用 Node 侧 undici fetch 而非 Electron net.fetch:redirect:'manual' 在 undici
+ // 下如实返回 3xx + Location,本槽据此逐跳校验白名单;Chromium 栈的 manual 会给
+ // opaqueredirect(读不到 Location),无法逐跳守门。系统代理由 outboundFetch 补上
+ // (意识声明的域名大量在境外,裸 undici 直连在「系统代理」模式下出不去)。
// init 收窄:body 的 Uint8Array 在 lib.dom 的 BodyInit 泛型下对不齐,
// 运行时 undici 原生支持,按 RequestInit 交给 fetch。
- fetchImpl: (url, init) => fetch(url, init as RequestInit),
+ fetchImpl: (url, init) => outboundFetch(url, init as RequestInit),
// 媒体模式(as:'media'):字节直落总仓 + ghost-gallery 记账(出生=该
// 意识,与 cindy 槽产物同一记账口径),走统一入库助手 ingestMedia
// (规则 25)。mime 白名单同一来源(blobStore),槽内归一化后再判。
diff --git a/apps/desktop/src/main/device-link/index.ts b/apps/desktop/src/main/device-link/index.ts
index daf5e0853e..90afa0cd17 100644
--- a/apps/desktop/src/main/device-link/index.ts
+++ b/apps/desktop/src/main/device-link/index.ts
@@ -33,6 +33,7 @@ import * as authManager from '../authManager';
import { createLogger } from '../logger';
import { onQuit } from '../lifecycle';
import { tryGetDbClient } from '../localDb/client/current';
+import { createOutboundHttpAgent } from '../maker-host/outbound-fetch';
import {
DeviceLinkOwnershipArbiter,
createDbClientOwnershipStore,
@@ -243,7 +244,10 @@ export function initDeviceLinkService(): void {
// 硬编码 false 会把 server presence 覆盖成空闲、且轮询 dedupe 压掉补正(New-F)。见 busyReporter。
busy: helloBusy(),
}),
- createWebSocket: (url, headers) => new WebSocket(url, { headers }),
+ // agent:`ws` 不吃系统代理,relay 在代理网络下会连不上;直连时为 undefined,
+ // 行为与不传一致(见 maker-host/outbound-fetch)。
+ createWebSocket: async (url, headers) =>
+ new WebSocket(url, { headers, agent: await createOutboundHttpAgent(url) }),
logger: {
debug: (...args) => log.debug(...args),
info: (...args) => log.info(...args),
diff --git a/apps/desktop/src/main/git-context/ipc.ts b/apps/desktop/src/main/git-context/ipc.ts
index 2d198b3d10..309fd71a5c 100644
--- a/apps/desktop/src/main/git-context/ipc.ts
+++ b/apps/desktop/src/main/git-context/ipc.ts
@@ -23,6 +23,7 @@ import { GithubClient } from '@cindy/github-client';
import { createLogger } from '../logger.js';
import { getCurrentDbClientUserId } from '../localDb/client/current';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { requireString, throwIpcError } from '../utils/ipcValidate';
import { createGhCliTokenSource } from './ghCliTokenSource.js';
import { GitContextService } from './GitContextService.js';
@@ -95,7 +96,8 @@ async function fetchUnresolvedCount(client: GithubClient, q: PrStatusQuery): Pro
}
async function fetchPrRemote(token: string, q: PrStatusQuery): Promise<PrRemoteState> {
- const client = new GithubClient({ token, owner: q.owner, repo: q.repo });
+ // fetchImpl:api.github.com 是境外端点,走吃系统代理的通道(见 maker-host/outbound-fetch)。
+ const client = new GithubClient({ token, owner: q.owner, repo: q.repo, fetchImpl: outboundFetch });
// 核心状态走 REST(所有 token 类型通用);未解决数走 GraphQL 增强信号,
// 失败(老 fine-grained PAT 不支持 GraphQL 等)降级 null,不拖垮整条状态。
const [pr, unresolved] = await Promise.all([
diff --git a/apps/desktop/src/main/heartbeatService.ts b/apps/desktop/src/main/heartbeatService.ts
index 55f4ac8dc2..abd503020f 100644
--- a/apps/desktop/src/main/heartbeatService.ts
+++ b/apps/desktop/src/main/heartbeatService.ts
@@ -24,6 +24,7 @@ import * as authManager from './authManager';
import { createLogger } from './logger';
import { onQuit } from './lifecycle';
import { getClientEndpoint } from './clientEndpointsService';
+import { outboundFetch } from './maker-host/outbound-fetch';
const log = createLogger('heartbeat');
@@ -50,6 +51,8 @@ function startCloudHeartbeat(uid: string): void {
handle = createHeartbeatClient({
endpoint,
intervalMs: DEFAULT_INTERVAL_MS,
+ // 走吃系统代理的通道:代理网络下裸 undici 直连会让心跳恒失败(静默 warn)。
+ fetchImpl: outboundFetch,
host: {
// 每次 tick 读活的 auth 状态:离开 cloud 后旧 handle 立刻拿不到 uid
// (client 对 null 跳过本次上报),不依赖 stop 的时序竞争。
diff --git a/apps/desktop/src/main/hook-control/transport.ts b/apps/desktop/src/main/hook-control/transport.ts
index 83c6c84f5f..01baa7301a 100644
--- a/apps/desktop/src/main/hook-control/transport.ts
+++ b/apps/desktop/src/main/hook-control/transport.ts
@@ -28,6 +28,8 @@ import {
type WelcomePayload,
} from '@cindy/slack-hook-protocol';
+import { createOutboundHttpAgent } from '../maker-host/outbound-fetch.js';
+
/** transport 对外状态(manager 映射为 HookConnectionStatus)。 */
export type HookTransportStatus = 'connecting' | 'connected' | 'standby' | 'error' | 'stopped';
@@ -92,6 +94,12 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {
let lastFrameAt = 0;
let lastError: string | null = null;
let unexpectedHttpStatus: number | null = null;
+ /**
+ * 建连世代。connect() 每次调用递增,建连路径上的每个 await 之后都要比对 —— 取 token
+ * 与解析出站代理各是一次异步往返,期间 401 重连 / 退避重试 / dispose 都可能再触发一次
+ * connect(),不比对就会并发建出多条 socket,旧的那条没人回收(review 2026-07-27)。
+ */
+ let connectEpoch = 0;
function setStatus(status: HookTransportStatus): void {
if (stopped && status !== 'stopped') return;
@@ -150,12 +158,13 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {
function connect(): void {
if (stopped) return;
+ const epoch = ++connectEpoch;
unexpectedHttpStatus = null;
setStatus('connecting');
void getAuthToken()
.catch(() => null)
.then((token) => {
- if (stopped) return;
+ if (stopped || epoch !== connectEpoch) return;
if (!token) {
// 未登录:不发起无凭证连接(必 401),记状态按退避重试;
// 登录事件会经 manager.sync 重建 transport 即时恢复
@@ -164,7 +173,7 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {
scheduleRetry();
return;
}
- openSocket(token);
+ void openSocket(token, epoch);
});
}
@@ -191,12 +200,17 @@ export function createHookTransport(opts: HookTransportOpts): HookTransport {
});
}
- function openSocket(token: string): void {
+ async function openSocket(token: string, epoch: number): Promise<void> {
let socket: WebSocket;
try {
+ // `ws` 不吃系统代理;直连时 agent 为 undefined,行为与不传一致。
+ const agent = await createOutboundHttpAgent(url);
+ // 代理解析是一次异步往返,期间可能已 stop 或又发起了一次 connect —— 都不再建连。
+ if (stopped || epoch !== connectEpoch) return;
socket = new WebSocket(url, {
headers: { Authorization: `Bearer ${token}` },
handshakeTimeout: 15_000,
+ agent,
});
} catch (err) {
// URL 非法等同步失败: 记错误并按退避重试(配置修好后自然恢复)
diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts
new file mode 100644
index 0000000000..f110c7d4c3
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts
@@ -0,0 +1,580 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { Agent as UndiciAgent, ProxyAgent } from 'undici';
+
+import { Socks5HttpsAgent, TunnelingHttpsAgent } from '@cindy/anthropic-compat-proxy';
+
+const resolverState = vi.hoisted(() => ({
+ resolve: vi.fn<(url: string) => Promise<string | null>>(async () => null),
+}));
+
+const undiciState = vi.hoisted(() => ({
+ fetch: vi.fn(async () => ({ ok: true, status: 200, headers: new Headers(), body: null })),
+}));
+
+/** 造一个 3xx 响应桩(带可取消的 body,验证我们会归还连接)。 */
+function redirectResponse(status: number, location: string): {
+ status: number;
+ headers: Headers;
+ body: { cancel: () => Promise<void> };
+} {
+ return {
+ status,
+ headers: new Headers({ location }),
+ body: { cancel: async () => undefined },
+ };
+}
+
+const loggerState = vi.hoisted(() => ({
+ warn: vi.fn(),
+ debug: vi.fn(),
+}));
+
+vi.mock('../logger-adapter.js', () => ({
+ createMakerLogger: () => ({
+ trace: vi.fn(),
+ debug: loggerState.debug,
+ info: vi.fn(),
+ warn: loggerState.warn,
+ error: vi.fn(),
+ child: vi.fn(),
+ isDebugEnabled: () => false,
+ }),
+}));
+
+vi.mock('../outbound-proxy-resolver.js', () => ({
+ resolveDesktopOutboundProxy: (url: string) => resolverState.resolve(url),
+}));
+
+// 只替换 fetch:ProxyAgent / Agent 用真实类,断言才能验证选型。
+vi.mock('undici', async (importOriginal) => {
+ const actual = await importOriginal<Record<string, unknown>>();
+ return { ...actual, fetch: (...args: unknown[]) => undiciState.fetch(...(args as [])) };
+});
+
+import {
+ createOutboundHttpAgent,
+ outboundFetch,
+ outboundUndiciFetch,
+ resetOutboundFetchStateForTest,
+ resolveConnectOptions,
+ resolveOutboundDispatcher,
+} from '../outbound-fetch.js';
+
+/** 取包装 dispatcher 对某个目标 URL 实际选中的底层 dispatcher(重定向选路即走这条)。 */
+function pick(dispatcher: unknown, url: string): unknown {
+ return (dispatcher as { pickForUrlForTest(u: string): unknown }).pickForUrlForTest(url);
+}
+
+beforeEach(() => {
+ resolverState.resolve.mockReset();
+ resolverState.resolve.mockResolvedValue(null);
+ undiciState.fetch.mockReset();
+ undiciState.fetch.mockResolvedValue({ ok: true, status: 200, headers: new Headers(), body: null });
+ loggerState.warn.mockClear();
+ resetOutboundFetchStateForTest();
+});
+
+afterEach(() => {
+ resetOutboundFetchStateForTest();
+});
+
+describe('resolveOutboundDispatcher', () => {
+ it('returns the caller fallback when the resolver says direct', async () => {
+ const fallback = new UndiciAgent();
+ await expect(resolveOutboundDispatcher('https://platform.claude.com/v1/oauth/token', { fallback }))
+ .resolves.toBe(fallback);
+ await expect(resolveOutboundDispatcher('https://platform.claude.com/v1/oauth/token'))
+ .resolves.toBeUndefined();
+ await fallback.close();
+ });
+
+ it('never consults the resolver for loopback upstreams', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ await expect(resolveOutboundDispatcher('http://localhost:51730/v1/messages')).resolves.toBeUndefined();
+ await expect(resolveOutboundDispatcher('http://127.0.0.1:51730/v1/messages')).resolves.toBeUndefined();
+ expect(resolverState.resolve).not.toHaveBeenCalled();
+ });
+
+ it('resolves per origin + path (query stripped) and builds a ProxyAgent for http proxies', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const dispatcher = await resolveOutboundDispatcher('https://platform.claude.com/v1/oauth/token?x=1');
+ expect(pick(dispatcher, 'https://platform.claude.com/v1/oauth/token')).toBeInstanceOf(ProxyAgent);
+ // PAC 的 FindProxyForURL 可以按路径判定 → 必须把 path 带上;query 可能含令牌,剥掉。
+ expect(resolverState.resolve).toHaveBeenCalledWith('https://platform.claude.com/v1/oauth/token');
+ });
+
+ it('keeps per-path PAC decisions apart on the same origin', async () => {
+ // 「/internal 直连、其余走代理」这类 PAC 配置必须逐路径生效。
+ resolverState.resolve.mockImplementation(async (target: string) =>
+ new URL(target).pathname === '/internal' ? null : 'http://127.0.0.1:7890',
+ );
+ const proxied = await resolveOutboundDispatcher('https://api.example.com/public');
+ expect(proxied).toBeDefined();
+ await expect(resolveOutboundDispatcher('https://api.example.com/internal')).resolves.toBeUndefined();
+ // 重定向选路也查同一份「origin + path」快照,不会把 /internal 拖进代理。
+ expect(pick(proxied, 'https://api.example.com/internal')).not.toBeInstanceOf(ProxyAgent);
+ });
+
+ it('lets caller connect tuning win over the built-in default', async () => {
+ // 合并规则(纯函数):默认值只补缺,调用方给的值优先,自定义 connector 原样保留。
+ expect(resolveConnectOptions(undefined)).toEqual({ autoSelectFamilyAttemptTimeout: 2500 });
+ expect(
+ resolveConnectOptions({ connect: { autoSelectFamilyAttemptTimeout: 9999 } }),
+ ).toEqual({ autoSelectFamilyAttemptTimeout: 9999 });
+ expect(resolveConnectOptions({ connect: { maxCachedSessions: 0 } })).toEqual({
+ autoSelectFamilyAttemptTimeout: 2500,
+ maxCachedSessions: 0,
+ });
+ const connector = (): void => {};
+ expect(resolveConnectOptions({ connect: connector as never })).toBe(connector);
+
+ // 端到端:带自定义 connect 调优时仍建得出 ProxyAgent。
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const dispatcher = await resolveOutboundDispatcher('https://chatgpt.com/backend-api/codex', {
+ agentOptions: { connect: { autoSelectFamilyAttemptTimeout: 9999 } },
+ });
+ expect(pick(dispatcher, 'https://chatgpt.com/backend-api/codex')).toBeInstanceOf(ProxyAgent);
+ });
+
+ it('builds a plain Agent with a socks5 connector for socks5 proxies', async () => {
+ resolverState.resolve.mockResolvedValue('socks5://127.0.0.1:7891');
+ const dispatcher = await resolveOutboundDispatcher('https://api.anthropic.com/api/oauth/profile');
+ const base = pick(dispatcher, 'https://api.anthropic.com/api/oauth/profile');
+ expect(base).toBeInstanceOf(UndiciAgent);
+ expect(base).not.toBeInstanceOf(ProxyAgent);
+ });
+
+ it('reuses one dispatcher per proxy + tuning, and separates different tuning', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const a = await resolveOutboundDispatcher('https://chatgpt.com/backend-api/codex');
+ const b = await resolveOutboundDispatcher('https://chatgpt.com/backend-api/codex');
+ expect(b).toBe(a);
+ const tuned = await resolveOutboundDispatcher('https://chatgpt.com/backend-api/codex', {
+ agentOptions: { keepAliveTimeout: 60_000 },
+ });
+ expect(tuned).not.toBe(a);
+ expect(pick(tuned, 'https://chatgpt.com/backend-api/codex')).toBeInstanceOf(ProxyAgent);
+ // 不同调优 = 不同底层池,不能共享连接。
+ expect(pick(tuned, 'https://chatgpt.com/backend-api/codex')).not.toBe(
+ pick(a, 'https://chatgpt.com/backend-api/codex'),
+ );
+ });
+
+ it('separates pools per custom connect function (functions vanish in JSON.stringify)', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const connectA = ((_o: unknown, cb: (e: Error | null) => void) => cb(null)) as never;
+ const connectB = ((_o: unknown, cb: (e: Error | null) => void) => cb(null)) as never;
+ const url = 'https://example.com/x';
+ const a = await resolveOutboundDispatcher(url, { agentOptions: { connect: connectA } });
+ const b = await resolveOutboundDispatcher(url, { agentOptions: { connect: connectB } });
+ const aAgain = await resolveOutboundDispatcher(url, { agentOptions: { connect: connectA } });
+ // 不同 connector → 不同底层池;同一 connector → 复用同一个。
+ expect(pick(b, url)).not.toBe(pick(a, url));
+ expect(pick(aAgain, url)).toBe(pick(a, url));
+ });
+
+ it('separates dispatchers per upstream protocol', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const https = await resolveOutboundDispatcher('https://example.com/a');
+ const http = await resolveOutboundDispatcher('http://example.com/a');
+ expect(pick(http, 'http://example.com/a')).not.toBe(pick(https, 'https://example.com/a'));
+ });
+
+ it('re-routes per hop so redirects cannot drag loopback or bypassed hosts through the proxy', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const dispatcher = await resolveOutboundDispatcher('https://platform.claude.com/v1/oauth/token');
+ const proxied = pick(dispatcher, 'https://platform.claude.com/v1/oauth/token');
+ expect(proxied).toBeInstanceOf(ProxyAgent);
+
+ // loopback 同步可判:重定向到本机一律直连,「loopback 恒直连」在跳转后依然成立。
+ const loopback = pick(dispatcher, 'http://127.0.0.1:51730/v1/messages');
+ expect(loopback).not.toBe(proxied);
+ expect(loopback).not.toBeInstanceOf(ProxyAgent);
+ // 同一个直连池复用,不会每跳新建。
+ expect(pick(dispatcher, 'http://localhost:51730/v1/messages')).toBe(loopback);
+
+ // 快照里记着「该 origin 直连」(NO_PROXY 命中等)→ 也走直连池。
+ resolverState.resolve.mockResolvedValue(null);
+ await resolveOutboundDispatcher('https://intranet.example.com/x');
+ expect(pick(dispatcher, 'https://intranet.example.com/x')).toBe(loopback);
+
+ // 从没解析过的 origin:同步拿不到结论,本跳沿用首跳出口(不阻塞热路径)。
+ expect(pick(dispatcher, 'https://unknown.example.org/x')).toBe(proxied);
+ });
+
+ it('never hands out an evicted base dispatcher (wrapper re-derives from the pool)', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const wrapper = await resolveOutboundDispatcher('https://a0.example.com/x');
+ const before = pick(wrapper, 'https://a0.example.com/x');
+
+ // 把底层池顶过上限,逼出 a0 那一项(wrapper 仍在 routingPool 里被复用)。
+ for (let i = 1; i <= 8; i += 1) {
+ await resolveOutboundDispatcher('https://a0.example.com/x', {
+ agentOptions: { keepAliveTimeout: 2000 + i },
+ });
+ }
+ const again = await resolveOutboundDispatcher('https://a0.example.com/x');
+ expect(again).toBe(wrapper); // 同一个 wrapper 实例
+ const after = pick(wrapper, 'https://a0.example.com/x');
+ // 但它派发到的底层已经是重建后的新实例,不是那个被安排关闭的旧实例。
+ expect(after).not.toBe(before);
+ expect(after).toBeInstanceOf(ProxyAgent);
+ });
+
+ it('backfills the snapshot under the path-bearing key so the next hop stops missing', async () => {
+ // wrapper 兜底路径(voice 客户端把它直接交给 undici):未命中时后台补解析,
+ // 必须按「origin + path」写快照,否则查的键永远 miss、永远沿用首跳代理。
+ resolverState.resolve.mockImplementation(async (target: string) =>
+ new URL(target).pathname === '/direct' ? null : 'http://127.0.0.1:7890',
+ );
+ const wrapper = await resolveOutboundDispatcher('https://api.example.com/first');
+ const proxied = pick(wrapper, 'https://api.example.com/first');
+
+ // 第一次访问 /direct:快照还没有 → 本跳沿用首跳出口,并触发后台解析。
+ expect(pick(wrapper, 'https://api.example.com/direct')).toBe(proxied);
+ expect(resolverState.resolve).toHaveBeenCalledWith('https://api.example.com/direct');
+ await vi.waitFor(() => {
+ // 后台解析落盘后,同一路径不再 miss —— 走直连池。
+ expect(pick(wrapper, 'https://api.example.com/direct')).not.toBe(proxied);
+ });
+ expect(pick(wrapper, 'https://api.example.com/direct')).not.toBeInstanceOf(ProxyAgent);
+ });
+
+ it('does not close an evicted dispatcher immediately (it may already be in a caller hand)', async () => {
+ vi.useFakeTimers();
+ try {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const first = await resolveOutboundDispatcher('https://a0.example.com/x');
+ const evictable = pick(first, 'https://a0.example.com/x') as { close: () => Promise<void> };
+ const closeSpy = vi.spyOn(evictable, 'close').mockResolvedValue(undefined);
+
+ // 用不同的池调优把底层池顶过上限(8),逼出最旧的那一项。
+ for (let i = 1; i <= 8; i += 1) {
+ await resolveOutboundDispatcher('https://a0.example.com/x', {
+ agentOptions: { keepAliveTimeout: 1000 + i },
+ });
+ }
+ expect(closeSpy).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(60_000);
+ expect(closeSpy).toHaveBeenCalledTimes(1);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('fails open to the fallback when the resolver throws', async () => {
+ resolverState.resolve.mockRejectedValue(new Error('boom'));
+ await expect(resolveOutboundDispatcher('https://auth.x.ai/oauth2/token')).resolves.toBeUndefined();
+ expect(loggerState.warn).toHaveBeenCalled();
+ });
+
+ it('falls back to direct for unsupported proxy schemes and warns once per origin', async () => {
+ resolverState.resolve.mockResolvedValue('https://secure.proxy:443');
+ await expect(resolveOutboundDispatcher('https://auth.x.ai/oauth2/token')).resolves.toBeUndefined();
+ await expect(resolveOutboundDispatcher('https://auth.x.ai/.well-known/openid-configuration'))
+ .resolves.toBeUndefined();
+ expect(loggerState.warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps proxy credentials out of the logs', async () => {
+ resolverState.resolve.mockResolvedValue('https://user:[email protected]:443');
+ await resolveOutboundDispatcher('https://auth.x.ai/oauth2/token');
+ const logged = JSON.stringify([...loggerState.warn.mock.calls, ...loggerState.debug.mock.calls]);
+ expect(logged).not.toContain('sekret');
+ });
+
+ it('tolerates unparseable urls by treating them as direct', async () => {
+ await expect(resolveOutboundDispatcher('/v1/oauth/token')).resolves.toBeUndefined();
+ expect(resolverState.resolve).not.toHaveBeenCalled();
+ });
+});
+
+describe('outboundFetch', () => {
+ it('passes the proxy dispatcher through to undici fetch', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ await outboundFetch('https://platform.claude.com/v1/oauth/token', { method: 'POST' });
+ expect(undiciState.fetch).toHaveBeenCalledTimes(1);
+ const [, init] = undiciState.fetch.mock.calls[0] as unknown as [unknown, Record<string, unknown>];
+ expect(init.method).toBe('POST');
+ expect(pick(init.dispatcher, 'https://platform.claude.com/v1/oauth/token')).toBeInstanceOf(ProxyAgent);
+ });
+
+ it('delegates to globalThis.fetch verbatim when the upstream is direct', async () => {
+ // 直连必须与改造前逐字节一致 —— 包括「宿主/单测替换了全局 fetch」这件事继续生效。
+ const globalFetch = vi.fn(async () => new Response('ok'));
+ const original = globalThis.fetch;
+ globalThis.fetch = globalFetch as unknown as typeof globalThis.fetch;
+ try {
+ await outboundFetch('https://platform.claude.com/v1/oauth/token', { method: 'POST' });
+ expect(undiciState.fetch).not.toHaveBeenCalled();
+ expect(globalFetch).toHaveBeenCalledTimes(1);
+ const [, init] = globalFetch.mock.calls[0] as unknown as [unknown, Record<string, unknown>];
+ expect(init).toEqual({ method: 'POST' });
+ } finally {
+ globalThis.fetch = original;
+ }
+ });
+
+ it('accepts URL inputs', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ await outboundFetch(new URL('https://api.anthropic.com/v1/models'));
+ expect(resolverState.resolve).toHaveBeenCalledWith('https://api.anthropic.com/v1/models');
+ });
+
+ it('normalizes global FormData bodies for the npm-undici proxy path', async () => {
+ // 全局 FormData 来自 Node 内置 undici;npm undici 的 instanceof 认不出来,不归一化
+ // 就会被序列化成 [object FormData](review 2026-07-27 P1)。
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const form = new FormData();
+ form.set('model', 'elevenlabs/scribe_v2');
+ form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'audio/mpeg' }), 'a.mp3');
+ await outboundFetch('https://gateway.example.com/v1/audio/transcriptions', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer k' },
+ body: form,
+ });
+ const [url, init] = undiciState.fetch.mock.calls[0] as unknown as [
+ string,
+ { method: string; body: unknown; headers: Array<[string, string]> },
+ ];
+ expect(url).toBe('https://gateway.example.com/v1/audio/transcriptions');
+ expect(init.method).toBe('POST');
+ expect(Buffer.isBuffer(init.body)).toBe(true);
+ expect((init.body as Buffer).includes('elevenlabs/scribe_v2')).toBe(true);
+ const headers = new Map(init.headers.map(([k, v]) => [k.toLowerCase(), v]));
+ // boundary 由全局 Request 生成,必须随字节一起传下去,否则服务端解不出 multipart。
+ expect(headers.get('content-type')).toMatch(/^multipart\/form-data; boundary=/);
+ expect(headers.get('authorization')).toBe('Bearer k');
+ });
+
+ it('follows redirects itself, re-resolving the proxy for every hop', async () => {
+ // 首跳走代理;第二跳的目标 host 在快照里是「直连」→ 不能再被塞进代理隧道。
+ // 用 URL.origin 精确比较,不做前缀匹配(前缀匹配会把 oauth.example.com.evil.test
+ // 也算命中,CodeQL 的 incomplete-url-substring-sanitization 正是这个)。
+ resolverState.resolve.mockImplementation(async (target: string) =>
+ new URL(target).origin === 'https://oauth.example.com' ? 'http://127.0.0.1:7890' : null,
+ );
+ undiciState.fetch
+ .mockResolvedValueOnce(redirectResponse(302, 'https://cdn.example.net/final') as never)
+ .mockResolvedValueOnce({ ok: true, status: 200, headers: new Headers(), body: null } as never);
+
+ await outboundFetch('https://oauth.example.com/token', { method: 'POST', body: '{}' });
+
+ expect(undiciState.fetch).toHaveBeenCalledTimes(2);
+ const [firstUrl, firstInit] = undiciState.fetch.mock.calls[0] as unknown as [
+ string,
+ { redirect: string; dispatcher?: unknown },
+ ];
+ const [secondUrl, secondInit] = undiciState.fetch.mock.calls[1] as unknown as [
+ string,
+ { method: string; dispatcher?: unknown },
+ ];
+ expect(firstUrl).toBe('https://oauth.example.com/token');
+ // 自己跟随 → 每跳都用 manual 拿 Location,不把选路交给 undici 内部。
+ expect(firstInit.redirect).toBe('manual');
+ expect(firstInit.dispatcher).toBeDefined();
+ expect(secondUrl).toBe('https://cdn.example.net/final');
+ // 第二跳解析为直连 → 不带 dispatcher(走 undici 自己的全局池)。
+ expect(secondInit.dispatcher).toBeUndefined();
+ expect(resolverState.resolve).toHaveBeenCalledWith('https://cdn.example.net/final');
+ });
+
+ it('turns 303 into GET, drops the body, and never replays credentials cross-origin', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ undiciState.fetch
+ .mockResolvedValueOnce(redirectResponse(303, 'https://other.example.org/done') as never)
+ .mockResolvedValueOnce({ ok: true, status: 200, headers: new Headers(), body: null } as never);
+
+ await outboundFetch('https://api.example.com/submit', {
+ method: 'POST',
+ headers: { Authorization: 'Bearer secret', 'Content-Type': 'application/json' },
+ body: '{"a":1}',
+ });
+
+ const [, second] = undiciState.fetch.mock.calls[1] as unknown as [
+ string,
+ { method: string; body?: unknown; headers: Array<[string, string]> },
+ ];
+ expect(second.method).toBe('GET');
+ expect(second.body).toBeUndefined();
+ const headers = new Map(second.headers.map(([k, v]) => [k.toLowerCase(), v]));
+ expect(headers.has('authorization')).toBe(false);
+ expect(headers.has('content-type')).toBe(false);
+ });
+
+ it('only rewrites POST on 301/302 and never rewrites HEAD on 303', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ // 301 + PUT:fetch 规范只把 POST 转 GET,PUT 必须带着方法和 body 继续。
+ undiciState.fetch
+ .mockResolvedValueOnce(redirectResponse(301, 'https://api.example.com/moved') as never)
+ .mockResolvedValueOnce({ ok: true, status: 200, headers: new Headers(), body: null } as never);
+ await outboundFetch('https://api.example.com/old', { method: 'PUT', body: 'payload' });
+ const [, put] = undiciState.fetch.mock.calls[1] as unknown as [
+ string,
+ { method: string; body?: Buffer },
+ ];
+ expect(put.method).toBe('PUT');
+ expect(put.body?.toString()).toBe('payload');
+
+ // 303 + HEAD:探测请求不该变成 GET。
+ undiciState.fetch.mockReset();
+ undiciState.fetch
+ .mockResolvedValueOnce(redirectResponse(303, 'https://api.example.com/probe2') as never)
+ .mockResolvedValueOnce({ ok: true, status: 200, headers: new Headers(), body: null } as never);
+ await outboundFetch('https://api.example.com/probe', { method: 'HEAD' });
+ const [, head] = undiciState.fetch.mock.calls[1] as unknown as [string, { method: string }];
+ expect(head.method).toBe('HEAD');
+ });
+
+ it('does not follow non-redirect 3xx statuses that happen to carry Location', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ // 304 / 300 在直连路径(globalThis.fetch)是原样返回的;开代理不该把它们吞掉。
+ for (const status of [300, 304]) {
+ undiciState.fetch.mockReset();
+ undiciState.fetch.mockResolvedValue(
+ redirectResponse(status, 'https://elsewhere.example.com/x') as never,
+ );
+ const res = (await outboundFetch('https://api.example.com/thing')) as unknown as {
+ status: number;
+ };
+ expect(undiciState.fetch).toHaveBeenCalledTimes(1);
+ expect(res.status).toBe(status);
+ }
+ });
+
+ it('replays method and body on 307 and stops after too many hops', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ undiciState.fetch.mockImplementation(
+ async () => redirectResponse(307, 'https://api.example.com/loop') as never,
+ );
+ await expect(
+ outboundFetch('https://api.example.com/loop', { method: 'PUT', body: 'payload' }),
+ ).rejects.toThrow(/too many redirects/);
+ const [, second] = undiciState.fetch.mock.calls[1] as unknown as [
+ string,
+ { method: string; body?: Buffer },
+ ];
+ expect(second.method).toBe('PUT');
+ expect(second.body?.toString()).toBe('payload');
+ });
+
+ it('rejects with the abort reason instead of hanging on proxy resolution', async () => {
+ const controller = new AbortController();
+ resolverState.resolve.mockImplementation(() => new Promise(() => {}));
+ const inflight = outboundFetch('https://platform.claude.com/v1/oauth/token', {
+ signal: controller.signal,
+ });
+ controller.abort(new Error('caller gave up'));
+ await expect(inflight).rejects.toThrow('caller gave up');
+ expect(undiciState.fetch).not.toHaveBeenCalled();
+ });
+
+ it('falls back to direct when proxy resolution itself times out', async () => {
+ vi.useFakeTimers();
+ try {
+ resolverState.resolve.mockImplementation(() => new Promise(() => {}));
+ const globalFetch = vi.fn(async () => new Response('ok'));
+ const original = globalThis.fetch;
+ globalThis.fetch = globalFetch as unknown as typeof globalThis.fetch;
+ try {
+ const inflight = outboundFetch('https://platform.claude.com/v1/oauth/token');
+ await vi.advanceTimersByTimeAsync(2000);
+ await inflight;
+ expect(globalFetch).toHaveBeenCalledTimes(1);
+ expect(undiciState.fetch).not.toHaveBeenCalled();
+ } finally {
+ globalThis.fetch = original;
+ }
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it('keeps json string bodies and abort signals on the proxy path', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const controller = new AbortController();
+ await outboundFetch('https://platform.claude.com/v1/oauth/token', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ grant_type: 'authorization_code' }),
+ signal: controller.signal,
+ });
+ const [, init] = undiciState.fetch.mock.calls[0] as unknown as [
+ string,
+ { body: Buffer; signal?: AbortSignal; redirect?: string },
+ ];
+ expect(init.body.toString()).toBe('{"grant_type":"authorization_code"}');
+ expect(init.signal).toBeInstanceOf(AbortSignal);
+ // 调用方要的是默认 follow,由我们逐跳跟随实现 → 每跳对 undici 用 manual。
+ expect(init.redirect).toBe('manual');
+ });
+
+ it('hands manual/error redirect modes straight to undici (plugin network slot守门靠它)', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ undiciState.fetch.mockResolvedValue(
+ redirectResponse(302, 'https://elsewhere.example.com/x') as never,
+ );
+ await outboundFetch('https://api.example.com/x', { redirect: 'manual' });
+ // 显式 manual:只发一次,3xx 原样回给调用方(它要自己逐跳校验白名单)。
+ expect(undiciState.fetch).toHaveBeenCalledTimes(1);
+ const [, init] = undiciState.fetch.mock.calls[0] as unknown as [string, { redirect: string }];
+ expect(init.redirect).toBe('manual');
+ });
+});
+
+describe('outboundUndiciFetch', () => {
+ it('honors the caller abort signal while resolving the proxy', async () => {
+ const controller = new AbortController();
+ resolverState.resolve.mockImplementation(() => new Promise(() => {}));
+ const inflight = outboundUndiciFetch('https://chatgpt.com/backend-api/codex', {
+ signal: controller.signal,
+ });
+ controller.abort(new Error('stopped mid-refine'));
+ await expect(inflight).rejects.toThrow('stopped mid-refine');
+ expect(undiciState.fetch).not.toHaveBeenCalled();
+ });
+
+ it('keeps using undici on both paths (callers consume undici Response)', async () => {
+ await outboundUndiciFetch('https://api.openai.com/v1/models');
+ expect(undiciState.fetch).toHaveBeenCalledTimes(1);
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ await outboundUndiciFetch('https://api.openai.com/v1/models');
+ const [, init] = undiciState.fetch.mock.calls[1] as unknown as [unknown, Record<string, unknown>];
+ expect(pick(init.dispatcher, 'https://api.openai.com/v1/models')).toBeInstanceOf(ProxyAgent);
+ });
+});
+
+describe('createOutboundHttpAgent', () => {
+ it('returns undefined when the upstream is direct', async () => {
+ await expect(createOutboundHttpAgent('wss://api.elevenlabs.io/v1/x')).resolves.toBeUndefined();
+ });
+
+ it('tunnels wss upstreams through http proxies', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ const agent = await createOutboundHttpAgent('wss://api.elevenlabs.io/v1/x');
+ expect(agent).toBeInstanceOf(TunnelingHttpsAgent);
+ expect(resolverState.resolve).toHaveBeenCalledWith('https://api.elevenlabs.io/v1/x');
+ agent?.destroy();
+ });
+
+ it('uses the socks5 agent for wss upstreams behind socks5 proxies', async () => {
+ resolverState.resolve.mockResolvedValue('socks5://127.0.0.1:7891');
+ const agent = await createOutboundHttpAgent('wss://api.elevenlabs.io/v1/x');
+ expect(agent).toBeInstanceOf(Socks5HttpsAgent);
+ agent?.destroy();
+ });
+
+ it('declines plaintext ws upstreams behind http proxies, warning once', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ await expect(createOutboundHttpAgent('ws://relay.example.com/socket')).resolves.toBeUndefined();
+ await expect(createOutboundHttpAgent('ws://relay.example.com/socket')).resolves.toBeUndefined();
+ expect(loggerState.warn).toHaveBeenCalledTimes(1);
+ });
+
+ it('never proxies loopback websockets', async () => {
+ resolverState.resolve.mockResolvedValue('http://127.0.0.1:7890');
+ await expect(createOutboundHttpAgent('ws://127.0.0.1:8123/hooks')).resolves.toBeUndefined();
+ expect(resolverState.resolve).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
index 62d02d1fdd..7d4c30e2ae 100644
--- a/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
+++ b/apps/desktop/src/main/maker-host/anthropic-responses-bridge-host.ts
@@ -25,6 +25,7 @@ import path from 'node:path';
import { createResponsesHandler, type BridgeProviderConfig, type ResponsesBridgeHandler } from '@cindy/anthropic-responses-bridge';
import { createMakerLogger } from './logger-adapter.js';
+import { outboundFetch } from './outbound-fetch.js';
import { getGrokAccessToken } from './grok-oauth-login.js';
import { invalidateXaiBridgeAuth } from './xai-auth-invalidation-host.js';
import { chatgptAccountIdFromIdToken, desktopCodexAuthAdapter } from './auth-adapters.js';
@@ -131,7 +132,7 @@ async function refreshIfNeeded(authPath: string, current: CodexAuthFile): Promis
log.info('bridge 兜底刷新 codex access_token', { last_refresh: fresh.last_refresh });
// 必须带超时:本 fetch 在 _refreshChain mutex 内,undici 默认 headersTimeout 5 分钟,
// auth.openai.com 挂起会让所有排队的 chatgpt/ 请求一起卡住。超时走 catch → 本次用旧 token。
- const res = await fetch(OPENAI_TOKEN_URL, {
+ const res = await outboundFetch(OPENAI_TOKEN_URL, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
@@ -310,6 +311,9 @@ export function getResponsesBridgeHandler(): ResponsesBridgeHandler | null {
_handler = createResponsesHandler({
providers: [codexProviderConfig(), xaiProviderConfig()],
logger: log,
+ // 订阅直连的上游(chatgpt.com / api.x.ai)由 handler 自己发出,不经 compat-proxy
+ // 的转发层,拿不到那边的出站代理;必须显式注入(见 outbound-fetch.ts)。
+ fetchImpl: outboundFetch,
});
} catch (err) {
_handler = null;
diff --git a/apps/desktop/src/main/maker-host/claude-oauth-login.ts b/apps/desktop/src/main/maker-host/claude-oauth-login.ts
index 85e542f6bf..162494eb71 100644
--- a/apps/desktop/src/main/maker-host/claude-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/claude-oauth-login.ts
@@ -27,6 +27,7 @@ import {
} from '../oauthResultPage.js';
import { describeErrorChain } from '../utils/errorChain.js';
import { desktopMakerLogger } from './logger-adapter.js';
+import { outboundFetch } from './outbound-fetch.js';
import { writeClaudeAiOAuth } from './claude-credentials-store.js';
import { bindNativeProviderAuth } from './nativeProviderAuthBinding.js';
import { backfillClaudeSubscriptionProfile } from './claude-oauth-refresh.js';
@@ -101,7 +102,10 @@ async function exchangeCodeForTokens(
port: number,
signal: AbortSignal,
): Promise<TokenExchangeResponse> {
- const res = await fetch(TOKEN_URL, {
+ // outboundFetch:换 token 是 main 自己发的 HTTPS 请求,不经浏览器。裸 undici fetch
+ // 不吃系统代理,代理软件跑「系统代理」模式时授权页正常、这一步却直连出网,被上游按
+ // 来源拒(实测 403)。
+ const res = await outboundFetch(TOKEN_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
diff --git a/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts b/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts
index 6071056ebb..ee99bb291b 100644
--- a/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts
+++ b/apps/desktop/src/main/maker-host/claude-oauth-refresh.ts
@@ -53,6 +53,7 @@ import {
type ClaudeAiOAuth,
} from './claude-credentials-store.js';
import { desktopMakerLogger } from './logger-adapter.js';
+import { outboundFetch } from './outbound-fetch.js';
const log = desktopMakerLogger.child('claude-oauth-refresh');
@@ -120,7 +121,7 @@ export interface SubscriptionProfile {
*/
export async function fetchSubscriptionProfile(
accessToken: string,
- fetchFn: typeof fetch = fetch,
+ fetchFn: typeof fetch = outboundFetch,
): Promise<SubscriptionProfile | null> {
try {
const res = await fetchFn(PROFILE_URL, {
@@ -693,7 +694,8 @@ function getDefaultRefresher(): ReturnType<typeof createClaudeOAuthRefresher> {
defaultRefresher = createClaudeOAuthRefresher({
readOAuth: readClaudeAiOAuth,
writeOAuth: writeClaudeAiOAuth,
- fetchFn: fetch,
+ // 刷新与 profile 回填都打境外端点,必须吃系统代理(见 outbound-fetch.ts)。
+ fetchFn: outboundFetch,
now: Date.now,
lockDir: defaultLockDir,
onInvalidGrant: () => invalidGrantHandler?.(),
diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
index d9e1ba56f0..7deedf8c8e 100644
--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts
+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts
@@ -63,6 +63,7 @@ import { createXaiProxyAuthInvalidationObserver } from './xai-auth-invalidation-
import { encryptedStripController, imageGenerationStripController } from './thread-strip-controllers.js';
import { createMakerLogger } from './logger-adapter.js';
import { resolveDesktopOutboundProxy } from './outbound-proxy-resolver.js';
+import { outboundFetch } from './outbound-fetch.js';
import { readSilentEncryptedRetrySettings } from './silent-encrypted-retry-store.js';
import { getLogDir } from '../logger.js';
import { recordXaiRateLimitSnapshot } from '../usageBroadcaster.js';
@@ -292,7 +293,9 @@ function createChatBridgeDecision(
rewriteModel: (model: string) => rewriteChatBridgeModel(model, stripPrefix),
capabilities,
...(onUpstreamError ? { onUpstreamError } : {}),
- }, { logger: log });
+ // localHandler 分支的上游请求由 chat bridge 自己发,绕开了 compat-proxy 转发层的
+ // 出站代理;显式注入代理感知 fetch(见 outbound-fetch.ts)。
+ }, { logger: log, fetchImpl: outboundFetch });
return {
localHandler: ({ rawBody, parsedBody, res }) => {
let body = parsedBody;
diff --git a/apps/desktop/src/main/maker-host/generic-oauth.ts b/apps/desktop/src/main/maker-host/generic-oauth.ts
index 44bacad2ac..32267b54e2 100644
--- a/apps/desktop/src/main/maker-host/generic-oauth.ts
+++ b/apps/desktop/src/main/maker-host/generic-oauth.ts
@@ -31,6 +31,7 @@ import {
type OAuthResultPageLang,
} from '../oauthResultPage.js';
import { desktopMakerLogger } from './logger-adapter.js';
+import { outboundFetch } from './outbound-fetch.js';
const log = desktopMakerLogger.child('generic-oauth');
@@ -77,7 +78,8 @@ function sleepWithAbort(ms: number, signal: AbortSignal): Promise<void> {
let io: GenericOAuthIo = {
storage: { read: () => null, write: () => false, remove: () => {} },
- fetchImpl: fetch,
+ // 第三方 provider 的 token / device / refresh 端点多在境外,默认走吃系统代理的通道。
+ fetchImpl: outboundFetch,
openExternal: async () => {
throw new Error('generic-oauth openExternal not configured');
},
diff --git a/apps/desktop/src/main/maker-host/grok-oauth-login.ts b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
index 1c69894f35..d41ead6d25 100644
--- a/apps/desktop/src/main/maker-host/grok-oauth-login.ts
+++ b/apps/desktop/src/main/maker-host/grok-oauth-login.ts
@@ -30,6 +30,7 @@ import {
type OAuthResultPageLang,
} from '../oauthResultPage.js';
import { desktopMakerLogger } from './logger-adapter.js';
+import { outboundFetch } from './outbound-fetch.js';
import { getProviderSecretStore } from '../secrets/providerSecretStore.js';
import { bindNativeProviderAuth, isNativeProviderAuthBound, unbindNativeProviderAuth } from './nativeProviderAuthBinding.js';
import type { XaiBridgeAuthRecoveryOutcome } from './xai-bridge-auth-invalidation.js';
@@ -146,7 +147,7 @@ async function resolveEndpoints(
signal: AbortSignal,
): Promise<{ authorize: string; token: string }> {
try {
- const res = await fetch(OIDC_DISCOVERY_URL, { signal });
+ const res = await outboundFetch(OIDC_DISCOVERY_URL, { signal });
if (res.ok) {
const j = (await res.json()) as { authorization_endpoint?: string; token_endpoint?: string };
if (j.authorization_endpoint && j.token_endpoint) {
@@ -525,7 +526,7 @@ export async function runGrokOAuthLogin(opts?: {
opts?.onProgress?.('exchanging');
// form-encoded + PKCE 二次校验(challenge/method 再发一次)。
- const res = await fetch(token, {
+ const res = await outboundFetch(token, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
@@ -678,7 +679,7 @@ async function refreshBlob(current: GrokTokenBlob, force: boolean): Promise<Grok
// 刷新路径只需 token endpoint,直接用常量,避免 OIDC discovery fetch 挂起整条 _refreshChain。
// 必须带超时:本 fetch 在 _refreshChain mutex 内,undici 默认 headersTimeout 5 分钟,
// auth.x.ai 挂起会让所有排队的 xai/ 请求一起卡住;超时走 catch → 本次用旧 token。
- const res = await fetch(FALLBACK_TOKEN_URL, {
+ const res = await outboundFetch(FALLBACK_TOKEN_URL, {
method: 'POST',
headers: { 'content-type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
diff --git a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
index bb25636067..bf0cef5a94 100644
--- a/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
+++ b/apps/desktop/src/main/maker-host/model-discovery/anthropic.ts
@@ -60,6 +60,7 @@ import {
} from '../active-catalog.js';
import { hasClaudeAiOAuth, readClaudeAiOAuth } from '../claude-credentials-store.js';
import { getValidClaudeAiOAuth } from '../claude-oauth-refresh.js';
+import { outboundFetch } from '../outbound-fetch.js';
const log = createLogger('model-discovery:anthropic');
@@ -929,7 +930,7 @@ export function refreshAnthropicModelsFromHttp(options?: {
let url: string | null = `${upstream.replace(/\/+$/, '')}/v1/models?limit=1000`;
try {
for (let page = 0; url && page < MAX_MODEL_PAGES; page += 1) {
- const res: Response = await fetch(url, {
+ const res: Response = await outboundFetch(url, {
headers: {
authorization: `Bearer ${oauth.accessToken}`,
'anthropic-version': '2023-06-01',
diff --git a/apps/desktop/src/main/maker-host/outbound-fetch.ts b/apps/desktop/src/main/maker-host/outbound-fetch.ts
new file mode 100644
index 0000000000..f51b90b94e
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/outbound-fetch.ts
@@ -0,0 +1,835 @@
+/**
+ * outbound-fetch —— main 侧「吃系统代理」的出网通道(undici fetch + ws agent)。
+ *
+ * 背景:Node 的 undici(`globalThis.fetch`)与 `ws` 都**不读系统代理设置、也不读
+ * 代理环境变量**。用户的代理软件跑「系统代理」模式(非 TUN)时,浏览器 / Electron
+ * `net.fetch`(Chromium 栈)正常,而 main 里的裸 `fetch` / `new WebSocket()` 是直连 ——
+ * 高墙网络下换 token 被上游按来源拒(实测 platform.claude.com 换 token 回 403)、
+ * 订阅直连上游连不上、provider 连通性探测误报不通。
+ *
+ * 本模块把仓库里已有的出站代理能力(`outbound-proxy-resolver` 的两层解析 +
+ * `@cindy/anthropic-compat-proxy` 的 HTTP CONNECT 隧道与 SOCKS5 agent)接到这两个栈上:
+ *
+ * - `outboundFetch`:签名与 `globalThis.fetch` 对齐的替换品,per-request 现取代理。
+ * 现存 `fetchImpl: typeof fetch` / `fetchFn: typeof fetch` 注入点可直接换默认值。
+ * - `resolveOutboundDispatcher`:给已有自建 dispatcher 的调用点(voice-input 的
+ * keepalive 池)用 —— 有代理时返回代理 dispatcher,直连时返回调用方的 fallback。
+ * - `createOutboundHttpAgent`:给 `ws` 用(`new WebSocket(url, { agent })`)。
+ *
+ * 语义与 loopback proxy host 那两处完全一致:loopback 上游恒直连;代理解析失败
+ * fail-open 走直连(不断链路);代理地址只以脱敏形态进日志。
+ *
+ * 已知限制:
+ * - **需要认证的系统代理不支持**。`session.resolveProxy` 只给 host:port,凭证由
+ * Chromium 自己的 proxy-auth 挑战(`app.on('login')`)补,Node/undici 这条路没有对接
+ * 口 —— 这类环境下会收到 407。命中 407 会明确告警并提示改用带 userinfo 的
+ * `HTTPS_PROXY`(env 层支持 Proxy-Authorization)。
+ * - 直连路径不经 undici(走 `globalThis.fetch`,以保证无代理时行为与改造前逐字节
+ * 一致),所以「直连 URL 重定向到需要代理的 host」不会中途升级成走代理 —— 与改造前
+ * 一致,不是本模块引入。
+ */
+
+import type { Agent as NodeHttpAgent } from 'node:http';
+
+import {
+ Agent as UndiciAgent,
+ Dispatcher,
+ ProxyAgent,
+ buildConnector,
+ fetch as undiciFetch,
+} from 'undici';
+
+import {
+ isLoopbackHostname,
+ parseOutboundProxyUrl,
+ redactProxyUrlForLog,
+ socks5Connect,
+ Socks5HttpAgent,
+ Socks5HttpsAgent,
+ stripIpv6Brackets,
+ TunnelingHttpsAgent,
+ type OutboundProxyTarget,
+} from '@cindy/anthropic-compat-proxy';
+
+import { createMakerLogger } from './logger-adapter.js';
+import { resolveDesktopOutboundProxy } from './outbound-proxy-resolver.js';
+
+const log = createMakerLogger('outbound-fetch');
+
+/**
+ * Happy Eyeballs 单地址握手超时。与 `main/index.ts` 的进程级默认值、
+ * `voice-input/refinerHttpDispatcher.ts` 的 per-pool 值同为 2500ms:代理软件背后可能
+ * 现拨远端节点,Node 默认的 250ms 会把合法握手全掐掉,只剩一个裸 'fetch failed'。
+ */
+const CONNECT_ATTEMPT_TIMEOUT_MS = 2500;
+
+/** 正常场景同一时刻只有一个系统代理;上限只防 PAC 按 host 给不同出口时无限累积。 */
+const DISPATCHER_POOL_MAX_ENTRIES = 8;
+
+/**
+ * 被逐出的 dispatcher 延迟这么久才 close。逐出的实例可能刚被某个调用方取走、还没
+ * 把请求交给 undici(`resolveOutboundDispatcher` 返回 → 调用方 fetch 之间有个窗口),
+ * 立刻 close 会让那一发请求撞上「dispatcher 已关闭」。宽限期内新请求照常发,过后
+ * 再优雅关闭空闲连接(close 本身会等已入队请求跑完)。
+ */
+const EVICTED_DISPATCHER_CLOSE_GRACE_MS = 60_000;
+
+/** routing wrapper 只做派发、不持有连接,逐出即丢,无需 close;上限只防无限增长。 */
+const ROUTING_POOL_MAX_ENTRIES = 64;
+
+/** 告警去重集合的上限 —— 满了整体清空(下一轮重新记一次,不会静默丢告警)。 */
+const WARNED_ORIGINS_MAX_ENTRIES = 256;
+
+/**
+ * 同步可读的「该 origin 当前该走什么」快照。用途只有一个:undici 内部跟随重定向时
+ * 会拿同一个 dispatcher 去打新 origin,而 dispatch() 是同步 API,来不及做一次
+ * `session.resolveProxy` 往返 —— 快照命中就能按新 origin 正确选出口。TTL 与
+ * outbound-proxy-resolver 的系统代理缓存同为 30s。
+ */
+const PROXY_DECISION_TTL_MS = 30 * 1000;
+
+export interface ResolveOutboundDispatcherOptions {
+ /** 直连(或代理不可用)时返回的 dispatcher —— 调用方已有的连接池。 */
+ fallback?: Dispatcher;
+ /** 代理 dispatcher 的连接池调优(keepAlive / connections 等),参与缓存 key。 */
+ agentOptions?: UndiciAgent.Options;
+ /**
+ * 调用方的取消信号。选路发生在请求出发之前,不传的话它就落在调用方的超时预算之外
+ * (见 PROXY_RESOLVE_TIMEOUT_MS 的注释);传了则 abort 时立刻抛,与 fetch 语义一致。
+ */
+ signal?: AbortSignal;
+}
+
+const dispatcherPool = new Map<string, Dispatcher>();
+const routingPool = new Map<string, Dispatcher>();
+// 每个 origin 上次告警过的原因;不支持的组合只记一次,不在热路径上刷日志。
+const warnedOrigins = new Set<string>();
+const proxyDecisionCache = new Map<string, { raw: string | null; expiresAt: number }>();
+let directAgent: UndiciAgent | null = null;
+
+/** 重定向落到 loopback / 已知直连 origin 时用的直连池(与代理池同握手调优)。 */
+function getDirectAgent(): UndiciAgent {
+ directAgent ??= new UndiciAgent({
+ connect: { autoSelectFamilyAttemptTimeout: CONNECT_ATTEMPT_TIMEOUT_MS },
+ });
+ return directAgent;
+}
+
+function upstreamProtocol(url: URL): 'http:' | 'https:' {
+ // ws/wss 在代理层与 http/https 同构(wss 经 CONNECT 隧道后做 TLS)。
+ if (url.protocol === 'wss:' || url.protocol === 'https:') return 'https:';
+ return 'http:';
+}
+
+function defaultPort(protocol: 'http:' | 'https:'): number {
+ return protocol === 'https:' ? 443 : 80;
+}
+
+/**
+ * 解析上游 URL。解不出(调用方给了相对路径等)返回 null —— 由调用方按直连处理,
+ * 真正的报错留给底层 fetch,本模块不制造新的失败模式。
+ */
+function parseUpstream(url: string): URL | null {
+ try {
+ return new URL(url);
+ } catch {
+ return null;
+ }
+}
+
+/** 上游 origin 串(协议 + host)—— 日志与 loopback 判定用。 */
+function originOf(upstream: URL): string {
+ return `${upstreamProtocol(upstream)}//${upstream.host}`;
+}
+
+/**
+ * 送给 resolver / 两级缓存的 key:origin + path,**不带 query 与 fragment**。
+ *
+ * 带 path 是因为 PAC 的 `FindProxyForURL(url, host)` 允许按路径判定 —— 只送 origin 会
+ * 让同一 origin 上所有路径共用 `/` 的结论,配置了「某内部路径直连、其余走代理」的用户
+ * 会被判错(review 2026-07-27 P1)。不带 query 是纪律:query 常带令牌等敏感参数,而它
+ * 会进入 resolver 的缓存 key;按 path 已经覆盖了现实中的 PAC 写法。
+ */
+function resolveKeyOf(upstream: URL): string {
+ return `${originOf(upstream)}${upstream.pathname}`;
+}
+
+/** 从 dispatch() 的 (origin, path) 拼出同一个 key —— 重定向选路要查同一份快照。 */
+function resolveKeyFromParts(origin: string, path: string | undefined): string {
+ const pathname = (path ?? '/').split('?')[0]?.split('#')[0] || '/';
+ return `${origin}${pathname}`;
+}
+
+/**
+ * 代理解析自身的超时。解析发生在请求真正出发之前,不受调用方 `signal` /
+ * `AbortSignal.timeout` 约束 —— `session.resolveProxy` 若慢或不 settle,OAuth 的 30s、
+ * 探测的 10s 这些既有上限就形同虚设(review 2026-07-27 P1)。超时按直连处理
+ * (fail-open,与其它解析故障同口径),不把请求拖死在选路上。
+ */
+const PROXY_RESOLVE_TIMEOUT_MS = 2000;
+
+function abortErrorOf(signal: AbortSignal): unknown {
+ return signal.reason ?? new DOMException('This operation was aborted', 'AbortError');
+}
+
+/**
+ * 带两道保险地取代理串:调用方 abort 立刻抛(与 fetch 的取消语义一致),解析自身
+ * 超时则按直连处理。
+ */
+async function resolveRawProxy(
+ resolveKey: string,
+ origin: string,
+ signal?: AbortSignal,
+): Promise<string | null> {
+ if (signal?.aborted) throw abortErrorOf(signal);
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let onAbort: (() => void) | undefined;
+ try {
+ return await Promise.race<string | null>([
+ Promise.resolve(resolveDesktopOutboundProxy(resolveKey)).then((v) => v ?? null),
+ new Promise<string | null>((resolve) => {
+ timer = setTimeout(() => {
+ warnOnce(origin, 'resolution-timed-out', { upstream: origin });
+ resolve(null);
+ }, PROXY_RESOLVE_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ new Promise<never>((_resolve, reject) => {
+ if (!signal) return;
+ onAbort = () => reject(abortErrorOf(signal));
+ signal.addEventListener('abort', onAbort, { once: true });
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (onAbort && signal) signal.removeEventListener('abort', onAbort);
+ }
+}
+
+/** 取当前生效的代理目标;直连 / 解析失败 / loopback 上游一律 null。 */
+async function resolveProxyTarget(
+ upstream: URL,
+ signal?: AbortSignal,
+): Promise<OutboundProxyTarget | null> {
+ if (isLoopbackHostname(upstream.hostname)) return null;
+ // resolver 拿 origin + path(PAC 可按路径判定);日志与告警只用 origin。
+ const resolveKey = resolveKeyOf(upstream);
+ const originUrl = originOf(upstream);
+ let raw: string | null | undefined;
+ try {
+ raw = await resolveRawProxy(resolveKey, originUrl, signal);
+ } catch (err) {
+ // 取消要如实向上抛(否则调用方的 abort 变成静默直连请求)。
+ if (signal?.aborted) throw err;
+ // fail-open:代理解析故障不该让请求失败,退回直连(与 resolver 内部语义一致)。
+ log.warn('outbound proxy resolution failed — using direct connection', {
+ upstream: originUrl,
+ err: err instanceof Error ? err.message : String(err),
+ });
+ return null;
+ }
+ rememberProxyDecision(resolveKey, raw ?? null);
+ if (!raw) return null;
+ const target = parseOutboundProxyUrl(raw);
+ if (!target) {
+ warnOnce(originUrl, 'unsupported-proxy-scheme', {
+ upstream: originUrl,
+ proxy: redactProxyUrlForLog(raw),
+ });
+ return null;
+ }
+ return target;
+}
+
+/** key 是 resolveKeyOf() 给的「origin + path」,不是单纯 origin —— per-path PAC 靠它。 */
+function rememberProxyDecision(resolveKey: string, raw: string | null): void {
+ if (proxyDecisionCache.size >= ROUTING_POOL_MAX_ENTRIES) {
+ // 与 routing wrapper 同量级即够(快照只服务重定向选路);满了整体重建,不做 LRU。
+ proxyDecisionCache.clear();
+ }
+ proxyDecisionCache.set(resolveKey, { raw, expiresAt: Date.now() + PROXY_DECISION_TTL_MS });
+}
+
+/**
+ * 同步取某个解析 key(**origin + path**,不是单纯 origin)的代理决策:
+ * `{ known: false }` = 快照里没有(调用方自行决定兜底),`{ known: true, target: null }`
+ * = 直连,否则给出代理目标。不发起任何异步解析。
+ */
+function syncProxyDecision(resolveKey: string): { known: boolean; target: OutboundProxyTarget | null } {
+ const hit = proxyDecisionCache.get(resolveKey);
+ if (!hit || hit.expiresAt <= Date.now()) return { known: false, target: null };
+ if (!hit.raw) return { known: true, target: null };
+ return { known: true, target: parseOutboundProxyUrl(hit.raw) };
+}
+
+function warnOnce(origin: string, reason: string, fields: Record<string, unknown>): void {
+ const key = `${origin}:${reason}`;
+ if (warnedOrigins.has(key)) return;
+ // 异常代理配置下 origin 可能持续变化;满了整体清空(下一轮重新记一次)而不是无限增长。
+ if (warnedOrigins.size >= WARNED_ORIGINS_MAX_ENTRIES) warnedOrigins.clear();
+ warnedOrigins.add(key);
+ log.warn(`outbound proxy ${reason} — using direct connection`, fields);
+}
+
+/**
+ * dispatcher 缓存 key。凭证参与(同地址不同凭证不能共享连接池);上游协议参与
+ * (https 要在隧道上做 TLS,http 不做);调优参数参与(调用方各自的池语义不同)。
+ * 用 JSON 数组而非拼接:字段本身可能含分隔符,拼接会让不同输入撞成同一 key。
+ */
+function dispatcherKey(
+ proxy: OutboundProxyTarget,
+ protocol: 'http:' | 'https:',
+ agentOptions: UndiciAgent.Options | undefined,
+): string {
+ return JSON.stringify([
+ proxy.kind,
+ proxy.url,
+ proxy.authHeader ?? '',
+ proxy.username ?? '',
+ proxy.password ?? '',
+ protocol,
+ agentOptions ? JSON.stringify(identifyFunctions(agentOptions)) : '',
+ ]);
+}
+
+// 函数身份 → 稳定标识。函数在 JSON.stringify 里会被整个丢掉,直接 stringify
+// agentOptions 会让「两个不同的自定义 connect / factory」塌成同一个 key,进而共享一个
+// 用别的 connector 建出来的 dispatcher(review 2026-07-27)。WeakMap 不阻止回收。
+const functionKeys = new WeakMap<object, string>();
+let functionKeySeq = 0;
+
+function functionKey(fn: object): string {
+ let key = functionKeys.get(fn);
+ if (!key) {
+ functionKeySeq += 1;
+ key = `fn#${functionKeySeq}`;
+ functionKeys.set(fn, key);
+ }
+ return key;
+}
+
+/** 把 options 里的函数值换成稳定标识,其余原样(键顺序沿用调用方给的顺序)。 */
+function identifyFunctions(value: unknown): unknown {
+ if (typeof value === 'function') return functionKey(value as object);
+ if (Array.isArray(value)) return value.map(identifyFunctions);
+ if (value && typeof value === 'object') {
+ return Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).map(([k, v]) => [k, identifyFunctions(v)]),
+ );
+ }
+ return value;
+}
+
+function closeAfterGrace(dispatcher: Dispatcher): void {
+ // 立刻 close 会打断「已取走但还没提交」的那一发请求(review 2026-07-27 P1);
+ // 宽限期后再 close,timer unref 不拖住进程退出。
+ const timer = setTimeout(() => {
+ void dispatcher.close().catch(() => {
+ /* 关闭空闲连接失败无所谓,交给 GC */
+ });
+ }, EVICTED_DISPATCHER_CLOSE_GRACE_MS);
+ timer.unref?.();
+}
+
+function poolGet(key: string, create: () => Dispatcher): Dispatcher {
+ const existing = dispatcherPool.get(key);
+ if (existing) return existing;
+ if (dispatcherPool.size >= DISPATCHER_POOL_MAX_ENTRIES) {
+ const oldest = dispatcherPool.keys().next().value;
+ if (oldest !== undefined) {
+ const evicted = dispatcherPool.get(oldest);
+ dispatcherPool.delete(oldest);
+ if (evicted) closeAfterGrace(evicted);
+ }
+ }
+ const created = create();
+ dispatcherPool.set(key, created);
+ return created;
+}
+
+function routingPoolGet(key: string, create: () => Dispatcher): Dispatcher {
+ const existing = routingPool.get(key);
+ if (existing) return existing;
+ if (routingPool.size >= ROUTING_POOL_MAX_ENTRIES) {
+ const oldest = routingPool.keys().next().value;
+ // wrapper 不持有连接(底层池才有),逐出直接丢,不能 close —— 那会连带关掉共享池。
+ if (oldest !== undefined) routingPool.delete(oldest);
+ }
+ const created = create();
+ routingPool.set(key, created);
+ return created;
+}
+
+/**
+ * SOCKS5 的 undici connector:先经代理握手拿裸 socket,再把它交给 undici 原生
+ * connector 做 TLS(`httpSocket` 选项)—— TLS 端到端,SNI / 证书校验沿用 undici 逻辑,
+ * 代理只见密文。http 上游没有 TLS 这一步,握手好的 socket 直接就是那条 TCP 连接。
+ */
+function createSocks5Connector(
+ proxy: OutboundProxyTarget,
+ connectOptions: Record<string, unknown>,
+): buildConnector.connector {
+ // BuildOptions 的类型联合里 TcpNetConnectOpts 要求 port,但 connector 的 port 是
+ // per-request 从 options 取的(建 connector 时给不了);undici 运行时只读我们传的这
+ // 几个字段,断言收在这一行。
+ const tlsConnector = buildConnector(connectOptions as buildConnector.BuildOptions);
+ return (options, callback) => {
+ const protocol = options.protocol === 'https:' ? 'https:' : 'http:';
+ const port = Number(options.port) || defaultPort(protocol);
+ socks5Connect(proxy, stripIpv6Brackets(options.hostname), port)
+ .then((socket) => {
+ if (protocol !== 'https:') {
+ callback(null, socket);
+ return;
+ }
+ tlsConnector({ ...options, httpSocket: socket }, callback);
+ })
+ .catch((err: unknown) => {
+ callback(err instanceof Error ? err : new Error(String(err)), null);
+ });
+ };
+}
+
+/**
+ * 合并握手配置:调用方给的 `agentOptions.connect` 优先,只在它没给某项时补默认。
+ * 无条件覆盖会让调用方的调优失效(voice-input 允许用 env 调
+ * autoSelectFamilyAttemptTimeout),而该字段又参与 dispatcherKey —— 那就白白多分一个
+ * 语义相同的池(review 2026-07-27)。调用方传的是自定义 connector 函数时原样保留。
+ *
+ * @internal 导出仅供单测断言合并规则。
+ */
+export function resolveConnectOptions(
+ agentOptions: UndiciAgent.Options | undefined,
+): Record<string, unknown> | UndiciAgent.Options['connect'] {
+ const callerConnect = agentOptions?.connect;
+ if (typeof callerConnect === 'function') return callerConnect;
+ return {
+ autoSelectFamilyAttemptTimeout: CONNECT_ATTEMPT_TIMEOUT_MS,
+ ...(callerConnect && typeof callerConnect === 'object'
+ ? (callerConnect as Record<string, unknown>)
+ : {}),
+ };
+}
+
+function createProxyDispatcher(
+ proxy: OutboundProxyTarget,
+ protocol: 'http:' | 'https:',
+ agentOptions: UndiciAgent.Options | undefined,
+): Dispatcher {
+ log.debug('creating outbound proxy dispatcher', { proxy: proxy.url, protocol });
+ const connect = resolveConnectOptions(agentOptions);
+ if (proxy.kind === 'socks5') {
+ // SOCKS5 隧道必须用我们自己的 connector(先握手再在裸 socket 上做 TLS),调用方若
+ // 自带 connector 无法复用 —— 那时 TLS 段退回默认握手参数。
+ const tlsOptions =
+ typeof connect === 'function'
+ ? { autoSelectFamilyAttemptTimeout: CONNECT_ATTEMPT_TIMEOUT_MS }
+ : ((connect ?? {}) as Record<string, unknown>);
+ return new UndiciAgent({
+ ...agentOptions,
+ connect: createSocks5Connector(proxy, tlsOptions),
+ });
+ }
+ return new ProxyAgent({
+ ...agentOptions,
+ uri: proxy.url,
+ ...(proxy.authHeader ? { token: proxy.authHeader } : {}),
+ connect,
+ });
+}
+
+/**
+ * 按**当前请求的 origin** 派发的 dispatcher 包装。
+ *
+ * 为什么需要:`fetch` 默认 `redirect: 'follow'`,undici 在内部跟随重定向时会一直用
+ * 同一个 dispatcher。裸给代理 dispatcher 的话,一个走代理的 URL 302 到 loopback 或
+ * 到 NO_PROXY 豁免的 host,后续跳仍会被塞进代理隧道 —— 既破坏 bypass 语义,也破坏
+ * 本模块「loopback 恒直连」的承诺(review 2026-07-27 P1)。
+ *
+ * 包装后每一跳都按目标 origin 重新选出口:
+ * - 首跳 origin → 原代理池(命中率最高的情况,零额外开销)
+ * - loopback → 直连池(**同步可判**,无需解析,承诺因此在重定向后依然成立)
+ * - 其它 origin → 查同步快照:直连决策走直连池,代理决策走对应代理池
+ * - 快照没有(该 origin 从没解析过)→ 沿用首跳的代理,并后台补一次解析,让下次准确。
+ * 这是 `dispatch()` 同步契约下的取舍:宁可多走一次代理,也不为了精确而阻塞热路径。
+ *
+ * 已知限制(与改造前一致,不是本 PR 引入):直连路径不经 undici(走 `globalThis.fetch`),
+ * 所以「直连 URL 重定向到需要代理的 host」不会中途升级成走代理。
+ *
+ * 类体懒建(第一次真的要走代理时才求值 `extends Dispatcher`):模块加载期不碰 undici 的
+ * 类,单测对 undici 做部分 mock 时不必为它额外补 `Dispatcher` 导出。
+ */
+interface OriginRoutingDispatcher extends Dispatcher {
+ /** @internal 单测用:看某个目标 URL 会被路由到哪个底层 dispatcher。 */
+ pickForUrlForTest(url: string): Dispatcher;
+}
+
+/** wrapper 的首跳出口描述 —— 存的是「怎么取」而不是 dispatcher 实例本身,见下方注释。 */
+interface PrimaryRoute {
+ /** 首跳的解析 key(origin + path),与快照 / resolver 同一维度。 */
+ resolveKey: string;
+ proxy: OutboundProxyTarget;
+ protocol: 'http:' | 'https:';
+}
+
+type OriginRoutingDispatcherCtor = new (
+ primary: PrimaryRoute,
+ agentOptions: UndiciAgent.Options | undefined,
+) => OriginRoutingDispatcher;
+
+let _routingDispatcherCtor: OriginRoutingDispatcherCtor | null = null;
+
+function routingDispatcherCtor(): OriginRoutingDispatcherCtor {
+ if (_routingDispatcherCtor) return _routingDispatcherCtor;
+ _routingDispatcherCtor = class extends Dispatcher {
+ constructor(
+ private readonly primary: PrimaryRoute,
+ private readonly agentOptions: UndiciAgent.Options | undefined,
+ ) {
+ super();
+ }
+
+ override dispatch(
+ options: Dispatcher.DispatchOptions,
+ handler: Dispatcher.DispatchHandler,
+ ): boolean {
+ return this.pick(options).dispatch(options, handler);
+ }
+
+ /** close/destroy 恒不向下传:底层是共享池,包装只是一层路由。 */
+ override async close(): Promise<void> {}
+ override async destroy(): Promise<void> {}
+
+ pickForUrlForTest(url: string): Dispatcher {
+ // 与 undici 的 dispatch 一致:origin 与 path 分开给。
+ const parsed = parseUpstream(url);
+ return this.pick({
+ origin: parsed ? originOf(parsed) : url,
+ path: parsed ? `${parsed.pathname}${parsed.search}` : '/',
+ method: 'GET',
+ });
+ }
+
+ private pick(options: Dispatcher.DispatchOptions): Dispatcher {
+ const target = this.targetUrl(options);
+ if (!target) return this.forProxy(this.primary.proxy, this.primary.protocol);
+ const origin = originOf(target);
+ if (isLoopbackHostname(target.hostname)) return getDirectAgent();
+ // 快照与 resolver 同 key(origin + path):PAC 可按路径判定,只比 origin 会串味。
+ const key = resolveKeyFromParts(origin, options.path);
+ if (key === this.primary.resolveKey) {
+ return this.forProxy(this.primary.proxy, this.primary.protocol);
+ }
+ const decision = syncProxyDecision(key);
+ if (!decision.known) {
+ // 后台补解析(它会写进快照),本跳沿用首跳出口。必须拿**带 path 的** URL 去解析
+ // —— 用只有 origin 的 target 会把结论写到 `origin + /` 上,而这里查的是
+ // `origin + path`,那就永远 miss、永远沿用首跳代理(review 2026-07-28 P1)。
+ // key 本身就是「origin + path」,直接拿它当 URL 解,写入与查询保证同键。
+ void resolveProxyTarget(parseUpstream(key) ?? target).catch(() => undefined);
+ return this.forProxy(this.primary.proxy, this.primary.protocol);
+ }
+ if (!decision.target) return getDirectAgent();
+ return this.forProxy(decision.target, upstreamProtocol(target));
+ }
+
+ /**
+ * 每次都从底层池现取(必要时重建),**不缓存 dispatcher 实例**:底层池有上限,
+ * 逐出后 60s 会 close 掉那个实例。若 wrapper 攥着旧引用,逐出之后就会把请求发给
+ * 一个已关闭的 dispatcher(review 2026-07-27 P1)。现取的代价只是一次 Map 查询。
+ */
+ private forProxy(proxy: OutboundProxyTarget, protocol: 'http:' | 'https:'): Dispatcher {
+ const key = dispatcherKey(proxy, protocol, this.agentOptions);
+ return poolGet(key, () => createProxyDispatcher(proxy, protocol, this.agentOptions));
+ }
+
+ private targetUrl(options: Dispatcher.DispatchOptions): URL | null {
+ const raw = options.origin;
+ if (raw instanceof URL) return raw;
+ if (typeof raw === 'string') return parseUpstream(raw);
+ return null;
+ }
+ } as unknown as OriginRoutingDispatcherCtor;
+ return _routingDispatcherCtor;
+}
+
+/**
+ * 取该上游当前该用的 undici dispatcher。直连 → `opts.fallback`(默认 undefined,
+ * 即 undici 全局 dispatcher,行为与改造前逐字节一致)。
+ */
+export async function resolveOutboundDispatcher(
+ url: string,
+ opts: ResolveOutboundDispatcherOptions = {},
+): Promise<Dispatcher | undefined> {
+ const upstream = parseUpstream(url);
+ if (!upstream) return opts.fallback;
+ const proxy = await resolveProxyTarget(upstream, opts.signal);
+ if (!proxy) return opts.fallback;
+ const protocol = upstreamProtocol(upstream);
+ const resolveKey = resolveKeyOf(upstream);
+ const key = dispatcherKey(proxy, protocol, opts.agentOptions);
+ // 先把底层池建起来(首跳大概率立刻要用),wrapper 里仍按 key 现取,所以底层被逐出
+ // 重建也不会留下 stale 引用。
+ poolGet(key, () => createProxyDispatcher(proxy, protocol, opts.agentOptions));
+ // 包装按 (底层 key, 首跳解析 key) 缓存:同一上游反复请求拿到同一个实例;
+ // 底层连接池仍跨 origin 共享(wrapper 本身不持有连接)。
+ const Routing = routingDispatcherCtor();
+ return routingPoolGet(
+ `${key}|${resolveKey}`,
+ () => new Routing({ resolveKey, proxy, protocol }, opts.agentOptions),
+ );
+}
+
+/**
+ * `globalThis.fetch` 的代理感知替换品:所有 `typeof fetch` 注入点可直接换默认值。
+ *
+ * 直连时**原样调用 `globalThis.fetch`** —— 与改造前逐字节一致(Node 内置的也是
+ * undici,`redirect: 'manual'` 同样如实回 3xx + Location,插件 network 槽的逐跳白名单
+ * 校验照旧;宿主与单测对全局 fetch 的替换也照旧生效)。只有代理生效时才切到 npm
+ * undici 的 fetch —— 那是唯一能挂 dispatcher 的入口。类型断言收口在这一处。
+ */
+export const outboundFetch = (async (
+ input: Parameters<typeof globalThis.fetch>[0],
+ init?: Parameters<typeof globalThis.fetch>[1],
+) => {
+ const target =
+ typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : ((input as { url?: string }).url ?? '');
+ const signal = signalOf(input, init);
+ const dispatcher = await resolveOutboundDispatcher(target, { signal });
+ if (!dispatcher) return globalThis.fetch(input, init);
+ const request = await normalizeForUndici(input, init);
+ if (request.init.redirect !== 'follow') {
+ // 调用方要 manual / error 语义(插件 network 槽靠 manual 逐跳守门),原样交给 undici。
+ return undiciFetch(request.url as never, { ...request.init, dispatcher } as never);
+ }
+ return followRedirectsThroughProxy(request, dispatcher, signal);
+}) as unknown as typeof globalThis.fetch;
+
+function signalOf(
+ input: Parameters<typeof globalThis.fetch>[0],
+ init: Parameters<typeof globalThis.fetch>[1],
+): AbortSignal | undefined {
+ if (init && 'signal' in init && init.signal) return init.signal;
+ if (typeof input === 'object' && input !== null && 'signal' in input) {
+ return (input as { signal?: AbortSignal }).signal;
+ }
+ return undefined;
+}
+
+/** 与 fetch 规范一致的跳数上限。 */
+const MAX_REDIRECT_HOPS = 20;
+
+/** fetch 规范的 redirect status 集合 —— 只有这几个才跟随。 */
+const REDIRECT_STATUSES = new Set([301, 302, 303, 307, 308]);
+
+/**
+ * 需要认证的系统代理:`session.resolveProxy` 只给 host:port,拿不到凭证 —— Chromium 自己
+ * 靠 `app.on('login')` 那套挑战交互补,而 Node/undici 这条路没有对接口,结果是 407。
+ *
+ * 我们不能凭空拿到系统 keychain 里的代理凭证,所以这里做不到透明支持;能做的是**不静默**:
+ * 命中 407 就明确告警,指出可用带凭证的 `HTTPS_PROXY`(env 层支持 userinfo → 会走
+ * Proxy-Authorization)绕过。这条限制同时登记在模块头与 PR 描述里。
+ */
+function noteProxyAuthRequired(url: string, status: number): void {
+ if (status !== 407) return;
+ const upstream = parseUpstream(url);
+ const origin = upstream ? originOf(upstream) : url;
+ warnOnce(origin, 'requires-authentication', {
+ upstream: origin,
+ hint: 'system proxy demands credentials; set HTTPS_PROXY=http://user:pass@host:port',
+ });
+}
+
+/**
+ * 代理路径上**自己**跟随重定向,每一跳都重新解析该 origin 该走什么。
+ *
+ * 为什么不交给 undici 的 `redirect: 'follow'`:它内部跟随时会一直用同一个 dispatcher,
+ * 而第一次访问某个重定向目标时我们的同步快照里通常没有它 —— 那一跳就会被塞进原来的
+ * 代理隧道,PAC / NO_PROXY 判定形同虚设(review 2026-07-27 P1)。这里逐跳 `await` 解析,
+ * 结论精确;两个 fetch 入口都走它,`OriginRoutingDispatcher` 只剩「调用方自带 dispatcher」
+ * (voice-input 的 keepalive 池)那条路径的兜底。
+ *
+ * 跳转语义按 fetch 规范的子集:303、以及 301/302 上的非 GET/HEAD → 转 GET 并丢 body;
+ * 307/308 原样重放(body 已是 Buffer,可重放);跨 origin 去掉凭证类头。
+ */
+async function followRedirectsThroughProxy(
+ request: { url: string; init: Record<string, unknown> },
+ initialDispatcher: Dispatcher,
+ signal: AbortSignal | undefined,
+): Promise<unknown> {
+ let url = request.url;
+ let method = String(request.init.method ?? 'GET');
+ let body = request.init.body as Buffer | undefined;
+ const headers = new Headers(request.init.headers as Array<[string, string]>);
+ let dispatcher: Dispatcher | undefined = initialDispatcher;
+
+ for (let hop = 0; ; hop += 1) {
+ const res = (await undiciFetch(url as never, {
+ method,
+ headers: [...headers] as Array<[string, string]>,
+ ...(body ? { body } : {}),
+ redirect: 'manual',
+ ...(signal ? { signal } : {}),
+ ...(dispatcher ? { dispatcher } : {}),
+ } as never)) as unknown as {
+ status: number;
+ headers: { get(name: string): string | null };
+ body?: { cancel(): Promise<void> } | null;
+ };
+ noteProxyAuthRequired(url, res.status);
+ const location = REDIRECT_STATUSES.has(res.status) ? res.headers.get('location') : null;
+ // 不是 fetch 定义的重定向状态(如 300 Multiple Choices、304 Not Modified),或没有
+ // Location(无从跟随)→ 原样回给调用方。**不能**按「3xx 且有 Location」就跟随:那会
+ // 让开代理时把 304 / 300 吞掉换成另一个响应,与直连路径行为不一致
+ // (review 2026-07-28 P1)。
+ if (!location) return res;
+ if (hop >= MAX_REDIRECT_HOPS) {
+ await res.body?.cancel().catch(() => undefined);
+ throw new TypeError('outboundFetch: too many redirects');
+ }
+ let next: URL;
+ try {
+ next = new URL(location, url);
+ } catch {
+ return res; // Location 非法:交回调用方按非 ok 处理,不自造异常
+ }
+ // fetch 规范的 method 改写只有两种情形:301/302 上的 **POST**,以及 303 上的
+ // 非 GET/HEAD。其余(301 上的 PUT/PATCH、303 上的 HEAD、307/308 全部)保留原方法
+ // 与 body(review 2026-07-28 P1:之前写宽了,PUT 会丢方法和 body、HEAD 会变 GET)。
+ const rewriteToGet =
+ ((res.status === 301 || res.status === 302) && method === 'POST') ||
+ (res.status === 303 && method !== 'GET' && method !== 'HEAD');
+ if (rewriteToGet) {
+ method = 'GET';
+ body = undefined;
+ headers.delete('content-type');
+ headers.delete('content-length');
+ }
+ if (new URL(url).origin !== next.origin) {
+ // 跨 origin 不重放凭证(与 github/gitlab client 的 fail-closed 纪律同口径)。
+ headers.delete('authorization');
+ headers.delete('cookie');
+ headers.delete('proxy-authorization');
+ }
+ // 3xx 的 body 不会被消费,显式取消以归还连接。
+ await res.body?.cancel().catch(() => undefined);
+ url = next.href;
+ dispatcher = await resolveOutboundDispatcher(url, { signal });
+ }
+}
+
+/**
+ * 把「全局 fetch 的入参」翻译成 npm undici 认得的形状。
+ *
+ * 为什么必须翻译:全局 `FormData` / `Blob` / `File` 来自 **Node 内置的** undici,而这里
+ * 用的是 **npm 包** undici —— 它的 body 提取靠 `instanceof` 自己那套类,跨实现的实例
+ * 认不出来,`FormData` 会被当普通对象序列化成 `[object FormData]`(review 2026-07-27 P1:
+ * 语音转写与 GitLab 附件上传都用全局 FormData)。
+ *
+ * 做法:交给全局 `Request` 归一化(它同时负责补 multipart 的 content-type 与 boundary),
+ * 再把 body 读成 Buffer 交给 undici。代价是流式上传会被缓冲成整块 —— 当前所有调用点
+ * 上传的都是内存里已有的字节(音频、附件),没有真正的流式上传。
+ */
+async function normalizeForUndici(
+ input: Parameters<typeof globalThis.fetch>[0],
+ init: Parameters<typeof globalThis.fetch>[1],
+): Promise<{ url: string; init: Record<string, unknown> }> {
+ const request = new Request(input as RequestInfo, init as RequestInit);
+ const body = request.body ? Buffer.from(await request.arrayBuffer()) : undefined;
+ return {
+ url: request.url,
+ init: {
+ method: request.method,
+ headers: [...request.headers] as Array<[string, string]>,
+ ...(body ? { body } : {}),
+ redirect: request.redirect,
+ signal: request.signal,
+ },
+ };
+}
+
+/**
+ * `undici` 自己的 fetch 签名版本 —— 调用点已经在用 `import { fetch as undiciFetch }`
+ * 且消费 undici 的 Response(如 `response.body?.cancel()`)时用这个,避免为了换通道
+ * 顺带改一圈类型。语义与 `outboundFetch` 完全一致。
+ */
+export const outboundUndiciFetch: typeof undiciFetch = async (input, init) => {
+ const target =
+ typeof input === 'string'
+ ? input
+ : input instanceof URL
+ ? input.href
+ : ((input as { url?: string }).url ?? '');
+ // signal 必须透传:选路在请求出发之前,不传就等于让调用方的取消晚生效(最多多等
+ // 一次解析超时),与 outboundFetch 的语义不一致。
+ const signal = signalOf(
+ input as Parameters<typeof globalThis.fetch>[0],
+ init as Parameters<typeof globalThis.fetch>[1],
+ );
+ const dispatcher = await resolveOutboundDispatcher(target, { signal });
+ if (!dispatcher) return undiciFetch(input, init);
+ const request = await normalizeForUndici(
+ input as Parameters<typeof globalThis.fetch>[0],
+ init as Parameters<typeof globalThis.fetch>[1],
+ );
+ if (request.init.redirect !== 'follow') {
+ return undiciFetch(request.url, { ...request.init, dispatcher } as never);
+ }
+ // 与 outboundFetch 同一套逐跳跟随:让 undici 内部跟随会把重定向那一跳按首跳的
+ // 代理判定发出去(review 2026-07-27 P1)。
+ return (await followRedirectsThroughProxy(request, dispatcher, signal)) as Awaited<
+ ReturnType<typeof undiciFetch>
+ >;
+};
+
+/**
+ * 给 node http 栈(主要是 `ws`:`new WebSocket(url, { agent })`)取代理 agent。
+ * 直连 → undefined(调用方原样不传 agent,行为与改造前一致)。
+ *
+ * 明文 `ws://` 到非 loopback 主机 + HTTP 代理的组合不支持:HTTP 代理下的明文上游走
+ * 绝对形式请求,而 WebSocket 的 upgrade 握手必须是隧道。实际用到的外网 WS 端点都是
+ * `wss://`;真遇到就记一次告警并直连,不静默。
+ */
+export async function createOutboundHttpAgent(url: string): Promise<NodeHttpAgent | undefined> {
+ const upstream = parseUpstream(url);
+ if (!upstream) return undefined;
+ const proxy = await resolveProxyTarget(upstream);
+ if (!proxy) return undefined;
+ const protocol = upstreamProtocol(upstream);
+ if (proxy.kind === 'socks5') {
+ return protocol === 'https:' ? new Socks5HttpsAgent(proxy) : new Socks5HttpAgent(proxy);
+ }
+ if (protocol !== 'https:') {
+ warnOnce(`${protocol}//${upstream.host}`, 'plaintext-upstream-unsupported', {
+ upstream: `${protocol}//${upstream.host}`,
+ proxy: proxy.url,
+ });
+ return undefined;
+ }
+ return new TunnelingHttpsAgent(proxy);
+}
+
+/** @internal 单测用:清空 dispatcher 池与告警去重状态。 */
+export function resetOutboundFetchStateForTest(): void {
+ for (const dispatcher of dispatcherPool.values()) {
+ void dispatcher.close().catch(() => {
+ /* no-op */
+ });
+ }
+ dispatcherPool.clear();
+ routingPool.clear();
+ proxyDecisionCache.clear();
+ warnedOrigins.clear();
+ // 直连池也要收:它是模块级单例,不重置会跨用例存活(状态不隔离 + 悬挂的空闲连接)。
+ if (directAgent) {
+ const agent = directAgent;
+ directAgent = null;
+ void agent.close().catch(() => {
+ /* no-op */
+ });
+ }
+}
diff --git a/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts b/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts
index 933b174463..e2ab69016f 100644
--- a/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts
+++ b/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts
@@ -77,36 +77,100 @@ interface CachedResolution {
expiresAt: number;
}
+/**
+ * 缓存条目上限。调用方可以按「origin + path」解析(PAC 允许按路径判定),条目数因此
+ * 与被访问的路径数同阶;满了整体重建(下一轮按 TTL 重新解析),不做 LRU。
+ */
+const SYSTEM_PROXY_CACHE_MAX_ENTRIES = 256;
+
const systemProxyCache = new Map<string, CachedResolution>();
// 每个 origin 上次记录过日志的生效值;仅在变化时记 info,避免 per-request 刷日志。
const lastLoggedByOrigin = new Map<string, string>();
+/** 日志维度恒为 origin:path 可能带业务语义,且按 path 去重会把日志刷成噪音。 */
+function originForLog(upstreamUrl: string): string {
+ try {
+ const u = new URL(upstreamUrl);
+ return `${u.protocol}//${u.host}`;
+ } catch {
+ return upstreamUrl;
+ }
+}
+
function logIfChanged(upstreamUrl: string, source: 'env' | 'system', value: string | null): void {
+ const origin = originForLog(upstreamUrl);
// env 值可能是 http://user:pass@host 形态,持久化日志只允许脱敏形态(scheme://host:port)。
const rendered = value === null ? 'direct' : redactProxyUrlForLog(value);
- if (lastLoggedByOrigin.get(upstreamUrl) === `${source}:${rendered}`) return;
- lastLoggedByOrigin.set(upstreamUrl, `${source}:${rendered}`);
- log.info('outbound proxy resolved', { upstream: upstreamUrl, source, proxy: rendered });
+ if (lastLoggedByOrigin.get(origin) === `${source}:${rendered}`) return;
+ if (lastLoggedByOrigin.size >= SYSTEM_PROXY_CACHE_MAX_ENTRIES) lastLoggedByOrigin.clear();
+ lastLoggedByOrigin.set(origin, `${source}:${rendered}`);
+ log.info('outbound proxy resolved', { upstream: origin, source, proxy: rendered });
+}
+
+/** resolveProxy 自身的上限。Chromium 侧卡住时不能让调用方无界等待。 */
+const SYSTEM_PROXY_RESOLVE_TIMEOUT_MS = 2000;
+/**
+ * 解析超时后按直连缓存的时长。必须写缓存(而不是什么都不写):否则每个请求都会再发一次
+ * resolveProxy,把已经卡住的解析路径打爆(IPC / Promise 堆积)。TTL 取短值,让代理软件
+ * 恢复后几秒内自动回到正常判定。
+ */
+const SYSTEM_PROXY_TIMEOUT_CACHE_TTL_MS = 5000;
+
+/** 给 resolveProxy 套超时:超时返回 null 并告知调用方这是超时(用于短 TTL 缓存)。 */
+async function resolveProxyWithTimeout(
+ ses: { resolveProxy(url: string): Promise<string> },
+ upstreamUrl: string,
+): Promise<{ value: string | null; timedOut: boolean }> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ try {
+ return await Promise.race<{ value: string | null; timedOut: boolean }>([
+ ses.resolveProxy(upstreamUrl).then((result) => ({
+ value: parseChromiumProxyResult(result),
+ timedOut: false,
+ })),
+ new Promise<{ value: string | null; timedOut: boolean }>((resolve) => {
+ timer = setTimeout(() => resolve({ value: null, timedOut: true }), SYSTEM_PROXY_RESOLVE_TIMEOUT_MS);
+ timer.unref?.();
+ }),
+ ]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
}
async function resolveViaSystemProxy(upstreamUrl: string): Promise<string | null> {
const cached = systemProxyCache.get(upstreamUrl);
if (cached && cached.expiresAt > Date.now()) return cached.value;
+ if (systemProxyCache.size >= SYSTEM_PROXY_CACHE_MAX_ENTRIES) systemProxyCache.clear();
// app 未 ready 时 session 不可用;此时按直连处理(splash 极早期,正常请求不会赶在这)。
if (!app.isReady()) return null;
const ses = session.defaultSession;
if (!ses || typeof ses.resolveProxy !== 'function') return null;
let value: string | null = null;
+ let timedOut = false;
try {
- value = parseChromiumProxyResult(await ses.resolveProxy(upstreamUrl));
+ const resolved = await resolveProxyWithTimeout(ses, upstreamUrl);
+ value = resolved.value;
+ timedOut = resolved.timedOut;
+ if (timedOut) {
+ log.warn('system proxy resolution timed out — using direct connection', {
+ upstream: originForLog(upstreamUrl),
+ timeoutMs: SYSTEM_PROXY_RESOLVE_TIMEOUT_MS,
+ });
+ }
} catch (err) {
log.warn('system proxy resolution failed — using direct connection', {
- upstream: upstreamUrl,
+ upstream: originForLog(upstreamUrl),
err: err instanceof Error ? err.message : String(err),
});
value = null;
}
- systemProxyCache.set(upstreamUrl, { value, expiresAt: Date.now() + SYSTEM_PROXY_CACHE_TTL_MS });
+ // 超时也写缓存,只是 TTL 短得多 —— 否则后续每个请求都会再打一次已经卡住的解析。
+ systemProxyCache.set(upstreamUrl, {
+ value,
+ expiresAt:
+ Date.now() + (timedOut ? SYSTEM_PROXY_TIMEOUT_CACHE_TTL_MS : SYSTEM_PROXY_CACHE_TTL_MS),
+ });
return value;
}
diff --git a/apps/desktop/src/main/maker-host/provider-diagnostics.ts b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
index 9474eccf78..f155ff9e8e 100644
--- a/apps/desktop/src/main/maker-host/provider-diagnostics.ts
+++ b/apps/desktop/src/main/maker-host/provider-diagnostics.ts
@@ -26,6 +26,7 @@ import {
type ProviderErrorCode,
} from '../../shared/providerErrors.js';
import { getActiveCatalog } from './active-catalog.js';
+import { outboundFetch } from './outbound-fetch.js';
/** 探测请求超时。 */
const PROBE_TIMEOUT_MS = 10_000;
@@ -214,7 +215,8 @@ function networkErrorCode(err: unknown): string {
/** 跑一次探测请求并分类结果。fetch 可注入(单测)。 */
export async function runProviderProbe(
spec: ProviderProbeSpec,
- fetchImpl: typeof fetch = fetch,
+ // 默认吃系统代理:探测必须与真实会话同口径,否则代理用户会被误判成「连不通」。
+ fetchImpl: typeof fetch = outboundFetch,
): Promise<ProviderTestResult> {
const { url, init } = buildProbeRequest(spec);
const start = Date.now();
@@ -367,7 +369,7 @@ export function setDiagnosticsOAuthTokenReader(reader: OAuthProbeTokenReader): v
/** 测试入口(IPC handler 消费)。 */
export async function testProviderConnection(
input: ProviderTestInput,
- fetchImpl: typeof fetch = fetch,
+ fetchImpl: typeof fetch = outboundFetch,
): Promise<ProviderTestResult> {
const spec = input.kind === 'saved' ? resolveSavedProbeSpec(input.providerId, input.agent) : input.spec;
return runProviderProbe(spec, fetchImpl);
diff --git a/apps/desktop/src/main/maker-host/provider-model-fetch.ts b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
index 99bb709766..22673b0554 100644
--- a/apps/desktop/src/main/maker-host/provider-model-fetch.ts
+++ b/apps/desktop/src/main/maker-host/provider-model-fetch.ts
@@ -18,6 +18,7 @@ import {
type ProviderErrorCode,
} from '../../shared/providerErrors.js';
import { deriveModelsDiscoveryUrl, parseModelsListResponse } from './generic-oauth.js';
+import { outboundFetch } from './outbound-fetch.js';
/** 拉取超时(与 test-connection 探测同量级)。 */
const FETCH_TIMEOUT_MS = 10_000;
@@ -107,7 +108,7 @@ function networkErrorCode(err: unknown): string {
/** 拉一次模型列表并分类结果。fetch 可注入(单测)。 */
export async function fetchProviderModels(
spec: ProviderModelsFetchSpec,
- fetchImpl: typeof fetch = fetch,
+ fetchImpl: typeof fetch = outboundFetch,
): Promise<ProviderModelsFetchResult> {
const { url, init } = buildModelsFetchRequest(spec);
let res: Response;
diff --git a/apps/desktop/src/main/maker-host/title-one-shot.ts b/apps/desktop/src/main/maker-host/title-one-shot.ts
index 94a436af51..1b7a8d2d15 100644
--- a/apps/desktop/src/main/maker-host/title-one-shot.ts
+++ b/apps/desktop/src/main/maker-host/title-one-shot.ts
@@ -44,6 +44,7 @@ import { getAppCapabilities } from '../appCapabilities.js';
import { getActiveCatalog } from './active-catalog.js';
import { readClaudeApiKey, readCodexOneShotCreds } from './auth-adapters.js';
import { getValidClaudeAiOAuth } from './claude-oauth-refresh.js';
+import { outboundUndiciFetch } from './outbound-fetch.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
const log = createLogger('maker-host:title-one-shot');
@@ -301,7 +302,8 @@ export async function generateTitleViaProvider(
args: { sessionId: string; agentKind: AgentKind; prompt: string; signal?: AbortSignal },
deps: TitleOneShotDeps = {},
): Promise<string | null> {
- const fetchImpl = deps.fetchImpl ?? undiciFetch;
+ // 默认走吃系统代理的 undici fetch:上游可能是境外端点(catalog routing.upstream)。
+ const fetchImpl = deps.fetchImpl ?? outboundUndiciFetch;
const readSessionProviderId = deps.readSessionProviderId ?? (async () => null);
const listConnectedProviders = deps.listConnectedProviders ?? (async () => []);
const readCodexCreds = deps.readCodexCreds ?? readCodexOneShotCreds;
diff --git a/apps/desktop/src/main/mcp-integrations/android.ts b/apps/desktop/src/main/mcp-integrations/android.ts
index c23f9a85af..7dbda8d5b0 100644
--- a/apps/desktop/src/main/mcp-integrations/android.ts
+++ b/apps/desktop/src/main/mcp-integrations/android.ts
@@ -25,6 +25,7 @@ import {
type AndroidAutomationSettings,
} from '../android-automation-settings-store.js';
import { createLogger } from '../logger.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
const logger = createLogger('mcp/cindy_android');
@@ -480,7 +481,8 @@ async function downloadPlatformToolsZip(url: string): Promise<Buffer> {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), platformToolsDownloadTimeoutMs);
try {
- const response = await fetch(url, { signal: controller.signal });
+ // dl.google.com:境外下载,必须吃系统代理(见 maker-host/outbound-fetch.ts)。
+ const response = await outboundFetch(url, { signal: controller.signal });
if (!response.ok) {
throw new AndroidDriverError(
'ANDROID_DRIVER_ERROR',
diff --git a/apps/desktop/src/main/mcp-integrations/computer.ts b/apps/desktop/src/main/mcp-integrations/computer.ts
index 92b5feaac7..9e53958d5c 100644
--- a/apps/desktop/src/main/mcp-integrations/computer.ts
+++ b/apps/desktop/src/main/mcp-integrations/computer.ts
@@ -18,6 +18,7 @@ import type {
ComputerMcpToolName,
} from '@cindy/mcps';
import { createLogger } from '../logger.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
const logger = createLogger('mcp/cindy_computer');
const DRIVER_COMMAND = 'cua-driver';
@@ -2848,7 +2849,8 @@ function startDriverUpdateCheck(fetchImpl: typeof fetch): Promise<Omit<ComputerD
* 进行中不发起刷新(装完缓存会被清)。fetchImpl 可注入用于测试。
*/
export async function checkComputerDriverUpdate(
- fetchImpl: typeof fetch = fetch,
+ // 默认吃系统代理:api.github.com / raw.githubusercontent.com 都是境外端点。
+ fetchImpl: typeof fetch = outboundFetch,
): Promise<ComputerDriverUpdateCheck> {
const updating = driverUpdateInstallInFlight !== null;
if (cachedDriverUpdateCheck) {
@@ -3012,7 +3014,7 @@ export async function updateComputerDriver(
let stopSampler: () => void = () => {};
// preflight + install 立即收进同一个 Promise,避免并发点击各起一轮安装。
driverUpdateInstallInFlight = (async () => {
- const targetVersion = await revalidateComputerDriverUpdateTarget(opts?.fetchImpl ?? fetch);
+ const targetVersion = await revalidateComputerDriverUpdateTarget(opts?.fetchImpl ?? outboundFetch);
if (!targetVersion) {
throw new ComputerDriverError('no verified installable cua-driver update is available');
}
diff --git a/apps/desktop/src/main/usage/claudeAccountUsage.ts b/apps/desktop/src/main/usage/claudeAccountUsage.ts
index 7e3c9b0e87..f675be992d 100644
--- a/apps/desktop/src/main/usage/claudeAccountUsage.ts
+++ b/apps/desktop/src/main/usage/claudeAccountUsage.ts
@@ -44,6 +44,7 @@ import { BrowserWindow } from 'electron';
import { createLogger } from '../logger';
import { readClaudeApiKey } from '../maker-host/auth-adapters';
+import { outboundFetch } from '../maker-host/outbound-fetch';
import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs';
const log = createLogger('claudeAccountUsage');
@@ -116,7 +117,7 @@ async function fetchUserInfo(
signal: AbortSignal,
): Promise<{ spend: number; maxBudget: number; budgetResetAt: string | null } | null> {
try {
- const res = await fetch(`${baseUrl.replace(/\/+$/, '')}/v2/user/info`, {
+ const res = await outboundFetch(`${baseUrl.replace(/\/+$/, '')}/v2/user/info`, {
headers: { Authorization: `Bearer ${apiKey}` },
signal,
});
@@ -148,7 +149,7 @@ async function fetchTodayActivity(
): Promise<LiteLlmDailyActivity | null> {
const today = utcTodayKey();
try {
- const res = await fetch(
+ const res = await outboundFetch(
`${baseUrl.replace(/\/+$/, '')}/user/daily/activity?start_date=${today}&end_date=${today}`,
{ headers: { Authorization: `Bearer ${apiKey}` }, signal },
);
diff --git a/apps/desktop/src/main/utility-model/oneShotCandidates.ts b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
index 527979c098..77cbc08129 100644
--- a/apps/desktop/src/main/utility-model/oneShotCandidates.ts
+++ b/apps/desktop/src/main/utility-model/oneShotCandidates.ts
@@ -1,7 +1,5 @@
import { randomUUID } from 'node:crypto';
-import { fetch as undiciFetch } from 'undici';
-
import { toSdkModelString, type AgentKind, type Maker } from '@cindy/maker-core';
import { appendProviderRequestPath } from '@cindy/model-providers';
@@ -11,6 +9,8 @@ import { getChatgptBridgeAuth } from '../maker-host/anthropic-responses-bridge-h
import { getValidClaudeAiOAuth } from '../maker-host/claude-oauth-refresh.js';
import { getGrokAccessToken } from '../maker-host/grok-oauth-login.js';
import { readCachedGenericOAuthAccessToken } from '../maker-host/generic-oauth.js';
+// undici 的 fetch,但 per-request 现取系统代理(裸 undici 不吃代理设置)。
+import { outboundUndiciFetch as undiciFetch } from '../maker-host/outbound-fetch.js';
import { claudeUpstreamEndpoint } from '../maker-host/runtime-configs.js';
import { getActiveCatalog } from '../maker-host/active-catalog.js';
import { effectiveXdGatewayBaseUrl } from '../model-access/effectiveEndpoint.js';
diff --git a/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts b/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts
index 7f9ad4c8ab..2758aabe7d 100644
--- a/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts
+++ b/apps/desktop/src/main/voice-input/CindyVoiceSessionClient.ts
@@ -2,6 +2,7 @@ import { app } from 'electron';
import * as authManager from '../authManager.js';
import { getClientEndpoint } from '../clientEndpointsService.js';
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { ServerApiError, serverApiFetch } from '../serverApiClient.js';
import { getAppCapabilities, requireAppCapability } from '../appCapabilities.js';
@@ -135,7 +136,7 @@ export class CindyVoiceRunContext {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), VOICE_REFINE_WARMUP_TIMEOUT_MS);
try {
- const response = await fetch(
+ const response = await outboundFetch(
`${baseUrl}/api/voice/sessions/${encodeURIComponent(sessionId)}/refine-warmup`,
{
method: 'POST',
diff --git a/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts b/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts
index 6df1ef523a..9bf7a966d9 100644
--- a/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts
+++ b/apps/desktop/src/main/voice-input/CodexResponsesTextModelClient.ts
@@ -6,7 +6,7 @@ import type { TextModelClient } from '@cindy/voice-input-core';
import { createLogger } from '../logger.js';
import { describeErrorWithCause, markRefinerModelOutputError } from './refinerErrorKind.js';
-import { createRefinerHttpDispatcher } from './refinerHttpDispatcher.js';
+import { createRefinerHttpDispatcher, resolveRefinerDispatcher } from './refinerHttpDispatcher.js';
import { extractJsonStringFieldSnapshot } from './streamingJson.js';
const log = createLogger('voice-input:refine-model');
@@ -57,7 +57,8 @@ export async function prewarmCodexResponsesEndpoint(): Promise<void> {
const response = await undiciFetch(DEFAULT_PREWARM_URL, {
method: 'HEAD',
signal: controller.signal,
- dispatcher: codexResponsesDispatcher,
+ // 预热必须与真实请求同一个池,否则握手白做(代理生效时是代理池)。
+ dispatcher: await resolveRefinerDispatcher(DEFAULT_PREWARM_URL, codexResponsesDispatcher),
});
log.debug('codex responses endpoint prewarmed', { status: response.status });
await response.arrayBuffer().catch(() => undefined);
@@ -208,6 +209,9 @@ export class CodexResponsesTextModelClient implements TextModelClient {
if (timeout) clearTimeout(timeout);
timeout = setTimeout(() => controller.abort(), this.timeoutMs);
};
+ // 代理解析放在看门狗与 timing 起表之前:它是本机一次解析(带 30s 缓存),
+ // 不该算进 response-headers 预算,也不该污染 send 耗时。
+ const dispatcher = await resolveRefinerDispatcher(this.baseUrl, codexResponsesDispatcher);
armIdleTimeout('response headers');
const sendStart = performance.now();
let firstByteAt: number | null = null;
@@ -216,7 +220,7 @@ export class CodexResponsesTextModelClient implements TextModelClient {
const response = await undiciFetch(this.baseUrl, {
method: 'POST',
signal: controller.signal,
- dispatcher: codexResponsesDispatcher,
+ dispatcher,
headers,
body: JSON.stringify(body),
});
diff --git a/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts b/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts
index 3d8e7e44a1..376a550769 100644
--- a/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts
+++ b/apps/desktop/src/main/voice-input/ElevenLabsScribeProvider.ts
@@ -2,6 +2,7 @@ import WebSocket from 'ws';
import type { ClientRequest, IncomingMessage } from 'node:http';
import type { AsrEvent, AsrProvider, AudioTrace } from '@cindy/voice-input-core';
import { createLogger } from '../logger.js';
+import { createOutboundHttpAgent } from '../maker-host/outbound-fetch.js';
import { elevenLabsLanguageCode } from './language.js';
import { mergeRecoveredTranscript } from './transcriptMerge.js';
@@ -95,8 +96,15 @@ export class ElevenLabsScribeProvider implements AsrProvider {
credential: this.apiKey ? 'elevenlabs-api-key' : 'proxy-api-key',
});
+ // agent:`ws` 不吃系统代理,境外 wss 上游在「系统代理」模式下连不上;
+ // 直连时为 undefined,行为与不传一致(见 maker-host/outbound-fetch)。
+ const agent = await createOutboundHttpAgent(url);
+ // 代理解析是一次异步往返,期间用户可能已经松手停录(stop 只置标志、看不到还没
+ // 建出来的 socket)。停了就别再建连,否则留下一条没人回收的 socket。
+ if (this.stopRequested) return;
const socket = new WebSocket(url, {
headers: this.buildHeaders(),
+ agent,
});
this.socket = socket;
diff --git a/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts b/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts
index d393669f0e..336159f98b 100644
--- a/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts
+++ b/apps/desktop/src/main/voice-input/LiteLlmTextModelClient.ts
@@ -7,7 +7,7 @@ import type { TextModelClient } from '@cindy/voice-input-core';
import { createLogger } from '../logger.js';
import { describeErrorWithCause, markRefinerModelOutputError } from './refinerErrorKind.js';
-import { createRefinerHttpDispatcher } from './refinerHttpDispatcher.js';
+import { createRefinerHttpDispatcher, resolveRefinerDispatcher } from './refinerHttpDispatcher.js';
import { extractJsonStringFieldSnapshot } from './streamingJson.js';
const log = createLogger('voice-input:refine-model:litellm');
@@ -42,7 +42,8 @@ export async function prewarmLiteLlmRefinerEndpoint(baseUrl: string): Promise<vo
const response = await undiciFetch(target, {
method: 'HEAD',
signal: controller.signal,
- dispatcher: refinerDispatcher,
+ // 预热必须与真实请求同一个池(代理生效时是代理池),否则握手白做。
+ dispatcher: await resolveRefinerDispatcher(target, refinerDispatcher),
});
log.debug('litellm refiner endpoint prewarmed', { status: response.status });
await response.arrayBuffer().catch(() => undefined);
@@ -164,11 +165,14 @@ export class LiteLlmTextModelClient implements TextModelClient {
url: joinProxyPath(this.baseUrl!, '/v1/chat/completions'),
authorization: `Bearer ${this.proxyApiKey!}`,
};
+ // 代理解析放在看门狗起表之前:它是本机一次解析(带 30s 缓存),不该占用
+ // response-headers 的等待预算。
+ const dispatcher = await resolveRefinerDispatcher(target.url, refinerDispatcher);
armIdleTimeout('response headers');
return undiciFetch(target.url, {
method: 'POST',
signal: controller.signal,
- dispatcher: refinerDispatcher,
+ dispatcher,
headers: {
Authorization: target.authorization,
'Content-Type': 'application/json',
diff --git a/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts b/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts
index 454f4a552b..51db4e9ba9 100644
--- a/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts
+++ b/apps/desktop/src/main/voice-input/LiteLlmTranscriptionProvider.ts
@@ -1,4 +1,6 @@
import type { AsrEvent, AsrProvider } from '@cindy/voice-input-core';
+
+import { outboundFetch } from '../maker-host/outbound-fetch.js';
import { elevenLabsLanguageCode } from './language.js';
type LiteLlmTranscriptionProviderOptions = {
@@ -104,7 +106,7 @@ export async function transcribeLiteLlmAudioFile(input: LiteLlmAudioFileTranscri
if (language) form.set('language', language);
form.set('file', new Blob([exact], { type: mimeType }), fileName);
- const response = await fetch(joinProxyPath(input.baseUrl, '/v1/audio/transcriptions'), {
+ const response = await outboundFetch(joinProxyPath(input.baseUrl, '/v1/audio/transcriptions'), {
method: 'POST',
headers: {
Authorization: `Bearer ${input.proxyApiKey}`,
diff --git a/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts b/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts
index 89cf153c59..eb48c95666 100644
--- a/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts
+++ b/apps/desktop/src/main/voice-input/RealtimeAsrWebSocketProvider.ts
@@ -3,6 +3,7 @@ import type { ClientRequest, IncomingMessage } from 'node:http';
import type { AsrEvent, AsrProvider, AudioTrace } from '@cindy/voice-input-core';
import type { VoiceInputRealtimeProtocolProfile } from '../../shared/voiceInputAsrProfiles.js';
import { createLogger } from '../logger.js';
+import { createOutboundHttpAgent } from '../maker-host/outbound-fetch.js';
import { openAiLanguageCode } from './language.js';
import { describeAsrHandshakeTraceId, describeAsrWebSocketTarget } from './voiceInputAsrConfig.js';
import {
@@ -336,9 +337,16 @@ function createWarmRealtimeSession(
if (!accessToken) return;
if (generation !== warmRealtimeSessionGeneration) return;
+ // `ws` 不吃系统代理;直连时 agent 为 undefined,行为与不传一致。
+ const wsAgent = await createOutboundHttpAgent(connection.realtimeUrl);
+ // 代理解析是一次异步往返,期间预热世代可能已经翻篇(用户开录 / 换配置),
+ // 那就别再建这条预热连接 —— 它不会被任何人回收。
+ if (generation !== warmRealtimeSessionGeneration) return;
+
await new Promise<void>((resolve, reject) => {
const socket = new WebSocket(connection.realtimeUrl, {
headers: realtimeHeaders(accessToken, connection.extraHeaders),
+ agent: wsAgent,
});
let settled = false;
let keepAliveTimer: ReturnType<typeof setInterval> | undefined;
@@ -754,8 +762,12 @@ export class RealtimeAsrWebSocketProvider implements AsrProvider {
return;
}
+ const wsAgent = await createOutboundHttpAgent(realtimeUrl);
+ // 代理解析期间可能已停录:复查后再建连,不留没人回收的 socket。
+ if (this.stopRequested) throw new Error('Realtime ASR connection stopped.');
const socket = new WebSocket(realtimeUrl, {
headers: realtimeHeaders(accessToken, this.extraHeaders),
+ agent: wsAgent,
});
this.socket = socket;
this.attachSocketHandlers(socket);
diff --git a/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts b/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts
index e19cfbd44c..8ca5993797 100644
--- a/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts
+++ b/apps/desktop/src/main/voice-input/VolcengineSaucAsrProvider.ts
@@ -3,6 +3,7 @@ import { gzipSync, gunzipSync } from 'node:zlib';
import type { ClientRequest, IncomingMessage } from 'node:http';
import type { AsrEvent, AsrProvider, AudioTrace } from '@cindy/voice-input-core';
import { createLogger } from '../logger.js';
+import { createOutboundHttpAgent } from '../maker-host/outbound-fetch.js';
import { resamplePcm16 } from './RealtimeAsrWebSocketProvider.js';
import { mergeRecoveredTranscript } from './transcriptMerge.js';
import { describeAsrHandshakeTraceId, describeAsrWebSocketTarget } from './voiceInputAsrConfig.js';
@@ -136,12 +137,17 @@ export class VolcengineSaucAsrProvider implements AsrProvider {
authorizationToken: this.proxyApiKey!,
};
if (this.stopRequested) throw new Error('Volcengine SAUC ASR connection stopped.');
+ // `ws` 不吃系统代理;直连时为 undefined,行为与不传一致。
+ const agent = await createOutboundHttpAgent(connection.websocketUrl);
+ // 解析代理是一次异步往返,期间可能已停录 —— 复查后再建连,不留孤儿 socket。
+ if (this.stopRequested) throw new Error('Volcengine SAUC ASR connection stopped.');
const socket = new WebSocket(connection.websocketUrl, {
headers: {
Authorization: `Bearer ${connection.authorizationToken}`,
'X-Api-Resource-Id': this.resourceId,
'X-Api-Connect-Id': buildConnectId(),
},
+ agent,
});
this.socket = socket;
this.attachSocketHandlers(socket);
diff --git a/apps/desktop/src/main/voice-input/refinerHttpDispatcher.ts b/apps/desktop/src/main/voice-input/refinerHttpDispatcher.ts
index 07d2ce5453..9687451cd4 100644
--- a/apps/desktop/src/main/voice-input/refinerHttpDispatcher.ts
+++ b/apps/desktop/src/main/voice-input/refinerHttpDispatcher.ts
@@ -1,6 +1,7 @@
-import { Agent } from 'undici';
+import { Agent, type Dispatcher } from 'undici';
import { createLogger } from '../logger.js';
+import { resolveOutboundDispatcher } from '../maker-host/outbound-fetch.js';
const log = createLogger('voice-input:refine-dispatcher');
@@ -50,15 +51,32 @@ export function resolveRefinerHttpDispatcherOptions(
* being misclassified as unreachable.
*/
export function createRefinerHttpDispatcher(): Agent {
- const options = resolveRefinerHttpDispatcherOptions();
- return new Agent({
+ return new Agent(refinerAgentOptions(resolveRefinerHttpDispatcherOptions()));
+}
+
+/** 上面两种池共用的 undici Agent 配置(直连池与代理池同调优)。 */
+function refinerAgentOptions(options: RefinerHttpDispatcherOptions): Agent.Options {
+ return {
keepAliveTimeout: options.keepAliveMs,
keepAliveMaxTimeout: 600_000,
connections: 4,
connect: {
autoSelectFamilyAttemptTimeout: options.connectAttemptTimeoutMs,
},
+ };
+}
+
+/**
+ * 取本次请求该用的池:系统代理生效时给一个同调优的代理池(见
+ * `maker-host/outbound-fetch.ts` —— 裸 undici 不吃系统代理,`chatgpt.com` 这类境外
+ * refiner 上游在「系统代理」模式下会直连失败),否则原样用调用方的直连池。
+ */
+export async function resolveRefinerDispatcher(url: string, direct: Agent): Promise<Dispatcher> {
+ const resolved = await resolveOutboundDispatcher(url, {
+ fallback: direct,
+ agentOptions: refinerAgentOptions(resolveRefinerHttpDispatcherOptions()),
});
+ return resolved ?? direct;
}
function readPositiveIntegerEnv(
diff --git a/packages/anthropic-compat-proxy/src/index.ts b/packages/anthropic-compat-proxy/src/index.ts
index e91c696516..06d9ebff80 100644
--- a/packages/anthropic-compat-proxy/src/index.ts
+++ b/packages/anthropic-compat-proxy/src/index.ts
@@ -17,8 +17,11 @@ export { createAnthropicCompatProxy } from './server.js';
export {
createEnvOutboundProxyResolver,
hasProxyEnvConfig,
+ isLoopbackHostname,
parseOutboundProxyUrl,
redactProxyUrlForLog,
+ stripIpv6Brackets,
+ TunnelingHttpsAgent,
} from './outbound-proxy.js';
export type {
OutboundProxyAgent,
diff --git a/packages/anthropic-responses-bridge/src/handler.ts b/packages/anthropic-responses-bridge/src/handler.ts
index 0cb6be7958..620f821536 100644
--- a/packages/anthropic-responses-bridge/src/handler.ts
+++ b/packages/anthropic-responses-bridge/src/handler.ts
@@ -164,6 +164,13 @@ export interface ResponsesHandlerOptions {
/** 供应商配置列表(按 model 前缀路由)。前缀需互不为前缀关系,避免歧义。 */
providers: BridgeProviderConfig[];
logger?: BridgeLogger;
+ /**
+ * 上游 fetch。默认全局 fetch(undici)—— 它**不吃系统代理**,宿主在「系统代理」模式
+ * 下必须注入自己的代理感知实现(desktop 注入 maker-host/outbound-fetch),否则
+ * chatgpt.com / api.x.ai 这类境外上游会裸直连失败。形态与
+ * responses-chat-bridge 的同名选项一致。
+ */
+ fetchImpl?: typeof fetch;
}
// 去尾部斜杠。不用 /\/+$/ 正则——超长 '/' 串上会 O(n²) 回溯(CodeQL js/polynomial-redos)。
@@ -186,6 +193,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
}
const providers = opts.providers.map((p) => ({ ...p, upstreamBase: trimTrailingSlashes(p.upstreamBase) }));
const log = opts.logger ?? {};
+ const fetchImpl = opts.fetchImpl ?? fetch;
let reqSeq = 0;
async function handle({ parsedBody, ctx, res, prefs }: BridgeHandleArgs): Promise<void> {
@@ -259,7 +267,7 @@ export function createResponsesHandler(opts: ResponsesHandlerOptions): Responses
let upstream: Response;
try {
- upstream = await fetch(`${provider.upstreamBase}/responses`, {
+ upstream = await fetchImpl(`${provider.upstreamBase}/responses`, {
method: 'POST',
headers: {
...providerHeaders,
diff --git a/packages/device-link/src/__tests__/client.test.ts b/packages/device-link/src/__tests__/client.test.ts
index 5db7361071..063fe21876 100644
--- a/packages/device-link/src/__tests__/client.test.ts
+++ b/packages/device-link/src/__tests__/client.test.ts
@@ -598,6 +598,77 @@ describe('DeviceLinkClient', () => {
client.stop();
});
+ it('异步 WsFactory:resolve 时世代已变 → 关掉孤儿 socket 且不挂到 client 上', async () => {
+ const sockets: FakeWs[] = [];
+ let release!: (ws: WsLike) => void;
+ const client = new DeviceLinkClient({
+ getWsUrl: () => 'ws://test/api/device-link/ws',
+ getToken: async () => 'jwt-token',
+ getHello: () => ({
+ deviceName: 'Test Mac',
+ platform: 'darwin',
+ appVersion: '1.0.0',
+ remoteControlEnabled: true,
+ busy: false,
+ }),
+ // 首轮工厂悬挂(模拟解析代理 agent 的异步往返),由测试决定何时 resolve。
+ createWebSocket: () =>
+ new Promise<WsLike>((resolve) => {
+ release = resolve;
+ }),
+ timing: { reconnectBaseMs: 5, reconnectMaxMs: 40 },
+ });
+ client.start();
+ await tick();
+ // 工厂还没 resolve 时先 stop:世代作废
+ client.stop();
+ const orphan = new FakeWs();
+ sockets.push(orphan);
+ release(orphan);
+ await tick();
+ // 孤儿被关掉,且不会成为 client 的当前连接(stop 后状态恒为 stopped)
+ expect(orphan.closed).not.toBeNull();
+ expect(client.getStatus()).toBe('stopped');
+ });
+
+ it('异步 WsFactory:过期的 reject 被忽略,不改状态也不排重连', async () => {
+ const statuses: string[] = [];
+ let rejectFirst!: (err: Error) => void;
+ let factoryCalls = 0;
+ const client = new DeviceLinkClient({
+ getWsUrl: () => 'ws://test/api/device-link/ws',
+ getToken: async () => 'jwt-token',
+ getHello: () => ({
+ deviceName: 'Test Mac',
+ platform: 'darwin',
+ appVersion: '1.0.0',
+ remoteControlEnabled: true,
+ busy: false,
+ }),
+ createWebSocket: () => {
+ factoryCalls += 1;
+ if (factoryCalls === 1) {
+ return new Promise<WsLike>((_resolve, reject) => {
+ rejectFirst = reject;
+ });
+ }
+ return new FakeWs();
+ },
+ timing: { reconnectBaseMs: 5, reconnectMaxMs: 40 },
+ });
+ client.onStatusChange((s) => statuses.push(s));
+ client.start();
+ await tick();
+ // 第一轮工厂还悬着时 stop:该轮世代已作废
+ client.stop();
+ statuses.length = 0;
+ rejectFirst(new Error('proxy agent unavailable'));
+ await tick(20);
+ // 过期失败既不改状态,也不排重连(不会有第二个 socket / 新的 connecting)
+ expect(statuses).toEqual([]);
+ expect(factoryCalls).toBe(1);
+ });
+
it('握手超时(open 后 hello-ack 一直不来)→ 强制断开走退避重连', async () => {
const h = makeHarness({ timing: { handshakeTimeoutMs: 15, reconnectBaseMs: 5, reconnectMaxMs: 40 } });
h.client.start();
diff --git a/packages/device-link/src/client.ts b/packages/device-link/src/client.ts
index bfbe9e53a0..ddd0a7664d 100644
--- a/packages/device-link/src/client.ts
+++ b/packages/device-link/src/client.ts
@@ -75,8 +75,14 @@ export interface WsLike {
on(event: 'error', cb: (err: Error) => void): void;
}
-/** 创建一条带鉴权 header 的 ws 连接 */
-export type WsFactory = (url: string, headers: Record<string, string>) => WsLike;
+/**
+ * 创建一条带鉴权 header 的 ws 连接。允许返回 Promise —— host 建连前可能要先做异步
+ * 准备(如 desktop 现取系统代理拿 http agent)。
+ */
+export type WsFactory = (
+ url: string,
+ headers: Record<string, string>,
+) => WsLike | Promise<WsLike>;
export interface DeviceLinkLogger {
debug(...args: unknown[]): void;
@@ -584,14 +590,36 @@ export class DeviceLinkClient {
let ws: WsLike;
try {
- ws = this.opts.createWebSocket(this.opts.getWsUrl(), {
+ ws = await this.opts.createWebSocket(this.opts.getWsUrl(), {
authorization: `Bearer ${token}`,
});
} catch (err) {
+ // 异步工厂可能在更新的一轮 connect 已经起来之后才 reject —— 那是过期尝试的失败,
+ // 不能据此改状态或排重连(scheduleReconnect 的 connect() 会顶掉那条更新的、
+ // 可能健康的连接)。与工厂成功分支用同一道 stopped/epoch 闸(review 2026-07-27 P1)。
+ if (this.stopped || epoch !== this.connEpoch) {
+ this.log.debug?.('stale createWebSocket rejection ignored', err);
+ return;
+ }
this.log.warn('createWebSocket failed', err);
this.scheduleReconnect();
return;
}
+ // 工厂可能是异步的(host 建连前要准备代理 agent 等):期间可能已 stop 或换了
+ // 连接世代 —— 那这条 socket 是孤儿,关掉再退,别挂到 this.ws 上。
+ if (this.stopped || epoch !== this.connEpoch) {
+ try {
+ // 必须先挂 error 监听再 close:孤儿 socket 大概率还在 CONNECTING,close() 会让
+ // ws 异步 emit 'error'(如 "WebSocket was closed before the connection was
+ // established"),而 EventEmitter 对无监听的 'error' 是直接抛 —— 那会变成主进程
+ // 的未捕获异常(review 2026-07-27 P1)。
+ ws.on('error', () => {});
+ ws.close();
+ } catch (err) {
+ this.log.debug?.('closing orphan websocket failed', err);
+ }
+ return;
+ }
this.ws = ws;
this.armHandshakeTimeout(epoch);
diff --git a/packages/github-client/src/client.ts b/packages/github-client/src/client.ts
index cdbbf6b218..734e4c8c85 100644
--- a/packages/github-client/src/client.ts
+++ b/packages/github-client/src/client.ts
@@ -1,8 +1,9 @@
/**
* GitHub REST API v3 客户端。
*
- * 零外部依赖 — 仅使用全局 fetch(Node 18+ / Electron 28+)。
- * 所有方法均可在 main / server 进程直接调用。
+ * 零外部依赖 — 默认用全局 fetch(Node 18+ / Electron 28+),也可经
+ * `GithubClientConfig.fetchImpl` 注入自己的实现(desktop 注入代理感知 fetch:Node /
+ * Electron 主进程下的全局 fetch 是 undici,不读系统代理)。所有方法均可在 main / server 进程直接调用。
*
* 与 @cindy/gitlab-client 接口形状对齐,差异点:
* - GitHub 用 `number` 标识 issue/PR(GitLab 是 `iid`)
@@ -120,6 +121,8 @@ export class GithubClient {
* 见 https://docs.github.com/en/enterprise-server/graphql/guides
*/
private readonly graphqlUrl: string;
+ /** 出网通道(见 GithubClientConfig.fetchImpl)。 */
+ private readonly fetchImpl: typeof fetch;
constructor(config: GithubClientConfig) {
this.baseUrl = trimTrailingSlashes(config.baseUrl ?? DEFAULT_BASE_URL);
@@ -136,6 +139,7 @@ export class GithubClient {
// GHE 的 baseUrl 末尾是 '/api/v3',把它剥掉换成 '/api' 后拼 '/graphql'。
// github.com 的 baseUrl 是 'https://api.github.com',正则不匹配,直接拼 '/graphql'。
this.graphqlUrl = `${this.baseUrl.replace(/\/api\/v3$/, '/api')}/graphql`;
+ this.fetchImpl = config.fetchImpl ?? fetch;
}
/** Return the encoded repo path or fail fast when the caller invoked a
@@ -639,7 +643,7 @@ export class GithubClient {
'X-GitHub-Api-Version': '2022-11-28',
},
body: JSON.stringify({ query, variables }),
- });
+ }, undefined, this.fetchImpl);
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new GithubApiError(
@@ -1749,7 +1753,7 @@ export class GithubClient {
}
// 认证请求禁止自动跟随跨 host 重定向:Authorization token 绝不重放到另一个 host。
- const res = await fetchWithSafeRedirect(url, init);
+ const res = await fetchWithSafeRedirect(url, init, undefined, this.fetchImpl);
if (!res.ok) {
const text = await res.text().catch(() => '');
@@ -1782,7 +1786,7 @@ export class GithubClient {
*/
private async requestRedirectUrl(method: string, path: string): Promise<string | null> {
const url = `${this.baseUrl}${path}`;
- const res = await fetch(url, {
+ const res = await this.fetchImpl(url, {
method,
redirect: 'manual',
headers: {
diff --git a/packages/github-client/src/http-safety.ts b/packages/github-client/src/http-safety.ts
index dbc0d3f300..ad35716b62 100644
--- a/packages/github-client/src/http-safety.ts
+++ b/packages/github-client/src/http-safety.ts
@@ -85,12 +85,14 @@ export async function fetchWithSafeRedirect(
url: string,
init: RequestInit,
maxRedirects = MAX_REDIRECTS,
+ /** 出网通道。宿主可注入(如 desktop 的代理感知 fetch);缺省 = 全局 fetch。 */
+ fetchImpl: typeof fetch = fetch,
): Promise<Response> {
const { origin, host, protocol } = new URL(url);
let current = url;
let lastStatus = 0;
for (let hop = 0; hop <= maxRedirects; hop++) {
- const res = await fetch(current, { ...init, redirect: 'manual' });
+ const res = await fetchImpl(current, { ...init, redirect: 'manual' });
// 只有 3xx 才走重定向分支;其余(含 2xx / 4xx / 5xx)交回调用方原有逻辑处理。
if (res.status < 300 || res.status >= 400) return res;
lastStatus = res.status;
diff --git a/packages/github-client/src/types.ts b/packages/github-client/src/types.ts
index 49f26b8f0e..e029bb1c5c 100644
--- a/packages/github-client/src/types.ts
+++ b/packages/github-client/src/types.ts
@@ -9,6 +9,12 @@ export interface GithubClientConfig {
owner?: string;
/** 仓库名,如 'cindy'。user-scope / search / cross-repo 调用可省略。 */
repo?: string;
+ /**
+ * 出网通道。缺省 = 全局 fetch —— 在 **Node / Electron 主进程**下那是 undici,不读系统
+ * 代理设置也不读代理环境变量,所以代理网络下的宿主应注入自己的代理感知实现
+ * (desktop 注入 main/maker-host/outbound-fetch)。
+ */
+ fetchImpl?: typeof fetch;
}
export interface GithubUser {
diff --git a/packages/gitlab-client/src/client.ts b/packages/gitlab-client/src/client.ts
index e897e2f2e0..a4275190aa 100644
--- a/packages/gitlab-client/src/client.ts
+++ b/packages/gitlab-client/src/client.ts
@@ -1,8 +1,9 @@
/**
* GitLab REST API v4 客户端。
*
- * 零外部依赖 — 仅使用全局 fetch(Node 18+ / Electron 28+)。
- * 所有方法均可在 main 进程直接调用。
+ * 零外部依赖 — 默认用全局 fetch(Node 18+ / Electron 28+),也可经
+ * `GitlabClientConfig.fetchImpl` 注入自己的实现(desktop 注入代理感知 fetch:Node /
+ * Electron 主进程下的全局 fetch 是 undici,不读系统代理)。所有方法均可在 main 进程直接调用。
*/
import type {
@@ -95,6 +96,8 @@ export class GitlabClient {
* (cross-project / user-scope calls). Project-scoped methods route through
* {@link requireProject} which throws a clear error in that case. */
private readonly projectId: string | null;
+ /** 出网通道(见 GitlabClientConfig.fetchImpl)。 */
+ private readonly fetchImpl: typeof fetch;
constructor(config: GitlabClientConfig) {
this.baseUrl = trimTrailingSlashes(config.baseUrl);
@@ -105,6 +108,7 @@ export class GitlabClient {
this.projectId = config.projectPath
? encodeURIComponent(config.projectPath)
: null;
+ this.fetchImpl = config.fetchImpl ?? fetch;
}
/** Return the encoded project id or fail fast when the caller invoked a
@@ -1281,7 +1285,7 @@ export class GitlabClient {
});
form.append('file', blob, params.filename);
- const res = await fetch(url, {
+ const res = await this.fetchImpl(url, {
method: 'POST',
headers: { 'PRIVATE-TOKEN': this.token },
body: form,
@@ -1331,7 +1335,7 @@ export class GitlabClient {
}
// 认证请求禁止自动跟随跨 host 重定向:PRIVATE-TOKEN 绝不重放到另一个 host。
- const res = await fetchWithSafeRedirect(url, init);
+ const res = await fetchWithSafeRedirect(url, init, undefined, this.fetchImpl);
// 304 Not Modified 对幂等写端点(如 POST /projects/:id/star 已 star / unstar
// 未 star)是"操作 no-op、状态和目标一致"的成功语义,GitLab 不返 body。
@@ -1365,7 +1369,7 @@ export class GitlabClient {
const res = await fetchWithSafeRedirect(url, {
method,
headers: { 'PRIVATE-TOKEN': this.token },
- });
+ }, undefined, this.fetchImpl);
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new GitlabApiError(
diff --git a/packages/gitlab-client/src/http-safety.ts b/packages/gitlab-client/src/http-safety.ts
index e6d5b3edcf..96bd9f6bd2 100644
--- a/packages/gitlab-client/src/http-safety.ts
+++ b/packages/gitlab-client/src/http-safety.ts
@@ -83,12 +83,14 @@ export async function fetchWithSafeRedirect(
url: string,
init: RequestInit,
maxRedirects = MAX_REDIRECTS,
+ /** 出网通道。宿主可注入(如 desktop 的代理感知 fetch);缺省 = 全局 fetch。 */
+ fetchImpl: typeof fetch = fetch,
): Promise<Response> {
const { origin, host } = new URL(url);
let current = url;
let lastStatus = 0;
for (let hop = 0; hop <= maxRedirects; hop++) {
- const res = await fetch(current, { ...init, redirect: 'manual' });
+ const res = await fetchImpl(current, { ...init, redirect: 'manual' });
// 只有 3xx 才走重定向分支;其余(含 2xx / 4xx / 5xx)交回调用方原有逻辑处理。
if (res.status < 300 || res.status >= 400) return res;
lastStatus = res.status;
diff --git a/packages/gitlab-client/src/types.ts b/packages/gitlab-client/src/types.ts
index e27f6ad947..b14d4f9bf9 100644
--- a/packages/gitlab-client/src/types.ts
+++ b/packages/gitlab-client/src/types.ts
@@ -22,6 +22,12 @@ export interface GitlabClientConfig {
token: string;
/** 项目路径,如 'group/project'。cross-project / user-scope 调用可省略。 */
projectPath?: string;
+ /**
+ * 出网通道。缺省 = 全局 fetch —— 在 **Node / Electron 主进程**下那是 undici,不读系统
+ * 代理设置也不读代理环境变量,所以代理网络下的宿主应注入自己的代理感知实现
+ * (desktop 注入 main/maker-host/outbound-fetch)。
+ */
+ fetchImpl?: typeof fetch;
}
export interface GitlabUser {
diff --git a/packages/heartbeat-client/src/client.ts b/packages/heartbeat-client/src/client.ts
index bdba448100..6c756488cb 100644
--- a/packages/heartbeat-client/src/client.ts
+++ b/packages/heartbeat-client/src/client.ts
@@ -14,12 +14,14 @@ import type {
* - host.getUid() 返回 null 时跳过本次 tick (不算失败),适用于登录态切换间隙
* - 没有 schedule jitter / no backoff / no retry —— 反正下一个 tick 还会再来,
* 重试只会浪费电
- * - 不依赖 Electron / Node 子系统,仅用 globalThis.fetch + AbortSignal.timeout
+ * - 不依赖 Electron / Node 子系统,仅用注入的 fetchImpl(缺省 globalThis.fetch)
+ * + AbortSignal.timeout
*
* 调用方负责生命周期 (stop()) 与 uid 来源切换 (通过 getUid 动态返回不同 id)。
*/
export function createHeartbeatClient(opts: HeartbeatClientOptions): HeartbeatHandle {
const timeoutMs = opts.timeoutMs ?? 5_000;
+ const fetchImpl = opts.fetchImpl ?? fetch;
const log = opts.host.logger;
const url = trimTrailingSlash(opts.endpoint) + '/heartbeat';
@@ -46,7 +48,7 @@ export function createHeartbeatClient(opts: HeartbeatClientOptions): HeartbeatHa
}
try {
- const res = await fetch(url, {
+ const res = await fetchImpl(url, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
diff --git a/packages/heartbeat-client/src/types.ts b/packages/heartbeat-client/src/types.ts
index 9af92d8be4..a4fc6f9bf4 100644
--- a/packages/heartbeat-client/src/types.ts
+++ b/packages/heartbeat-client/src/types.ts
@@ -60,6 +60,13 @@ export interface HeartbeatClientOptions {
* 适合复用 heartbeat 的节拍做本地轻量任务,但回调异常不会中断心跳上报。
*/
onTick?: (payload: HeartbeatTickPayload) => void;
+ /**
+ * 出网通道。缺省 = `globalThis.fetch`。注意 **Node / Electron 主进程**下它是 undici,
+ * 不读系统代理设置也不读代理环境变量;需要经代理出网的宿主要注入自己的实现
+ * (desktop 注入 main/maker-host/outbound-fetch)。浏览器环境不受此影响 —— 那里的
+ * fetch 走浏览器网络栈,系统代理天然生效。
+ */
+ fetchImpl?: typeof fetch;
}
/** start() 返回的句柄,允许停止与状态查询。 */