Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): codex 后端不可达时报实测出站路径,替掉通用猜测清单 (#1000)
Dash603f346724e0
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex babb5e2c86..0d881be5b8 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -117,6 +117,129 @@ async function freshCodexProxyHost() {return import('../codex-proxy-host.js');}+describe('withCodexUpstreamRecording', () => {+ const DEFAULT_UPSTREAM = 'https://gateway.example/v1';+ const ctxFor = (threadId?: string) => ({+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: threadId ? { 'thread-id': threadId } : {},+ }) as never;++ it('records the override upstream origin for the request thread', async () => {+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();+ const wrapped = host.withCodexUpstreamRecording(+ () => ({ upstreamOverride: 'https://api.x.ai/v1' }),+ () => DEFAULT_UPSTREAM,+ );++ await wrapped({}, ctxFor('t-xai'));++ // 诊断必须报本次真正打的上游 —— 会话选了 xAI 就不能报 gateway。+ expect(host.getCodexThreadUpstreamOrigin('t-xai')).toBe('https://api.x.ai');+ // 没记录过的 thread 不借用别人的结论。+ expect(host.getCodexThreadUpstreamOrigin('t-other')).toBe(null);+ });++ it('falls back to the default upstream when the decision does not override it', async () => {+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();+ const wrapped = host.withCodexUpstreamRecording(() => null, () => DEFAULT_UPSTREAM);++ await wrapped({}, ctxFor('t-default'));++ expect(host.getCodexThreadUpstreamOrigin('t-default')).toBe('https://gateway.example');+ });++ it('records through an async decision and returns it unchanged', async () => {+ // chat-bridge 分支返回 Promise;包装层必须同样记录,且不改变 decision。+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();+ const decision = { upstreamOverride: 'https://custom.provider:8443/v1' };+ const wrapped = host.withCodexUpstreamRecording(+ () => Promise.resolve(decision),+ () => DEFAULT_UPSTREAM,+ );++ await expect(wrapped({}, ctxFor('t-async'))).resolves.toBe(decision);+ expect(host.getCodexThreadUpstreamOrigin('t-async')).toBe('https://custom.provider:8443');+ });++ it('does not record for localHandler decisions or thread-less requests', async () => {+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();++ // localHandler 与其余路由字段互斥,不发生上游转发 → 没有出口可记。+ const local = host.withCodexUpstreamRecording(+ () => ({ localHandler: { handle: async () => undefined } }) as never,+ () => DEFAULT_UPSTREAM,+ );+ await local({}, ctxFor('t-local'));+ expect(host.getCodexThreadUpstreamOrigin('t-local')).toBe(null);++ // 无 thread 的控制面请求(models 轮询)会被 selectedThreadIdFromHeaders 回落成+ // 字面量 'unknown';那不是 thread,不该进桶。+ const plain = host.withCodexUpstreamRecording(() => null, () => DEFAULT_UPSTREAM);+ await plain({}, ctxFor(undefined));+ expect(host.getCodexThreadUpstreamOrigin('unknown')).toBe(null);+ });++ it('records the chat-bridge upstream even though it routes through a localHandler', async () => {+ // localHandler 不等于「不出网」:chat bridge 的 handler 自己用 outboundFetch 打+ // route.routing.upstream,照样产生出站路径快照。漏记会让该供应商不可达时诊断+ // 查不到映射、静默退回通用猜测清单。+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();+ const { buildUserProvider } = await import('@cindy/model-providers');+ const { setCustomProviders } = await import('../active-catalog.js');+ const { setCustomProviderKeyReader } = await import('../provider-route.js');+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ setCustomProviders([+ buildUserProvider({+ id: 'kimi-moonshot',+ name: 'Kimi (Moonshot 中国大陆)',+ runtimes: {+ codex: {+ baseUrl: 'https://api.moonshot.cn/v1',+ wireProtocol: 'openai-chat',+ models: [{ id: 'kimi-k3', name: 'Kimi K3' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'moonshot-key');+ host.registerComposed('session-kimi-diag', 'thread-kimi-diag', 'PRODUCT_PROMPT');+ setSessionProvider('session-kimi-diag', 'kimi-moonshot');+ host.setCodexProxyAuthInjection('env-key');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'kimi-k3' },+ { reqId: 1, method: 'POST', url: '/responses', headers: { 'thread-id': 'thread-kimi-diag' } },+ ));+ expect(decision).toEqual(expect.objectContaining({ localHandler: expect.any(Function) }));+ expect(host.getCodexThreadUpstreamOrigin('thread-kimi-diag')).toBe('https://api.moonshot.cn');+ } finally {+ clearSessionProvider('session-kimi-diag');+ setCustomProviders([]);+ }+ });++ it('never lets a recording failure affect forwarding', async () => {+ // 诊断旁路:默认上游取值抛错也不能影响 decision。+ const host = await freshCodexProxyHost();+ host.resetCodexThreadUpstreamForTest();+ const decision = { upstreamOverride: 'https://api.x.ai/v1' };+ const wrapped = host.withCodexUpstreamRecording(+ () => decision,+ () => { throw new Error('endpoint unavailable'); },+ );++ expect(await wrapped({}, ctxFor('t-boom'))).toBe(decision);+ });+});+describe('codex gateway config', () => {it('oauth-bearer 模式: requires_openai_auth, 不带 env_key', async () => {const { buildCodexProxySpawnArgs } = await import('../codex-gateway-config.js');diff --git a/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.ts b/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.tsindex b5c8cc1483..ba4d4493e3 100644--- a/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/outboundProxyResolver.test.ts@@ -40,11 +40,15 @@ vi.mock('electron', async (importOriginal) => {});import {+ getOutboundPathSnapshotFor,parseChromiumProxyResult,resetOutboundProxyResolverStateForTest,resolveDesktopOutboundProxy,} from '../outbound-proxy-resolver.js';+/** 单 origin 查询的简写(快照按上游分桶,测试里绝大多数断言只关心一个上游)。 */+const snapshotFor = (origin: string) => getOutboundPathSnapshotFor([origin]);+const PROXY_ENV_KEYS = ['HTTPS_PROXY', 'https_proxy','HTTP_PROXY', 'http_proxy',@@ -77,19 +81,22 @@ afterEach(() => {});describe('parseChromiumProxyResult', () => {+ /** 只关心选中的地址时的简写(verdict 的另一半 skippedUnsupported 另有专门用例)。 */+ const urlOf = (result: string) => parseChromiumProxyResult(result).url;+it('parses PROXY entries into http urls', () => {- expect(parseChromiumProxyResult('PROXY 127.0.0.1:7890')).toBe('http://127.0.0.1:7890');+ expect(urlOf('PROXY 127.0.0.1:7890')).toBe('http://127.0.0.1:7890');});it('returns null for DIRECT', () => {- expect(parseChromiumProxyResult('DIRECT')).toBe(null);+ expect(urlOf('DIRECT')).toBe(null);});it('uses SOCKS5 when it is the only usable candidate', () => {- expect(parseChromiumProxyResult('SOCKS5 127.0.0.1:7891')).toBe('socks5://127.0.0.1:7891');+ expect(urlOf('SOCKS5 127.0.0.1:7891')).toBe('socks5://127.0.0.1:7891');// 「代理软件只开 SOCKS 出口」的典型形态 —— 此时直连会因本机解不出上游而 ENOTFOUND。- expect(parseChromiumProxyResult('SOCKS5 127.0.0.1:7891; DIRECT')).toBe('socks5://127.0.0.1:7891');- expect(parseChromiumProxyResult('HTTPS secure.proxy:443; SOCKS5 127.0.0.1:7891'))+ expect(urlOf('SOCKS5 127.0.0.1:7891; DIRECT')).toBe('socks5://127.0.0.1:7891');+ expect(urlOf('HTTPS secure.proxy:443; SOCKS5 127.0.0.1:7891')).toBe('socks5://127.0.0.1:7891');});@@ -97,27 +104,53 @@ describe('parseChromiumProxyResult', () => {// 回归防护:resolver 只能给一个结果,选中的条目连不上就是失败、不会退到下一个。// 支持 SOCKS5 之前这两串都选 PROXY(SOCKS5 条目被跳过);若改成选 SOCKS5,// 该端点一挂就成 502,凭空多出一种原来不存在的失败模式。- expect(parseChromiumProxyResult('SOCKS5 127.0.0.1:7891; PROXY 127.0.0.1:7890; DIRECT'))+ expect(urlOf('SOCKS5 127.0.0.1:7891; PROXY 127.0.0.1:7890; DIRECT')).toBe('http://127.0.0.1:7890');- expect(parseChromiumProxyResult('PROXY 127.0.0.1:7890; SOCKS5 127.0.0.1:7891'))+ expect(urlOf('PROXY 127.0.0.1:7890; SOCKS5 127.0.0.1:7891')).toBe('http://127.0.0.1:7890');});it('stops at DIRECT and skips unsupported HTTPS/SOCKS(v4) entries', () => {- expect(parseChromiumProxyResult('HTTPS secure.proxy:443; DIRECT')).toBe(null);+ expect(urlOf('HTTPS secure.proxy:443; DIRECT')).toBe(null);// DIRECT 之后的条目不再考虑:PAC 里 DIRECT 意味着「到此为止,直连即可」。- expect(parseChromiumProxyResult('DIRECT; PROXY 127.0.0.1:7890')).toBe(null);- expect(parseChromiumProxyResult('DIRECT; SOCKS5 127.0.0.1:7891')).toBe(null);+ expect(urlOf('DIRECT; PROXY 127.0.0.1:7890')).toBe(null);+ expect(urlOf('DIRECT; SOCKS5 127.0.0.1:7891')).toBe(null);// Chromium 里裸 SOCKS 前缀就是 v4,不支持。- expect(parseChromiumProxyResult('SOCKS 127.0.0.1:1080')).toBe(null);- expect(parseChromiumProxyResult('SOCKS 127.0.0.1:1080; PROXY 127.0.0.1:7890'))+ expect(urlOf('SOCKS 127.0.0.1:1080')).toBe(null);+ expect(urlOf('SOCKS 127.0.0.1:1080; PROXY 127.0.0.1:7890')).toBe('http://127.0.0.1:7890');});+ it('reports whether a configured-but-unusable entry was skipped', () => {+ // 转发行为不受这个标志影响(照旧直连),但诊断必须能区分「系统说没有代理」和+ // 「系统列了代理、Cindy 用不了」—— 后者的动作是把那条改成 HTTP/SOCKS5。+ expect(parseChromiumProxyResult('HTTPS corporate.proxy:443; DIRECT')).toEqual({+ url: null,+ skippedUnsupported: true,+ });+ expect(parseChromiumProxyResult('SOCKS legacy.proxy:1080')).toEqual({+ url: null,+ skippedUnsupported: true,+ });+ // 真 DIRECT / 无条目不算「跳过了不支持的条目」。+ expect(parseChromiumProxyResult('DIRECT')).toEqual({ url: null, skippedUnsupported: false });+ expect(parseChromiumProxyResult('')).toEqual({ url: null, skippedUnsupported: false });+ // 有可用候选时标志不影响结果,但仍如实反映扫描过程。+ expect(parseChromiumProxyResult('HTTPS secure.proxy:443; PROXY 127.0.0.1:7890')).toEqual({+ url: 'http://127.0.0.1:7890',+ skippedUnsupported: true,+ });+ // DIRECT 之前没有不支持条目 → false(DIRECT 之后的一律不看)。+ expect(parseChromiumProxyResult('DIRECT; HTTPS secure.proxy:443')).toEqual({+ url: null,+ skippedUnsupported: false,+ });+ });+it('tolerates malformed input', () => {- expect(parseChromiumProxyResult('')).toBe(null);- expect(parseChromiumProxyResult(';;')).toBe(null);- expect(parseChromiumProxyResult('PROXY')).toBe(null);+ expect(urlOf('')).toBe(null);+ expect(urlOf(';;')).toBe(null);+ expect(urlOf('PROXY')).toBe(null);});});@@ -170,3 +203,230 @@ describe('resolveDesktopOutboundProxy', () => {expect(electronState.resolveProxy).not.toHaveBeenCalled();});});++describe('getOutboundPathSnapshotFor', () => {+ it('is null until a resolution happens', () => {+ expect(snapshotFor('https://chatgpt.com:443')).toBe(null);+ });++ it('keys snapshots by upstream so a shared resolver cannot cross-contaminate', async () => {+ // 回归防护:这个 resolver 由 codex proxy / anthropic-compat proxy / 通用+ // outbound-fetch 共用。曾经存单值槽,最后完成解析的请求会覆盖它 —— 于是+ // codex 的错误消息里可能出现属于 Anthropic 上游的判定。NO_PROXY 逐 origin+ // 生效时两者结论甚至相反(如下:chatgpt 被豁免直连,api.anthropic 走代理)。+ process.env.HTTPS_PROXY = 'http://127.0.0.1:7890';+ process.env.NO_PROXY = 'chatgpt.com';+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ await resolveDesktopOutboundProxy('https://api.anthropic.com:443');++ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({ kind: 'direct', source: 'env' });+ expect(snapshotFor('https://api.anthropic.com:443')).toMatchObject({+ kind: 'proxy',+ proxy: 'http://127.0.0.1:7890',+ });+ // 没解析过的上游不会借用别人的判定。+ expect(snapshotFor('https://api.x.ai:443')).toBe(null);+ });++ it('accepts full base URLs and returns the newest among candidate origins', async () => {+ // 调用方(maker-host)手里是带 path 的 base URL,不归一成 origin 会永远查不中。+ electronState.resolveProxy.mockResolvedValue('PROXY 127.0.0.1:7890');+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(getOutboundPathSnapshotFor(['https://chatgpt.com/backend-api/codex']))+ .toMatchObject({ kind: 'proxy' });++ // 多候选:codex 的出口随凭证模式在 ChatGPT / gateway 间切换,取最新那条。+ vi.useFakeTimers();+ try {+ await vi.advanceTimersByTimeAsync(1_000);+ electronState.resolveProxy.mockResolvedValue('DIRECT');+ await resolveDesktopOutboundProxy('https://gateway.example:443');+ const picked = getOutboundPathSnapshotFor([+ 'https://chatgpt.com/backend-api/codex',+ 'https://gateway.example/v1',+ ]);+ expect(picked).toMatchObject({ kind: 'direct', upstream: 'https://gateway.example' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('records env-sourced proxies with a redacted address', async () => {+ process.env.HTTPS_PROXY = 'http://user:[email protected]:6152';+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ const snap = snapshotFor('https://chatgpt.com:443');+ expect(snap).toMatchObject({+ source: 'env',+ kind: 'proxy',+ proxy: 'http://127.0.0.1:6152',+ // origin 形态由 originForLog 归一;默认端口按 URL.host 语义省略。+ upstream: 'https://chatgpt.com',+ });+ // 快照会进用户可见的错误消息,凭证绝不能出现在里面。+ expect(JSON.stringify(snap)).not.toContain('sekret');+ });++ it('records a confirmed direct path when the system proxy reports DIRECT', async () => {+ electronState.resolveProxy.mockResolvedValue('DIRECT');+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ source: 'system',+ kind: 'direct',+ });+ expect(snapshotFor('https://chatgpt.com:443')?.reason).toBeUndefined();+ });++ it('distinguishes an unresolved path from a confirmed direct one', async () => {+ // 这是本快照存在的理由:超时/异常下返回的 null 是 fail-open 猜测,不是「确认无代理」。+ // 报成 direct 会让高墙网络里的用户以为代理判定正常,把排查带向反方向。+ electronState.resolveProxy.mockImplementation(() => new Promise(() => {}));+ vi.useFakeTimers();+ try {+ const pending = resolveDesktopOutboundProxy('https://chatgpt.com:443');+ await vi.advanceTimersByTimeAsync(2100);+ await expect(pending).resolves.toBe(null);+ } finally {+ vi.useRealTimers();+ }+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ source: 'system',+ kind: 'unknown',+ reason: 'resolve_timeout',+ });++ resetOutboundProxyResolverStateForTest();+ electronState.resolveProxy.mockReset();+ electronState.resolveProxy.mockRejectedValue(new Error('boom'));+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ kind: 'unknown',+ reason: 'resolve_failed',+ });++ resetOutboundProxyResolverStateForTest();+ electronState.ready = false;+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ kind: 'unknown',+ reason: 'app_not_ready',+ });+ });++ it('re-resolves a failed lookup on the short TTL, not the 30s success TTL', async () => {+ // 行为变化(本次改动):原实现只对「超时」用短 TTL,resolveProxy **抛错**时+ // 落到 30s 长 TTL —— 瞬时故障会让接下来 30 秒一直用直连兜底。两种「没问出来」+ // 都该快速重试,统一走短 TTL。+ vi.useFakeTimers();+ try {+ electronState.resolveProxy.mockRejectedValue(new Error('boom'));+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(electronState.resolveProxy).toHaveBeenCalledTimes(1);++ // 短 TTL(5s)内仍复用缓存,不打爆解析路径。+ await vi.advanceTimersByTimeAsync(4_000);+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(electronState.resolveProxy).toHaveBeenCalledTimes(1);++ // 越过短 TTL 后重新解析;若仍按 30s 缓存,这里就不会有第二次调用。+ await vi.advanceTimersByTimeAsync(2_000);+ electronState.resolveProxy.mockResolvedValue('PROXY 127.0.0.1:7890');+ await expect(resolveDesktopOutboundProxy('https://chatgpt.com:443')).resolves.toBe('http://127.0.0.1:7890');+ expect(electronState.resolveProxy).toHaveBeenCalledTimes(2);+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({ kind: 'proxy' });+ } finally {+ vi.useRealTimers();+ }+ });++ it('keeps per-path PAC verdicts apart instead of collapsing them to the origin', async () => {+ // outbound-fetch 按「origin + path」解析(per-path PAC 靠它,见其 resolveKeyOf),+ // 所以同 origin、不同 requestPath 的两个 chat-bridge 会话可以拿到不同判定。+ // 早先按 origin 归一存快照会让后到的那条覆盖前一条。+ electronState.resolveProxy.mockImplementation(async (url: string) =>+ url.includes('/v1/chat/completions') ? 'PROXY 127.0.0.1:7890' : 'DIRECT');++ await resolveDesktopOutboundProxy('https://api.moonshot.cn/v1/chat/completions');+ await resolveDesktopOutboundProxy('https://api.moonshot.cn/v1/responses');++ // 两条 path 的结论相反 → 无法确定失败的那次走了哪条,宁可不报也不谎报。+ expect(snapshotFor('https://api.moonshot.cn/v1')).toBe(null);+ });++ it('still reports when every path under the origin agrees', async () => {+ electronState.resolveProxy.mockResolvedValue('PROXY 127.0.0.1:7890');+ await resolveDesktopOutboundProxy('https://api.moonshot.cn/v1/chat/completions');+ await resolveDesktopOutboundProxy('https://api.moonshot.cn/v1/responses');++ // 判定一致(PAC 只看 host 是常态)→ 照常给结论。+ expect(snapshotFor('https://api.moonshot.cn/v1')).toMatchObject({+ kind: 'proxy',+ proxy: 'http://127.0.0.1:7890',+ // 展示仍只用 origin —— path 可能带业务语义,不进用户可见消息。+ upstream: 'https://api.moonshot.cn',+ });+ });++ it('does not claim a proxy path for env values the forwarding layer rejects', async () => {+ // envResolver 只做「哪个变量适用」,不校验值可用性。转发层的 parseOutboundProxyUrl+ // 会拒收 https://(TLS-to-proxy)与 socks4://,实际走直连 —— 此时报「已经过该代理」+ // 就是谎报。判定必须用转发层同一个解析器。+ for (const bad of ['https://corporate.proxy:443', 'socks4://legacy.proxy:1080']) {+ resetOutboundProxyResolverStateForTest();+ process.env.HTTPS_PROXY = bad;+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ const snap = snapshotFor('https://chatgpt.com:443');+ expect(snap).toMatchObject({ source: 'env', kind: 'unsupported' });+ // 谎报的地址绝不能出现。+ expect(snap?.proxy).toBeUndefined();+ }++ // 可用形态照旧记 proxy。+ resetOutboundProxyResolverStateForTest();+ process.env.HTTPS_PROXY = 'socks5://127.0.0.1:7891';+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ kind: 'proxy',+ proxy: 'socks5://127.0.0.1:7891',+ });+ });++ it('classifies a configured-but-unusable system proxy as unsupported, not direct', async () => {+ // 企业环境常见:PAC 只给 HTTPS(TLS-to-proxy)出口。行为上确实直连了,但把它+ // 报成「系统报告无代理」会让用户以为代理配置正常,真正的动作是换成 HTTP/SOCKS5。+ electronState.resolveProxy.mockResolvedValue('HTTPS corporate.proxy:443; DIRECT');+ await expect(resolveDesktopOutboundProxy('https://chatgpt.com:443')).resolves.toBe(null);+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ source: 'system',+ kind: 'unsupported',+ });++ // 真 DIRECT 仍是 direct,两者不能混。+ resetOutboundProxyResolverStateForTest();+ electronState.resolveProxy.mockResolvedValue('DIRECT');+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({ kind: 'direct' });+ });++ it('keeps the unsupported verdict when a cached resolution is reused', async () => {+ // 与 unknownReason 同理:标志不跟着缓存走,缓存命中时会把 unsupported 降级成 direct。+ electronState.resolveProxy.mockResolvedValue('HTTPS corporate.proxy:443');+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ electronState.resolveProxy.mockClear();+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(electronState.resolveProxy).not.toHaveBeenCalled();+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({ kind: 'unsupported' });+ });++ it('keeps the unknown verdict when a cached fallback is reused', async () => {+ // unknownReason 必须跟着缓存走,否则缓存命中时会把当初的兜底重新报成 direct。+ electronState.resolveProxy.mockRejectedValue(new Error('boom'));+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ electronState.resolveProxy.mockClear();+ await resolveDesktopOutboundProxy('https://chatgpt.com:443');+ expect(electronState.resolveProxy).not.toHaveBeenCalled();+ expect(snapshotFor('https://chatgpt.com:443')).toMatchObject({+ kind: 'unknown',+ reason: 'resolve_failed',+ });+ });+});diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 8d7719ba0b..8983f4a6a9 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -1442,12 +1442,23 @@ export function createModelRoutingTransform()) {const selectedRouting = getSessionRoutingDescriptor(sessionId, 'codex', model || undefined);if (selectedRouting?.wireProtocol === 'openai-chat' && ctx.method === 'POST' && model) {- return resolveSessionRoute(sessionId, 'codex', model).then((localRoute) =>- createChatBridgeDecision(+ return resolveSessionRoute(sessionId, 'codex', model).then((localRoute) => {+ const decision = createChatBridgeDecision(localRoute,threadId ? registry.get(threadId) : undefined,model,- ));+ );+ // chat bridge 走 localHandler,但它**确实出网** —— handler 自己用+ // outboundFetch 打 route.routing.upstream(绕开转发层,却走同一个出站代理+ // 解析器),所以照样会产生出站路径快照。这里必须补记 thread→上游映射:+ // 漏了的话该供应商不可达时诊断查不到记录,静默退回通用猜测清单。+ // 包装层(withCodexUpstreamRecording)看不到 localHandler 背后的上游,+ // 只能由产生它的分支自己记。+ if (decision && localRoute?.routing.upstream) {+ recordCodexThreadUpstreamForDiagnostics(threadId, localRoute.routing.upstream);+ }+ return decision;+ });}// model 传给 scope 门(空串 = 控制面 GET,不受范围限制);声明了 modelPrefixes 的// 供应商(如 xai)只捕获自家命名空间的请求,其余回落默认路由。@@ -1529,6 +1540,98 @@ function createTransformRequestChain(): RequestTransform[] {return transforms;}+/**+ * threadId → 该 thread 最近一次转发的**实际出口 origin**。+ *+ * 「后端不可达」诊断要报的出站路径必须属于这次失败的请求。resolver 侧的快照按上游+ * origin 分桶,但光有 origin 不够:codex 的出口随会话选定的 provider 变(订阅直连+ * ChatGPT、网关、xAI、自定义供应商),多会话并发时「按时间戳挑最新」只是猜测,可能+ * 把另一个会话的判定报到本次故障上。这里在转发前记下每个 thread 的实际出口,诊断按+ * threadId 精确取。+ *+ * 记录点选在 routingTransform 外层而非 responseObserver:observer 要等响应回来才跑,+ * 而上游不可达时压根没有响应 —— 那恰恰是诊断最需要它的时刻。+ *+ * 另一个副产品:只有请求**真的经过本 loopback proxy** 时才会有记录。gateway-key+ * fallback 下 codexProxyActive=false、codex 直连 gateway,这个 transform 不跑,于是+ * 查不到映射、诊断退回通用文案 —— 而不是报一条本次根本没走过的陈旧路径。+ */+const codexThreadUpstreamOrigin = new Map<string, string>();+const CODEX_THREAD_UPSTREAM_MAX_ENTRIES = 256;++/**+ * 记录 thread 的出口 origin。两个调用点共用(routingTransform 包装层与 chat bridge+ * 分支),守卫集中在这里 —— 分散写必然有一处漏掉 'unknown' 排除或漏掉 try/catch。+ *+ * `selectedThreadIdFromHeaders` 对无 thread 的请求(典型: models-manager 的+ * `GET /models` 轮询)回落到字面量 'unknown';那不是一个 thread,记进去只会污染桶,+ * 而诊断永远是用真实 threadId 来查的。+ *+ * 任何异常一律吞掉:这是诊断旁路,绝不能反过来影响转发。+ */+function recordCodexThreadUpstreamForDiagnostics(+ threadId: string | undefined,+ upstream: string,+): void {+ try {+ if (!threadId || threadId === 'unknown') return;+ const origin = new URL(upstream).origin;+ if (+ codexThreadUpstreamOrigin.size >= CODEX_THREAD_UPSTREAM_MAX_ENTRIES+ && !codexThreadUpstreamOrigin.has(threadId)+ ) {+ codexThreadUpstreamOrigin.clear();+ }+ codexThreadUpstreamOrigin.set(threadId, origin);+ } catch {+ // 上游串解析不出 origin(或其它意外)→ 不记,转发照常。+ }+}++/** 诊断用:该 thread 最近一次转发的实际出口 origin;没有记录过 → null。 */+export function getCodexThreadUpstreamOrigin(threadId: string): string | null {+ return codexThreadUpstreamOrigin.get(threadId) ?? null;+}++/** @internal 单测用。 */+export function resetCodexThreadUpstreamForTest(): void {+ codexThreadUpstreamOrigin.clear();+}++/**+ * 给 routingTransform 包一层「记录本次实际出口」。刻意包在外层而不是往+ * createModelRoutingTransform 内部逐分支补:那里有六个以上 return(含一个返回+ * Promise 的 chat-bridge 分支),逐个补必漏。+ *+ * 记录异常一律吞掉 —— 这是诊断旁路,绝不能反过来影响转发。+ */+export function withCodexUpstreamRecording(+ inner: RoutingTransform,+ defaultUpstream: () => string,+): RoutingTransform {+ return (body, ctx) => {+ const result = inner(body, ctx);+ const record = (decision: RoutingDecision | null): RoutingDecision | null => {+ try {+ // localHandler 的上游在这一层**看不见**(它由产生 decision 的分支自己持有),+ // 所以这里跳过,由那些分支自行记录 —— chat bridge 就在它的 .then 里记了。+ // 注意:localHandler 不代表「不出网」(chat bridge 自己用 outboundFetch 打+ // route.routing.upstream),只代表「不走 compat-proxy 的转发层」。+ if (!decision?.localHandler) {+ recordCodexThreadUpstreamForDiagnostics(+ selectedThreadIdFromHeaders(ctx.headers),+ decision?.upstreamOverride ?? defaultUpstream(),+ );+ }+ } catch {+ // 诊断旁路:记录失败就不记,转发照常。+ }+ return decision;+ };+ return result instanceof Promise ? result.then(record) : record(result);+ };+}+function createCodexProxyHandle(frozenAuthInjection?: CodexProxyAuthInjection,): Promise<ProxyHandle> {@@ -1538,7 +1641,10 @@ function createCodexProxyHandle(transformRequest: createTransformRequestChain(),// 常规 session proxy 继续读取当前全局 spawn 形态;control-plane proxy 在创建时// 冻结自己的形态,两个 app-server 并行时不会互相改写路由。- routingTransform: createModelRoutingTransform(frozenAuthInjection),+ routingTransform: withCodexUpstreamRecording(+ createModelRoutingTransform(frozenAuthInjection),+ () => buildCodexGatewayBaseUrl(),+ ),responseObserver: composeResponseObservers(createCodexResponseObserver(),createProviderUpstreamErrorObserver({diff --git a/apps/desktop/src/main/maker-host/index.ts b/apps/desktop/src/main/maker-host/index.tsindex 26a406914b..6cc3f548a7 100644--- a/apps/desktop/src/main/maker-host/index.ts+++ b/apps/desktop/src/main/maker-host/index.ts@@ -96,6 +96,7 @@ import {getCodexControlPlaneProxyEndpoint,getCodexProxyAuthInjectionState,getCodexProxyEndpoint,+ getCodexThreadUpstreamOrigin,isCodexControlPlaneProxyHandleReady,isCodexProxyHandleReady,setCodexProxyAuthInjection,@@ -134,6 +135,7 @@ import {} from './remote-codex-mcp-recovery.js';import { CODEX_DISABLED_BUILTIN_PLUGIN_IDS_KEY } from '../mcp-integrations/codexBuiltinToolPolicy.js';import { buildCodexProxySpawnArgs, CODEX_OPENAI_COMPACT_PROVIDER_ID } from './codex-gateway-config.js';+import { getOutboundPathSnapshotFor } from './outbound-proxy-resolver.js';import {createDesktopMakerMemoryManager,attachAgentsToMakerMemory,@@ -890,6 +892,23 @@ export function getMaker(): Maker {onCodexLocalModelsListed: (models) => {setDiscoveredCodexModels(mapCodexAppServerModelsToCatalog(models));},+ // 「后端不可达」终局升级时读一次本次请求的出站路径判定,把通用猜测换成实测事实。+ // 快照的 proxy 字段在 resolver 侧已脱敏,可直接进用户可见的错误消息。+ //+ // 两步定位,缺一不可:+ // 1. codex-proxy-host 记的 threadId → 本次实际出口 origin。codex 的出口随会话+ // 选定的 provider 变(订阅直连 ChatGPT、网关、xAI、自定义供应商),猜候选或+ // 按时间戳挑最新都会把别的会话的判定报到本次故障上。+ // 2. 该 origin 在 resolver 侧的判定。resolver 是共享的(anthropic-compat proxy、+ // 通用 outbound-fetch 也在调),按 origin 取才不会串到别的消费方。+ // 任一步查不到就返回 null,退回通用文案 —— 尤其 gateway-key fallback 下+ // codexProxyActive=false、codex 直连不经本 proxy 时,这里必然查不到映射,+ // 于是不会报出一条本次根本没走过的路径。+ getOutboundPathFact: ({ threadId }) => {+ if (!threadId) return null;+ const origin = getCodexThreadUpstreamOrigin(threadId);+ return origin ? getOutboundPathSnapshotFor([origin]) : null;+ },onAutoPermissionClassifierUnavailable: notifyAutoPermissionClassifierUnavailable,prepareCodexLocalCredentialModeSwitch: async (ctx) => {const maker = _maker;diff --git a/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts b/apps/desktop/src/main/maker-host/outbound-proxy-resolver.tsindex e2ab69016f..a079d7c7e8 100644--- a/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts+++ b/apps/desktop/src/main/maker-host/outbound-proxy-resolver.ts@@ -17,6 +17,13 @@** 解析结果变化时记一条 info(每个 origin 只在值变化时记),排查网络问题时 grep* "outbound proxy" 即可看到当前生效路径。+ *+ * 除日志外还留一份**旁路快照**(getLastOutboundPathSnapshot):日志用户看不到,而+ * 「当前到底走没走代理」恰恰是上游不可达时最该告诉用户的一句话。快照只被诊断读取,+ * 不参与任何转发决策 —— 转发行为与扩展前逐字节一致。快照刻意把「解析超时 / 解析+ * 失败 / app 未 ready」记成 `unknown` 而不是 `direct`:这三种情况下我们是 fail-open+ * 猜了直连,而不是确认了无代理,把猜测显示成事实会把排查带向反方向(高墙网络里+ * 直连必然失败,用户却以为代理判定正常)。*/import { app, session } from 'electron';@@ -24,6 +31,7 @@ import { app, session } from 'electron';import {createEnvOutboundProxyResolver,hasProxyEnvConfig,+ parseOutboundProxyUrl,redactProxyUrlForLog,type OutboundProxyResolver,} from '@cindy/anthropic-compat-proxy';@@ -54,9 +62,22 @@ const SYSTEM_PROXY_CACHE_TTL_MS = 30 * 1000;* 支持 SOCKS5 的意义所在(此时直连会因本机解不出上游域名而 ENOTFOUND)。* DIRECT 之后的条目不再考虑:PAC 里 DIRECT 意味着「到此为止,直连即可」。* HTTPS(TLS-to-proxy)与裸 SOCKS(Chromium 里就是 v4)不支持,跳过。+ *+ * `skippedUnsupported` 记录「跳过了至少一个配置了但本实现用不了的条目」。它对转发+ * 决策没有影响(照旧直连),但对诊断是决定性的:`HTTPS corporate.proxy:443` 这种+ * 结果说明**系统确实配了代理、只是 Cindy 用不了**,与「系统报告无代理」是两回事,+ * 报成后者会把用户的排查方向带反。*/-export function parseChromiumProxyResult(result: string): string | null {+export interface ChromiumProxyVerdict {+ /** 选中的代理地址(http:// 或 socks5://);没有可用条目 → null(直连)。 */+ url: string | null;+ /** 是否跳过了 HTTPS(TLS-to-proxy)/ 裸 SOCKS(v4)这类不支持的已配置条目。 */+ skippedUnsupported: boolean;+}++export function parseChromiumProxyResult(result: string): ChromiumProxyVerdict {let socks5Fallback: string | null = null;+ let skippedUnsupported = false;for (const rawEntry of result.split(';')) {const entry = rawEntry.trim();if (!entry) continue;@@ -65,15 +86,69 @@ export function parseChromiumProxyResult(result: string): string | null {if (kind === 'DIRECT') break;const hostPort = spaceIdx === -1 ? '' : entry.slice(spaceIdx + 1).trim();if (!hostPort) continue;- if (kind === 'PROXY') return `http://${hostPort}`;+ if (kind === 'PROXY') return { url: `http://${hostPort}`, skippedUnsupported };// 先记下第一个 SOCKS5;扫完(或遇到 DIRECT)确认没有 PROXY 候选才用它。- if (kind === 'SOCKS5') socks5Fallback ??= `socks5://${hostPort}`;+ if (kind === 'SOCKS5') {+ socks5Fallback ??= `socks5://${hostPort}`;+ continue;+ }+ // HTTPS / SOCKS(v4)/ 其它未知前缀:带了地址却用不了 —— 记下来给诊断。+ skippedUnsupported = true;}- return socks5Fallback;+ return { url: socks5Fallback, skippedUnsupported };+}++/**+ * 「没问出系统代理判定」的原因。存在这一态是本模块的诊断前提:这些分支下返回的+ * `null` 是 fail-open 的猜测,不等于「确认无代理」。+ */+export type OutboundPathUnknownReason =+ | 'resolve_timeout'+ | 'resolve_failed'+ | 'app_not_ready'+ | 'session_unavailable';++/**+ * 出站路径类别。四态刻意分开 —— 它们的**实际行为只有直连或走代理两种,但原因完全+ * 不同**,而原因才是诊断要说的话:+ * - proxy 走代理,且该地址**转发层确实能用**+ * - direct 没有代理配置(env 无、系统解析器给了直连)+ * - unsupported 配了代理但转发层用不了,故实际直连。两种来源:系统侧返回+ * HTTPS(TLS-to-proxy)/ SOCKS(v4)条目;env 侧写了同类形态的值+ * (`HTTPS_PROXY=https://…`、`socks4://…`),被 parseOutboundProxyUrl 拒收。+ * - unknown 判定没问出来(超时 / 异常 / app 未 ready),按直连兜底+ *+ * 判定 proxy 的唯一依据是转发层的 parseOutboundProxyUrl —— resolver 返回了字符串+ * 不代表转发层能用它,按字符串非空就报 proxy 会让诊断谎称走了代理。+ */+export type OutboundPathKind = 'proxy' | 'direct' | 'unsupported' | 'unknown';++/** 出站路径旁路快照 —— 仅供诊断展示,不参与转发决策。 */+export interface OutboundPathSnapshot {+ /** 判定来源:env = 代理环境变量;system = Electron 系统代理 / PAC。 */+ source: 'env' | 'system';+ kind: OutboundPathKind;+ /** kind='proxy' 时的**脱敏**代理地址(scheme://host:port),绝不含 userinfo。 */+ proxy?: string;+ /** kind='unknown' 时的具体原因。 */+ reason?: OutboundPathUnknownReason;+ /** 该判定对应的上游 origin(诊断展示时说明这条事实属于哪个上游)。 */+ upstream: string;+ at: number;}interface CachedResolution {value: string | null;+ /**+ * 该缓存值是「问出来的」还是「没问出来的兜底」。必须跟着缓存走:否则缓存命中时+ * 快照会把当初的 unknown 兜底重新报成 direct。+ */+ unknownReason?: OutboundPathUnknownReason;+ /**+ * 该次解析是否跳过了「配了但不支持」的系统代理条目。同样必须跟着缓存走 ——+ * 否则缓存命中时会把 unsupported 降级报成 direct。+ */+ skippedUnsupported?: boolean;expiresAt: number;}@@ -116,20 +191,34 @@ const SYSTEM_PROXY_RESOLVE_TIMEOUT_MS = 2000;*/const SYSTEM_PROXY_TIMEOUT_CACHE_TTL_MS = 5000;+interface TimedProxyResolution {+ value: string | null;+ timedOut: boolean;+ /** 见 ChromiumProxyVerdict.skippedUnsupported;超时分支下无意义(恒 false)。 */+ skippedUnsupported: boolean;+}+/** 给 resolveProxy 套超时:超时返回 null 并告知调用方这是超时(用于短 TTL 缓存)。 */async function resolveProxyWithTimeout(ses: { resolveProxy(url: string): Promise<string> },upstreamUrl: string,-): Promise<{ value: string | null; timedOut: boolean }> {+): Promise<TimedProxyResolution> {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);+ return await Promise.race<TimedProxyResolution>([+ ses.resolveProxy(upstreamUrl).then((result) => {+ const verdict = parseChromiumProxyResult(result);+ return {+ value: verdict.url,+ timedOut: false,+ skippedUnsupported: verdict.skippedUnsupported,+ };+ }),+ new Promise<TimedProxyResolution>((resolve) => {+ timer = setTimeout(+ () => resolve({ value: null, timedOut: true, skippedUnsupported: false }),+ SYSTEM_PROXY_RESOLVE_TIMEOUT_MS,+ );timer.unref?.();}),]);@@ -138,27 +227,47 @@ async function resolveProxyWithTimeout(}}-async function resolveViaSystemProxy(upstreamUrl: string): Promise<string | null> {+interface SystemProxyResolution {+ value: string | null;+ /** 有值 = 这次的 null 是 fail-open 兜底,不是「确认无代理」。 */+ unknownReason?: OutboundPathUnknownReason;+ /** true = 系统列了代理但形态不支持,直连是「用不了」而非「没配」。 */+ skippedUnsupported?: boolean;+}++async function resolveViaSystemProxy(upstreamUrl: string): Promise<SystemProxyResolution> {const cached = systemProxyCache.get(upstreamUrl);- if (cached && cached.expiresAt > Date.now()) return cached.value;+ if (cached && cached.expiresAt > Date.now()) {+ return {+ value: cached.value,+ unknownReason: cached.unknownReason,+ skippedUnsupported: cached.skippedUnsupported,+ };+ }if (systemProxyCache.size >= SYSTEM_PROXY_CACHE_MAX_ENTRIES) systemProxyCache.clear();// app 未 ready 时 session 不可用;此时按直连处理(splash 极早期,正常请求不会赶在这)。- if (!app.isReady()) return null;+ // 不写缓存:app ready 是单向状态,缓存下来只会让 ready 之后的判定继续用兜底值。+ if (!app.isReady()) return { value: null, unknownReason: 'app_not_ready' };const ses = session.defaultSession;- if (!ses || typeof ses.resolveProxy !== 'function') return null;+ if (!ses || typeof ses.resolveProxy !== 'function') {+ return { value: null, unknownReason: 'session_unavailable' };+ }let value: string | null = null;- let timedOut = false;+ let unknownReason: OutboundPathUnknownReason | undefined;+ let skippedUnsupported = false;try {const resolved = await resolveProxyWithTimeout(ses, upstreamUrl);value = resolved.value;- timedOut = resolved.timedOut;- if (timedOut) {+ skippedUnsupported = resolved.skippedUnsupported;+ if (resolved.timedOut) {+ unknownReason = 'resolve_timeout';log.warn('system proxy resolution timed out — using direct connection', {upstream: originForLog(upstreamUrl),timeoutMs: SYSTEM_PROXY_RESOLVE_TIMEOUT_MS,});}} catch (err) {+ unknownReason = 'resolve_failed';log.warn('system proxy resolution failed — using direct connection', {upstream: originForLog(upstreamUrl),err: err instanceof Error ? err.message : String(err),@@ -168,10 +277,12 @@ async function resolveViaSystemProxy(upstreamUrl: string): Promise<string | null// 超时也写缓存,只是 TTL 短得多 —— 否则后续每个请求都会再打一次已经卡住的解析。systemProxyCache.set(upstreamUrl, {value,+ unknownReason,+ skippedUnsupported,expiresAt:- Date.now() + (timedOut ? SYSTEM_PROXY_TIMEOUT_CACHE_TTL_MS : SYSTEM_PROXY_CACHE_TTL_MS),+ Date.now() + (unknownReason ? SYSTEM_PROXY_TIMEOUT_CACHE_TTL_MS : SYSTEM_PROXY_CACHE_TTL_MS),});- return value;+ return { value, unknownReason, skippedUnsupported };}// 惰性初始化:单测可能对 @cindy/anthropic-compat-proxy 做部分 mock(如 codexProxyHost@@ -182,6 +293,108 @@ function envResolver(upstreamUrl: string): string | null {return _envResolver(upstreamUrl);}+/**+ * 出站路径判定快照,**按调用方给的原始 upstream 键分桶**。+ *+ * 必须分桶而不能存单值:这个 resolver 是共享的(codex proxy、anthropic-compat+ * proxy、通用 outbound-fetch 都在调),单值槽会被最后一个完成解析的请求覆盖。+ * 而 `NO_PROXY` 与 PAC 都可以逐上游给出不同判定,于是诊断可能报出一条属于无关+ * 上游、甚至与故障上游结论相反的路径。+ *+ * 键刻意保留调用方传进来的原始形态,不归一成 origin:两个消费方的粒度本来就不同 ——+ * compat-proxy 的转发层按 origin 解析,而 outbound-fetch 按「origin + path」解析+ * (见其 `resolveKeyOf`,per-path PAC 靠它)。归一成 origin 会让同 origin、不同+ * requestPath 的两个 chat-bridge 会话互相覆盖判定。展示侧仍只用 origin(见+ * snapshot.upstream),不把 path 带进用户可见消息。+ *+ * 上限与 systemProxyCache 同量级;满了整体清空(下一轮请求会重新填)。+ */+const outboundPathByKey = new Map<string, OutboundPathSnapshot>();++function recordOutboundPath(+ upstreamUrl: string,+ source: 'env' | 'system',+ value: string | null,+ opts: {+ unknownReason?: OutboundPathUnknownReason;+ skippedUnsupported?: boolean;+ } = {},+): void {+ const origin = originForLog(upstreamUrl);+ if (+ outboundPathByKey.size >= SYSTEM_PROXY_CACHE_MAX_ENTRIES+ && !outboundPathByKey.has(upstreamUrl)+ ) {+ outboundPathByKey.clear();+ }+ // 关键:kind 必须反映**转发层实际会做什么**,不是 resolver 返回了什么字符串。+ // resolver 可以返回一个转发层根本用不了的地址(env 里写 HTTPS_PROXY=https://…+ // 的 TLS-to-proxy,或 socks4://),转发层的 parseOutboundProxyUrl 会拒收并直连 ——+ // 此时报「已经过 X 代理」就是在撒谎。用同一个解析器判定,谎报不了。+ const usable = value ? parseOutboundProxyUrl(value) : null;+ // 优先级:没问出来(unknown)> 转发层能用的代理(proxy)> 配了但用不了(unsupported)+ // > 确认没有代理配置(direct)。unsupported 必须压在 direct 之前 —— 两者的实际行为+ // 都是直连,但「列了代理却用不了」和「没有代理」是完全不同的排查方向。+ const kind: OutboundPathKind = opts.unknownReason+ ? 'unknown'+ : usable+ ? 'proxy'+ : value || opts.skippedUnsupported+ ? 'unsupported'+ : 'direct';+ outboundPathByKey.set(upstreamUrl, {+ source,+ kind,+ // 只在转发层真能用时报地址,且只报脱敏形态(env 值可能带 user:pass)。+ // usable.url 已是规范化后的无 userinfo 形态,再过一次脱敏是纵深防御。+ ...(opts.unknownReason ? { reason: opts.unknownReason } : {}),+ ...(usable && !opts.unknownReason ? { proxy: redactProxyUrlForLog(usable.url) } : {}),+ upstream: origin,+ at: Date.now(),+ });+}++/**+ * 取**指定上游**的出站路径判定;都没有记录过则返回 null。+ *+ * 入参收候选列表而不是单个值:调用方的实际上游可能随凭证模式动态切换(codex 订阅+ * 直连打 ChatGPT,网关模式打 gateway),但都属于同一个消费方;而且调用方手里通常是+ * 带 path 的 base URL,与快照键的粒度不一定一致,所以这里按 origin 归组匹配。+ *+ * **同一个 origin 下有多条判定且结论不一致时返回 null。** PAC 允许逐 path 给出不同+ * 判定,此时无法确定失败的那次请求走的是哪一条 —— 报其中任意一条(哪怕是最新的)+ * 都可能属于另一条 path。这条路径上宁可不报,也不能谎报。+ *+ * 注意冲突判定只在**组内**(同 origin):候选之间本来就允许不同(订阅直连与网关是+ * 两个 origin、判定天然可以不同),跨组按 `at` 取最新。+ *+ * 只读诊断用途:上游不可达时把「当前走的是代理 / 直连 / 配了但用不了 / 判定没问+ * 出来」这句事实交给用户,比让他猜快得多。返回的 proxy 字段已脱敏,可直接进错误+ * 消息与日志。+ */+export function getOutboundPathSnapshotFor(+ upstreamCandidates: readonly string[],+): OutboundPathSnapshot | null {+ const wanted = new Set(upstreamCandidates.map((raw) => originForLog(raw)));+ const byOrigin = new Map<string, OutboundPathSnapshot>();+ for (const snap of outboundPathByKey.values()) {+ if (!wanted.has(snap.upstream)) continue;+ const prev = byOrigin.get(snap.upstream);+ if (!prev) {+ byOrigin.set(snap.upstream, snap);+ continue;+ }+ // 一致性只看结论(走哪个代理 / 哪一类);unknown 的具体 reason 不同不算冲突。+ if (prev.kind !== snap.kind || prev.proxy !== snap.proxy) return null;+ if (snap.at > prev.at) byOrigin.set(snap.upstream, snap);+ }+ let best: OutboundPathSnapshot | null = null;+ for (const snap of byOrigin.values()) {+ if (!best || snap.at > best.at) best = snap;+ }+ return best;+}+/*** 两个 proxy host 共用的出站代理解析器(单例,系统代理缓存共享)。* per-request 由 anthropic-compat-proxy 以最终上游 origin 调用;loopback 上游@@ -191,15 +404,21 @@ export const resolveDesktopOutboundProxy: OutboundProxyResolver = async (upstreaif (hasProxyEnvConfig()) {const fromEnv = envResolver(upstreamUrl);logIfChanged(upstreamUrl, 'env', fromEnv);+ recordOutboundPath(upstreamUrl, 'env', fromEnv);return fromEnv;}const fromSystem = await resolveViaSystemProxy(upstreamUrl);- logIfChanged(upstreamUrl, 'system', fromSystem);- return fromSystem;+ logIfChanged(upstreamUrl, 'system', fromSystem.value);+ recordOutboundPath(upstreamUrl, 'system', fromSystem.value, {+ unknownReason: fromSystem.unknownReason,+ skippedUnsupported: fromSystem.skippedUnsupported,+ });+ return fromSystem.value;};-/** @internal 单测用:清空系统代理解析缓存与日志去重状态。 */+/** @internal 单测用:清空系统代理解析缓存、日志去重与路径快照状态。 */export function resetOutboundProxyResolverStateForTest(): void {systemProxyCache.clear();lastLoggedByOrigin.clear();+ outboundPathByKey.clear();}diff --git a/packages/maker-core/src/agents/base-agent.ts b/packages/maker-core/src/agents/base-agent.tsindex ce45e5a5de..a7d684516c 100644--- a/packages/maker-core/src/agents/base-agent.ts+++ b/packages/maker-core/src/agents/base-agent.ts@@ -268,6 +268,26 @@ export interface AgentDeps {*/getRemoteCodexTransport?: (remoteHostId: string) => import('./codex/app-server/transport.js').Transport;+ /**+ * Codex 专用:读**这个 thread 本次实际出口**的出站代理路径判定,用于把「后端不可达」+ * 的通用猜测换成实测事实(走了哪个代理 / 确认直连 / 配了但用不了 / 判定没问出来)。+ *+ * 必须传 threadId:codex 的出口随会话选定的 provider 变(订阅直连、网关、xAI、+ * 自定义供应商),host 侧要靠它定位本次请求真正打的上游。拿不到对应记录时**必须**+ * 返回 null(例:本次请求没经过 loopback proxy),而不是回退到「最近一条」——+ * 报一条本次没走过的路径比不报更糟。+ *+ * 只在**本地** session 的 retry-loop 终局升级时读一次,不进任何热路径;实现必须是+ * 同步、只读、不抛的内存快照读取(desktop 侧 = outbound-proxy-resolver 的快照 ++ * codex-proxy-host 的 thread→上游映射)。返回的 proxy 字段必须已脱敏 —— 它会进+ * 用户可见的错误消息。+ *+ * 缺省 / undefined / 返回 null → 保留原有的通用排查文案,不降级任何行为。+ */+ getOutboundPathFact?: (+ ctx: { threadId?: string },+ ) => import('./codex/retry-escalation.js').OutboundPathFact | null;+/*** Maker Memory 顶层单例 (host 注入). 当 runtimeConfig.makerMemoryEnabled === true 时,* agent.startSession 会从这里拉当前 workdir 的 MEMORY.md 索引拼进 system prompt;diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 7d47e911f9..9ef72ee060 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -95,6 +95,7 @@ import {import {TurnRetryTracker,buildBackendUnreachableMessage,+ type OutboundPathFact,} from './retry-escalation.js';import { extractNonSecretErrorSignals } from '@cindy/maker-shared/error-redaction';import { AppServerHost, type ThreadEventHandlers, type ThreadSubscription } from './app-server/host.js';@@ -4754,18 +4755,39 @@ export class CodexAgent extends BaseAgent {});});}+ // 出站路径快照只对本地有意义 (远端 daemon 自己出网, 见+ // buildBackendUnreachableMessage 注释)。必须带 threadId: host 侧靠它+ // 定位本次请求实际打的上游 (codex 的出口随会话 provider 变), 查不到就+ // 返回 null 而不是拿「最近一条」凑。读取按 best-effort: 诊断绝不能反过来+ // 把已经在收口的错误路径搞崩。+ let outboundPath = null as OutboundPathFact | null;+ if (!opts.remoteHostId && this.deps.getOutboundPathFact) {+ try {+ outboundPath = this.deps.getOutboundPathFact({+ threadId: params.threadId,+ }) ?? null;+ } catch (e) {+ log.warn('outbound path fact lookup failed (best-effort)', {+ error: e instanceof Error ? e.message : String(e),+ });+ }+ }const message = buildBackendUnreachableMessage({isRemote: Boolean(opts.remoteHostId),remoteHostId: opts.remoteHostId,retryCount: decision.retryCount,elapsedMs: decision.elapsedMs,lastError: rawMessage,+ outboundPath,});log.error('codex retry-loop escalated to terminal error (backend unreachable)', {threadId: params.threadId,turnId: params.turnId,retryCount: decision.retryCount,elapsedMs: decision.elapsedMs,+ // 与用户看到的消息同源;`at` 让排查者判断这条判定有多新+ // (系统代理判定有 TTL 缓存, 陈旧快照要按陈旧解读)。+ ...(outboundPath ? { outboundPath } : {}),});effectiveParams = { ...params, willRetry: false, error: { message } };isTerminalError = true;diff --git a/packages/maker-core/src/agents/codex/retry-escalation.test.ts b/packages/maker-core/src/agents/codex/retry-escalation.test.tsindex b4b1126a7d..c1f779017b 100644--- a/packages/maker-core/src/agents/codex/retry-escalation.test.ts+++ b/packages/maker-core/src/agents/codex/retry-escalation.test.ts@@ -8,8 +8,10 @@ import { describe, expect, it } from 'vitest';import {TurnRetryTracker,buildBackendUnreachableMessage,+ describeOutboundPath,RETRY_ESCALATION_MAX_COUNT,RETRY_ESCALATION_MAX_ELAPSED_MS,+ type OutboundPathFact,} from './retry-escalation.js';describe('TurnRetryTracker', () => {@@ -105,4 +107,131 @@ describe('buildBackendUnreachableMessage', () => {expect(msg).not.toContain('\nline2');expect(msg.length).toBeLessThan(900);});++ it('local variant replaces the generic cause list with the measured outbound path', () => {+ const msg = buildBackendUnreachableMessage({+ isRemote: false,+ retryCount: 30,+ elapsedMs: 30_000,+ lastError: 'fetch failed',+ outboundPath: {+ source: 'system',+ kind: 'direct',+ upstream: 'https://chatgpt.com',+ },+ });+ expect(msg).toContain('direct connection');+ expect(msg).toContain('https://chatgpt.com');+ // 通用四选一猜测清单应被实测事实取代,否则两段互相矛盾。+ expect(msg).not.toContain('Likely causes');+ });++ it('falls back to the generic cause list when no outbound fact is available', () => {+ const msg = buildBackendUnreachableMessage({+ isRemote: false,+ retryCount: 30,+ elapsedMs: 30_000,+ lastError: 'fetch failed',+ outboundPath: null,+ });+ expect(msg).toContain('Likely causes');+ });++ it('never attaches the local outbound path to a remote failure', () => {+ // 远端 daemon 在远端机器上自己出网 — 报本机代理判定会把排查指向错误的机器。+ const msg = buildBackendUnreachableMessage({+ isRemote: true,+ remoteHostId: 'gpu-box',+ retryCount: 30,+ elapsedMs: 30_000,+ lastError: 'Network unreachable',+ outboundPath: {+ source: 'env',+ kind: 'proxy',+ proxy: 'http://127.0.0.1:7890',+ upstream: 'https://chatgpt.com',+ },+ });+ expect(msg).not.toContain('127.0.0.1:7890');+ expect(msg).not.toContain("Cindy's outbound path");+ expect(msg).toContain('Route agent traffic via local proxy');+ });+});++describe('describeOutboundPath', () => {+ const fact = (over: Partial<OutboundPathFact>): OutboundPathFact => ({+ source: 'system',+ kind: 'direct',+ upstream: 'https://chatgpt.com',+ ...over,+ });++ it('names the proxy and where the verdict came from', () => {+ expect(describeOutboundPath(fact({+ kind: 'proxy', proxy: 'http://127.0.0.1:7890', source: 'env',+ }))).toContain('via http://127.0.0.1:7890');+ expect(describeOutboundPath(fact({+ kind: 'proxy', proxy: 'socks5://127.0.0.1:7891', source: 'system',+ }))).toContain('system proxy settings');+ });++ it('states a system-sourced direct path without asserting the system has no proxy', () => {+ // 只有「没有代理 env」可以断言(走到 system 分支的前提)。系统侧不能断言 ——+ // resolveProxy 是逐 URL 解析,系统可能配了代理、只是 PAC/bypass 豁免了这个上游,+ // 那时它对该 URL 就返回 DIRECT。说成「系统报告无代理」会盖掉这种 bypass。+ const text = describeOutboundPath(fact({ source: 'system', kind: 'direct' }));+ expect(text).toContain('direct connection');+ expect(text).toContain('no proxy env var is set');+ expect(text).toContain('returned a direct route for this upstream');+ expect(text).toContain('bypassing this host');+ expect(text).not.toContain('reported none');+ });++ it('renders an env-sourced direct path as a bypass, never as missing proxy config', () => {+ // 走 env 分支的前提恰恰是**有**代理 env。此时的 direct 意味着配了代理却对这个+ // 上游不生效(NO_PROXY 豁免 / 没有覆盖该 scheme 的变量)。说成「没设代理」会+ // 盖掉真正的故障原因,把用户推向反方向。+ const text = describeOutboundPath(fact({ source: 'env', kind: 'direct' }));+ expect(text).toContain('proxy env vars are set');+ expect(text).toContain('NO_PROXY');+ expect(text).toContain('bypassed');+ expect(text).not.toContain('no proxy env var is set');+ expect(text).not.toContain('reported none');+ });++ it('renders an unsupported system proxy as configured-but-unusable, not as absent', () => {+ // 企业 PAC 只给 HTTPS(TLS-to-proxy)出口时,行为上是直连,但原因是「Cindy 用+ // 不了那个形态」。报成「没有代理」会让用户以为配置正常,而正确动作是换出口类型。+ const text = describeOutboundPath(fact({ source: 'system', kind: 'unsupported' }));+ expect(text).toContain('do list a proxy');+ expect(text).toContain('cannot use');+ expect(text).toContain('SOCKS5');+ expect(text).not.toContain('no proxy env var is set');+ });++ it('points env-sourced unsupported values at the variable, not the system settings', () => {+ // unsupported 也可能来自 env(HTTPS_PROXY=https://… / socks4://),此时该改的是+ // 变量值而不是系统设置 —— 指错位置等于没给动作。+ const text = describeOutboundPath(fact({ source: 'env', kind: 'unsupported' }));+ expect(text).toContain('proxy env var is set');+ expect(text).toContain('http:// or socks5://');+ expect(text).not.toContain('system proxy settings');+ });++ it('always returns a non-empty diagnostic for every kind', () => {+ for (const kind of ['proxy', 'direct', 'unsupported', 'unknown'] as const) {+ for (const source of ['env', 'system'] as const) {+ expect(describeOutboundPath(fact({ kind, source })).length).toBeGreaterThan(0);+ }+ }+ });++ it('marks an unresolved path as a guess rather than a confirmed no-proxy', () => {+ // 这条是整个改动的语义核心:超时兜底不得被读成「确认无代理」。+ const text = describeOutboundPath(fact({ kind: 'unknown', reason: 'resolve_timeout' }));+ expect(text).toContain('could not determine');+ expect(text).toContain('resolve_timeout');+ expect(text).toContain('a guess');+ expect(text).not.toContain('reported none');+ });});diff --git a/packages/maker-core/src/agents/codex/retry-escalation.ts b/packages/maker-core/src/agents/codex/retry-escalation.tsindex b60fb8eb07..a875aecf1c 100644--- a/packages/maker-core/src/agents/codex/retry-escalation.ts+++ b/packages/maker-core/src/agents/codex/retry-escalation.ts@@ -27,6 +27,99 @@ export interface RetryEscalationDecision {elapsedMs: number;}+/**+ * 本机出站路径事实(host 注入,来源是 desktop 的 outbound-proxy-resolver 快照)。+ *+ * 存在的理由:「后端不可达」时最有用的一句话是「你现在到底走没走代理」,而这件事+ * Cindy 自己知道、用户看不到 —— 日志在磁盘上,错误消息里只有一串通用猜测。+ *+ * `kind='unknown'` 是刻意与 `direct` 分开的:那表示代理判定没问出来、按直连兜底,+ * 不是确认了无代理。把猜测当事实报给用户会把排查带向反方向。+ *+ * 类型在此本地定义(不 import desktop 侧类型):maker-core 零 Electron 依赖。+ */+export interface OutboundPathFact {+ source: 'env' | 'system';+ /**+ * 四态的实际行为只有「走代理」与「直连」两种,但**原因**完全不同,而原因才是+ * 诊断要说的话:direct = 确认没配;unsupported = 配了但形态用不了(TLS-to-proxy+ * / SOCKS4);unknown = 判定没问出来、按直连兜底。+ */+ kind: 'proxy' | 'direct' | 'unsupported' | 'unknown';+ /** 已脱敏的代理地址(scheme://host:port);kind='proxy' 时有值。 */+ proxy?: string;+ /** kind='unknown' 时的原因标识(resolve_timeout / resolve_failed / …)。 */+ reason?: string;+ upstream: string;+ /**+ * 判定时间戳。不进用户消息(对排查没有直接价值),但会进升级日志 —— 系统代理+ * 判定带 TTL 缓存,读日志的人需要知道这条事实是刚测的还是缓存里的。+ */+ at?: number;+}++/**+ * 把出站路径事实渲染成一行可操作的诊断。恒返回非空串 —— 三种 kind 各有话可说。+ * 导出仅供单测。+ *+ * `direct` 必须按 source 分叉,两者是**语义相反**的结论:+ * - source='env':有代理 env 才会走 env 分支,所以这里的 direct 意味着**配了代理+ * 却对这个上游不生效**(NO_PROXY 豁免了它,或没有覆盖该 scheme 的变量)。说成+ * 「没设代理」会盖掉真正的原因,把用户推向反方向。+ * - source='system':只能断言「没有代理 env」(走到这一层的前提),**不能**断言+ * 系统侧没有代理配置 —— `session.resolveProxy` 是逐 URL 解析,系统完全可以配了+ * 代理、只是 PAC / bypass 规则豁免了这个上游,那时它对该 URL 就返回 DIRECT。+ * 所以这一支只陈述「系统解析器为这个上游给了直连」,并提示 bypass 的可能。+ */+export function describeOutboundPath(fact: OutboundPathFact): string {+ if (fact.kind === 'proxy') {+ const from = fact.source === 'env' ? 'proxy env vars' : 'system proxy settings';+ return (+ `Cindy's outbound path for ${fact.upstream}: via ${fact.proxy ?? '(unknown address)'} ` ++ `(from ${from}). If that proxy is down or cannot reach the upstream, this is where it fails.`+ );+ }+ if (fact.kind === 'unsupported') {+ // 配了代理,但形态转发层用不了(TLS-to-proxy 的 https / SOCKS4),所以实际直连。+ // 报成「没有代理」会让用户以为配置正常,真正的动作是把出口换成 HTTP 或 SOCKS5。+ // 两种来源的修改位置不同 —— env 改变量值,system 改系统/PAC 里的那一条。+ if (fact.source === 'env') {+ return (+ `Cindy's outbound path for ${fact.upstream}: direct connection — a proxy env var is set, ` ++ `but its value is not a form Cindy can use (an https:// TLS-to-proxy or socks4:// URL), ` ++ `so it was rejected and the request went out directly. Use an http:// or socks5:// proxy URL.`+ );+ }+ return (+ `Cindy's outbound path for ${fact.upstream}: direct connection — the system proxy ` ++ `settings do list a proxy for this upstream, but in a form Cindy cannot use (an HTTPS/` ++ `TLS-to-proxy entry, or SOCKS4), so the request went out directly. Switch that entry to ` ++ `an HTTP or SOCKS5 proxy to route Cindy through it.`+ );+ }+ if (fact.kind === 'direct') {+ if (fact.source === 'env') {+ return (+ `Cindy's outbound path for ${fact.upstream}: direct connection — proxy env vars are set, ` ++ `but none of them applies to this upstream (NO_PROXY exempts it, or no variable covers ` ++ `its scheme), so the configured proxy is being bypassed. On a network that needs a proxy ` ++ `to reach the upstream, that bypass alone explains the failure.`+ );+ }+ return (+ `Cindy's outbound path for ${fact.upstream}: direct connection — no proxy env var is set, ` ++ `and the system proxy resolver returned a direct route for this upstream (a system proxy ` ++ `may still be configured but bypassing this host). On a network that needs a proxy or VPN ` ++ `to reach the upstream, this explains the failure.`+ );+ }+ return (+ `Cindy could not determine the outbound path for ${fact.upstream} ` ++ `(${fact.reason ?? 'unknown reason'}) and fell back to a direct connection. ` ++ `That fallback is a guess, not a confirmed "no proxy" — on a network that needs a proxy it fails.`+ );+}+export class TurnRetryTracker {private turnId: string | null = null;private count = 0;@@ -61,6 +154,10 @@ export class TurnRetryTracker {/*** 升级时合成给用户的终态错误消息。保留末次原始错误 (截断) 作为诊断锚点;* 按 local/remote 给出不同的排查指向 (remote 才有 SSH 代理隧道入口)。+ *+ * `outboundPath` 只在**本地**场景附加: 远端 daemon 在远端机器上自己出网, 本机的+ * 出站代理判定与它无关 —— 把本机快照报给远端故障会指错方向 (agentProxy 未开时+ * 远端根本不经本机)。远端仍走原有的 SSH 代理隧道引导。*/export function buildBackendUnreachableMessage(opts: {isRemote: boolean;@@ -68,6 +165,7 @@ export function buildBackendUnreachableMessage(opts: {retryCount: number;elapsedMs: number;lastError: string;+ outboundPath?: OutboundPathFact | null;}): string {const last = opts.lastError.trim().replace(/\s+/g, ' ').slice(0, 300) || '(no error detail)';const elapsedS = Math.round(opts.elapsedMs / 1000);@@ -75,6 +173,13 @@ export function buildBackendUnreachableMessage(opts: {`Codex backend unreachable — the daemon retried ${opts.retryCount} times over ${elapsedS}s ` +`without success (last error: "${last}").`;if (!opts.isRemote) {+ // 有实测出站事实就用它替掉通用猜测清单 —— 后者把四种原因并列, 等于没有指向。+ if (opts.outboundPath) {+ return (+ `${head}\nThe Codex backend (chatgpt.com) is not responding.\n` ++ `${describeOutboundPath(opts.outboundPath)}`+ );+ }return (`${head}\nThe Codex backend (chatgpt.com) is not responding. Likely causes: network outage, ` +`proxy/VPN required, request blocked (403), or timeout. Check your connection and retry.`