Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 让已有任务使用轮换后的网关凭据
liugaowei502e49d0b67c
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.tsindex 684b09b393..0945d76d27 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyGuestRoute.test.ts@@ -30,7 +30,7 @@ import { buildUserProvider } from '@cindy/model-providers';import type { RoutingDecision } from '@cindy/anthropic-compat-proxy';import { setCustomProviders } from '../active-catalog';-import { createCodexGuestRoutingGuard, registerComposed, unregister } from '../codex-proxy-host';+import { createCodexGuestRoutingGuard, registerComposed, setCodexProxyGatewayKeyReader, unregister } from '../codex-proxy-host';import { CODEX_CUSTOM_PROVIDER_ROUTE_ROOT } from '../codex-custom-provider-route';import { registerGuestProviderRoute, resetGuestProviderRoutesForTest } from '../guest-provider-route-store';import { clearAllSessionProviders, setSessionProvider } from '../session-provider-store';@@ -65,6 +65,7 @@ describe('Codex proxy guard for shared-provider guests', () => {resetGuestProviderRoutesForTest();clearAllSessionProviders();setCustomProviders([]);+ setCodexProxyGatewayKeyReader(() => null);});it('lets a guest request for a shared model continue to the session route', () => {@@ -88,13 +89,17 @@ describe('Codex proxy guard for shared-provider guests', () => {expect(await statusOf(guard({ model: 'shared-model' }, ctx('/responses', { 'thread-id': 'owner-thread' })))).toBe(403);});- it('routes an unresolved request straight to the default upstream only when that is the shared provider', () => {+ it('routes an unresolved request with the current gateway key only when that is the shared provider', async () => {const gateway = createCodexGuestRoutingGuard('xd', 'env-key');// 模型核对按 xd 的目录:这里的 fixture 没有 xd 模型,所以推理请求被拒;非推理路径只看默认路由。- expect(gateway({ model: 'gpt-image-1' }, ctx('/images/generations'))).toBeNull();+ setCodexProxyGatewayKeyReader(() => 'test-current-gateway-key');+ expect(gateway({ model: 'gpt-image-1' }, ctx('/images/generations'))).toEqual({+ headerOverride: { authorization: 'Bearer test-current-gateway-key' },+ });+ setCodexProxyGatewayKeyReader(() => null);+ expect(await statusOf(gateway({ model: 'gpt-image-1' }, ctx('/images/generations')))).toBe(401);const mismatched = createCodexGuestRoutingGuard('xd', 'oauth-bearer');- return statusOf(mismatched({ model: 'gpt-image-1' }, ctx('/images/generations')))- .then((status) => expect(status).toBe(403));+ expect(await statusOf(mismatched({ model: 'gpt-image-1' }, ctx('/images/generations')))).toBe(403);});it('leaves custom-provider paths and control-plane requests to the frozen routing', () => {diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 7588350e58..d7389d2b24 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -189,7 +189,7 @@ beforeAll(async () => {}, process.platform === 'win32' ? 120_000 : 60_000);-/** 本地 403 拒绝的 localHandler:执行它并返回写出的状态码与响应体。 */+/** 本地拒绝的 localHandler:执行它并返回写出的状态码与响应体。 */async function runLocalRefusal(decision: unknown): Promise<{ status: number; body: { error?: { code?: string } } }> {const handler = (decision as { localHandler?: (args: { res: unknown }) => Promise<void> }).localHandler;if (typeof handler !== 'function') throw new Error('expected a local refusal handler');@@ -677,10 +677,10 @@ describe('createCrossProviderCompactionCompatTransform', () => {describe('decideCodexRoute', () => {const CHATGPT = 'https://chatgpt.com/backend-api/codex';- it('env-key spawn → 不 override(codex 已带 gateway key, 走默认上游)', async () => {+ it.each(['gpt-5.5', 'codex/gpt-5.5', ''])('env-key spawn → 用当前 gateway key 覆盖请求头: %s', async (model) => {const { decideCodexRoute } = await import('../codex-proxy-host.js');- expect(decideCodexRoute({ model: 'gpt-5.5', authInjection: 'env-key', gatewayKey: 'k' })).toBeNull();- expect(decideCodexRoute({ model: 'codex/gpt-5.5', authInjection: 'env-key', gatewayKey: 'k' })).toBeNull();+ expect(decideCodexRoute({ model, authInjection: 'env-key', gatewayKey: 'test-current-gateway-key' }))+ .toEqual({ headerOverride: { authorization: 'Bearer test-current-gateway-key' } });});it('oauth-bearer + codex/ 折扣模型 → 换 gateway key', async () => {@@ -1401,7 +1401,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toBeNull();+ expect(decision).toEqual({ headerOverride: { authorization: 'Bearer xd-gateway-key' } });expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();host.unregister('session-xd-no-projection');@@ -1449,7 +1449,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toBeNull();+ expect(decision).toEqual({ headerOverride: { authorization: 'Bearer xd-gateway-key' } });expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();} finally {host.unregister('session-implicit-xd');@@ -1477,6 +1477,7 @@ describe('chatBridgeCapabilitiesForRoute', () => {);clearSessionProvider('session-native-hot-path');host.setCodexProxyAuthInjection('env-key');+ host.setCodexProxyGatewayKeyReader(() => 'test-native-gateway-key');try {const decision = await Promise.resolve(host.createModelRoutingTransform()(@@ -1492,13 +1493,14 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toBeNull();+ expect(decision).toEqual({ headerOverride: { authorization: 'Bearer test-native-gateway-key' } });expect(providerViewsReader).not.toHaveBeenCalled();} finally {host.unregister('session-native-hot-path');clearSessionProvider('session-native-hot-path');setProviderViewsReader(async () => []);setXdGatewayModels([]);+ host.setCodexProxyGatewayKeyReader(() => null);}});@@ -2354,7 +2356,10 @@ describe('chatBridgeCapabilitiesForRoute', () => {},));- expect(decision).toBeNull();+ expect(await runLocalRefusal(decision)).toMatchObject({+ status: 401,+ body: { error: { code: 'cindy_gateway_credentials_unavailable' } },+ });expect(mockState.createResponsesAnthropicHandler).not.toHaveBeenCalled();clearSessionProvider('session-xd-no-key');@@ -2558,11 +2563,44 @@ describe('createModelRoutingTransform —— session-less 控制面请求(桶③})).toEqual({ upstreamOverride: CHATGPT });});- it('env-key + 无 session + 无 model(GET /models)→ null(留默认网关, sk- key 本就有效)', async () => {- const host = await import('../codex-proxy-host.js');- host.setCodexProxyAuthInjection('env-key');- const transform = host.createModelRoutingTransform();- expect(transform(undefined, { reqId: 1, method: 'GET', url: '/models', headers: {} })).toBeNull();+ it.each(['responses', 'models'] as const)('env-key proxy 随凭据轮换更新 /%s,撤销后拒绝旧 key', async (endpoint) => {+ const host = await freshCodexProxyHost();+ const { setSessionProvider, clearSessionProvider } = await import('../session-provider-store.js');+ let gatewayKey: string | null = 'test-old-gateway-key';+ const readKey = vi.fn(() => gatewayKey);+ host.setCodexProxyGatewayKeyReader(readKey);+ host.registerComposed('session-key-rotation', 'thread-key-rotation', 'PRODUCT_PROMPT');+ setSessionProvider('session-key-rotation', 'xd');+ // 独立 host 冻结 env-key 身份;其它 host 改写全局形态不应改变它的路由。+ host.setCodexProxyAuthInjection('oauth-bearer');+ const transform = host.createModelRoutingTransform('env-key');+ const body = endpoint === 'responses' ? { model: 'gpt-5.5', input: [] } : undefined;+ const headers = { authorization: 'Bearer test-old-gateway-key',+ ...(endpoint === 'responses' ? { 'thread-id': 'thread-key-rotation' } : {}),+ };+ const ctx = { reqId: 1, method: endpoint === 'responses' ? 'POST' : 'GET', url: `/${endpoint}`, headers };++ try {+ expect(await transform(body, ctx)).toEqual({+ headerOverride: { authorization: 'Bearer test-old-gateway-key' },+ });+ gatewayKey = 'test-new-gateway-key';+ expect(await transform(body, { ...ctx, reqId: 2 })).toEqual({+ headerOverride: { authorization: 'Bearer test-new-gateway-key' },+ });+ gatewayKey = null;+ const refused = await transform(body, { ...ctx, reqId: 3 });+ expect(await runLocalRefusal(refused)).toMatchObject({+ status: 401,+ body: { error: { code: 'cindy_gateway_credentials_unavailable' } },+ });+ expect(readKey).toHaveBeenCalledTimes(3);+ expect(headers.authorization).toBe('Bearer test-old-gateway-key');+ } finally {+ host.unregister('session-key-rotation');+ clearSessionProvider('session-key-rotation');+ host.setCodexProxyGatewayKeyReader(() => null);+ }});it('provider-oauth + 无 session + 无 model(GET /models)→ 路由到 provider OAuth 上游', async () => {diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex 26810e4f29..50b7c9641d 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -2428,7 +2428,7 @@ function createCodexResponseObserver(): ResponseObserver {/*** 纯函数: 按 model(原始, 含 codex/ 前缀)+ spawn 鉴权注入方式决定 **默认** 上游 / 鉴权 override。* (会话显式选了供应商时由 resolveSessionRouteDecision 优先接管,不会走到这里。)- * - env-key spawn(codex 已带 gateway key): 全程 null(走默认上游 gateway, 不动 header)。+ * - env-key spawn: 走默认上游 gateway,用当前 key 覆盖子进程启动时的旧 key;无 key 则本地拒绝。* - oauth-bearer spawn(codex 带 OAuth token):* codex/ 折扣模型 → 换 gateway key, 默认上游(gateway); 无 key 则 null(passthrough, 上游会 401)。* 普通模型 → override 上游到 ChatGPT, 透传 OAuth token(不动 header)= 订阅默认。@@ -2439,7 +2439,27 @@ export function decideCodexRoute(opts: {authInjection: CodexProxyAuthInjection;gatewayKey: string | null;}): RoutingDecision | null {- if (opts.authInjection === 'env-key' || opts.authInjection === 'provider-oauth') return null;+ if (opts.authInjection === 'env-key') {+ if (opts.gatewayKey) {+ return { headerOverride: { authorization: `Bearer ${opts.gatewayKey}` } };+ }+ return {+ localHandler: async ({ res }) => {+ res.writeHead(401, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ });+ res.end(JSON.stringify({+ error: {+ type: 'authentication_error',+ code: 'cindy_gateway_credentials_unavailable',+ message: 'Cindy AI credentials are unavailable.',+ },+ }));+ },+ };+ }+ if (opts.authInjection === 'provider-oauth') return null;if (!opts.model) return null;const toGateway = gatewayProviderIdForRewrittenModel(opts.model) !== null;if (toGateway) {@@ -3016,8 +3036,8 @@ export function createModelRoutingTransform(}// ① 该会话显式选了供应商 → 据 catalog 统一路由。thread-id header → threadToSession 反解 xdt sessionId。- // oauth-bearer 态全量适用;env-key 态默认全量走网关、per-session 无意义(与 decideCodexRoute 的- // env-key 短路一致,内置三家保持旧行为)。例外:自定义(user)供应商和 host 注入鉴权的+ // oauth-bearer 态全量适用;env-key 态默认走网关,由 decideCodexRoute 换成当前网关 key。+ // 例外:自定义(user)供应商和 host 注入鉴权的// 供应商(provider-oauth-header 如 xAI、通用 Runner 的 oauth-token)必须按会话路由,// 因为它们的鉴权由 proxy 覆盖,不依赖 Codex 子进程凭证。if (sessionId && (@@ -3086,17 +3106,17 @@ export function createModelRoutingTransform(// spawn 时那把凭证 —— oauth-bearer 揣的 OAuth token 在网关无效(要 sk-)→ 401。// 故按 spawn 凭证回它的原生后端: oauth-bearer → ChatGPT 订阅后端(只 override 上游、透传 OAuth// token,等价 stock codex 订阅模式轮 /models 的去处); provider-oauth → 唯一 provider-oauth- // 供应商的上游/令牌(当前 xAI),避免把占位 key 打到网关; env-key → null(留默认网关, sk- key 本就有效)。+ // 供应商的上游/令牌(当前 xAI),避免把占位 key 打到网关; env-key → 默认网关,同样换成当前 key。// `!model` 这道闸确保真实 /responses(永远带 model)绝不落进此分支,杜绝注册时序竞争误伤推理请求。if (!sessionId && !model) {if (authInjection === 'oauth-bearer') return { upstreamOverride: CODEX_OAUTH_UPSTREAM };if (authInjection === 'provider-oauth') {return resolveProviderOAuthControlRouteDecision('codex', gatewayKey);}- return null;+ return decideCodexRoute({ model, authInjection, gatewayKey });}- // ② 未显式选供应商 → 回落默认路由(decideCodexRoute,与未升级行为字节级一致)。+ // ② 未显式选供应商 → 回落默认路由(decideCodexRoute)。const decision = decideCodexRoute({ model, authInjection, gatewayKey });// codex/ 折扣模型该走 gateway 换 key 但没配 key → null(passthrough), 上游大概率 401, 记一条诊断。if (decision === null && authInjection === 'oauth-bearer' && model