Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): preserve proxy address failover
liugaowei4446f3079642
diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.tsindex 66ccea8c73..be82567c3e 100644--- a/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/outboundFetch.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { Agent as UndiciAgent, ProxyAgent } from 'undici';+import { Agent as UndiciAgent, Dispatcher, ProxyAgent } from 'undici';import { Socks5HttpsAgent, TunnelingHttpsAgent } from '@cindy/anthropic-compat-proxy';@@ -53,6 +53,7 @@ vi.mock('undici', async (importOriginal) => {import {createOutboundHttpAgent,+ createPinnedProxyDispatcher,guardedOutboundFetch,outboundFetch,outboundUndiciFetch,@@ -314,6 +315,53 @@ describe('outboundFetch', () => {]);});+ it('fails over between vetted proxy targets only before the request starts', async () => {+ const dispatchSpy = vi.spyOn(ProxyAgent.prototype, 'dispatch');+ const controller = {} as Dispatcher.DispatchController;+ const responseError = vi.fn();+ try {+ dispatchSpy+ .mockImplementationOnce((_options, handler) => {+ handler.onResponseError?.(controller, new Error('first address unreachable'));+ return true;+ })+ .mockImplementationOnce((_options, handler) => {+ handler.onRequestStart?.(controller, null);+ handler.onResponseError?.(controller, new Error('request failed after start'));+ return true;+ });+ const dispatcher = createPinnedProxyDispatcher(+ {+ kind: 'http',+ url: 'http://127.0.0.1:7890',+ hostname: '127.0.0.1',+ port: 7890,+ },+ new URL('https://api.example.com/data'),+ ['203.0.113.10', '203.0.113.11'],+ );++ dispatcher.dispatch(+ { origin: 'https://api.example.com', path: '/data', method: 'POST', body: 'payload' },+ { onRequestStart: vi.fn(), onResponseError: responseError },+ );++ expect(dispatchSpy).toHaveBeenCalledTimes(2);+ expect(dispatchSpy.mock.calls.map(([options]) => options.origin)).toEqual([+ 'https://203.0.113.10',+ 'https://203.0.113.11',+ ]);+ expect(responseError).toHaveBeenCalledTimes(1);+ expect(responseError).toHaveBeenCalledWith(+ controller,+ expect.objectContaining({ message: 'request failed after start' }),+ );+ await dispatcher.close();+ } finally {+ dispatchSpy.mockRestore();+ }+ });+it.each(['http://127.0.0.1:7890','socks5://127.0.0.1:7891',diff --git a/apps/desktop/src/main/maker-host/outbound-fetch.ts b/apps/desktop/src/main/maker-host/outbound-fetch.tsindex bb65cb4fc0..aed0ea88db 100644--- a/apps/desktop/src/main/maker-host/outbound-fetch.ts+++ b/apps/desktop/src/main/maker-host/outbound-fetch.ts@@ -490,13 +490,13 @@ export function rewritePinnedProxyDispatchOptions(* rebinding 窗口。包装层把下游连接目标改成已审核 IP,同时保留原始 Host 与 TLS SNI。* dispatcher 为单次请求所有,响应消费完由 SSRF shell 统一关闭。*/-function createPinnedProxyDispatcher(+/** @internal 导出供安全回归测试断言多地址故障转移只发生在请求发出前。 */+export function createPinnedProxyDispatcher(proxy: OutboundProxyTarget,upstream: URL,addresses: readonly string[],): Dispatcher {- const address = addresses[0];- if (!address) throw new Error(`Unable to resolve hostname: ${upstream.hostname}`);+ if (addresses.length === 0) throw new Error(`Unable to resolve hostname: ${upstream.hostname}`);const base = createProxyDispatcher(proxy,upstreamProtocol(upstream),@@ -508,7 +508,67 @@ function createPinnedProxyDispatcher(options: Dispatcher.DispatchOptions,handler: Dispatcher.DispatchHandler,): boolean {- return base.dispatch(rewritePinnedProxyDispatchOptions(options, upstream, address), handler);+ const dispatchFrom = (startIndex: number): boolean => {+ let lastError: unknown;+ for (let index = startIndex; index < addresses.length; index += 1) {+ const address = addresses[index]!;+ let requestStarted = false;+ const attemptHandler: Dispatcher.DispatchHandler = {+ onRequestStart(controller, context) {+ requestStarted = true;+ handler.onRequestStart?.(controller, context);+ },+ onRequestUpgrade(controller, statusCode, headers, socket) {+ handler.onRequestUpgrade?.(controller, statusCode, headers, socket);+ },+ onResponseStart(controller, statusCode, headers, statusMessage) {+ handler.onResponseStart?.(controller, statusCode, headers, statusMessage);+ },+ onResponseData(controller, chunk) {+ handler.onResponseData?.(controller, chunk);+ },+ onResponseEnd(controller, trailers) {+ handler.onResponseEnd?.(controller, trailers);+ },+ onResponseError(controller, error) {+ // HTTPS CONNECT / SOCKS5 握手失败发生在 onRequestStart 之前;一旦请求开始,+ // 就不能为了换 IP 而重放可能产生副作用的 POST。+ if (!requestStarted && !controller.aborted && index + 1 < addresses.length) {+ try {+ dispatchFrom(index + 1);+ } catch (nextError) {+ handler.onResponseError?.(+ controller,+ nextError instanceof Error ? nextError : new Error(String(nextError)),+ );+ }+ return;+ }+ handler.onResponseError?.(controller, error);+ },+ onResponseStarted() {+ handler.onResponseStarted?.();+ },+ onBodySent(chunk) {+ handler.onBodySent?.(chunk);+ },+ onRequestSent() {+ handler.onRequestSent?.();+ },+ };+ try {+ return base.dispatch(+ rewritePinnedProxyDispatchOptions(options, upstream, address),+ attemptHandler,+ );+ } catch (error) {+ lastError = error;+ }+ }+ throw lastError instanceof Error ? lastError : new Error(String(lastError));+ };++ return dispatchFrom(0);}override async close(): Promise<void> {