Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(codex): 修复 spawn_agent 首请求 Provider 继承 (#1591)
Xiantao Ge27e26eaf0f31
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.tsindex 06b0838812..8be9ebca75 100644--- a/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts+++ b/apps/desktop/src/main/maker-host/__tests__/codexProxyHost.test.ts@@ -1110,6 +1110,285 @@ describe('chatBridgeCapabilitiesForRoute', () => {}});+ it('routes the first collab_spawn request through its parent custom Responses provider', async () => {+ const host = await freshCodexProxyHost();+ 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: 'collab-spawn-provider',+ name: 'Collab Spawn Provider',+ runtimes: {+ codex: {+ baseUrl: 'https://collab-spawn.invalid/v1',+ models: [{ id: 'collab-spawn-model', name: 'Collab Spawn Model' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader(() => 'test-invalid-collab-spawn-key');+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-collab-parent', 'thread-collab-parent', 'PRODUCT_PROMPT');+ setSessionProvider('session-collab-parent', 'collab-spawn-provider');+ host.setCodexProxyAuthInjection('env-key');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'collab-spawn-model', input: [] },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-collab-child',+ 'x-openai-subagent': 'collab_spawn',+ 'x-codex-parent-thread-id': 'thread-collab-parent',+ },+ },+ ));++ expect(decision).toEqual({+ upstreamOverride: 'https://collab-spawn.invalid/v1',+ headerOverride: { authorization: 'Bearer test-invalid-collab-spawn-key' },+ headerDelete: ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'],+ });+ expect(mockState.capturedRegistry?.get('thread-collab-child')).toBe('PRODUCT_PROMPT');+ } finally {+ host.unregister('session-collab-parent');+ clearSessionProvider('session-collab-parent');+ setCustomProviderKeyReader(() => null);+ setCustomProviders([]);+ }+ });++ it('fails closed when a collab_spawn request cannot resolve its parent route', async () => {+ const host = await freshCodexProxyHost();+ const ctx = {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-collab-orphan',+ 'x-openai-subagent': 'collab_spawn',+ 'x-codex-parent-thread-id': 'thread-collab-missing-parent',+ },+ };++ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'collab-spawn-model', input: [] },+ ctx,+ ));++ expect(decision).toEqual({ localHandler: expect.any(Function) });+ if (!decision?.localHandler) throw new Error('missing unresolved collab_spawn route handler');++ const writeHead = vi.fn();+ const end = vi.fn();+ await decision.localHandler({+ rawBody: Buffer.alloc(0),+ parsedBody: { model: 'collab-spawn-model', input: [] },+ ctx,+ res: { writeHead, end } as never,+ });++ expect(writeHead).toHaveBeenCalledWith(503, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ });+ expect(JSON.parse(String(end.mock.calls[0]?.[0]))).toEqual({+ error: {+ type: 'server_error',+ code: 'cindy_codex_parent_route_unavailable',+ message: 'Cindy could not resolve the parent Provider route for this spawned Codex agent.',+ },+ });+ expect(mockState.capturedRegistry?.get('thread-collab-orphan')).toBeUndefined();+ });++ it('does not use a matching x-client-request-id as a collab_spawn child identity', async () => {+ const host = await freshCodexProxyHost();+ host.registerComposed('session-collab-parent', 'thread-collab-parent', 'PARENT_PROMPT');+ host.registerComposed('session-request-owner', 'request-collab-child', 'OWNER_PROMPT');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'collab-spawn-model', input: [] },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'x-client-request-id': 'request-collab-child',+ 'x-openai-subagent': 'collab_spawn',+ 'x-codex-parent-thread-id': 'thread-collab-parent',+ },+ },+ ));++ expect(decision).toEqual({ localHandler: expect.any(Function) });+ expect(host.registerChildThread('thread-collab-parent', 'request-collab-child')).toBe(false);+ } finally {+ host.unregister('session-collab-parent');+ host.unregister('session-request-owner');+ }+ });++ it('keeps an already-owned collab_spawn child on its existing session route', async () => {+ const host = await freshCodexProxyHost();+ 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: 'collab-parent-provider',+ name: 'Collab Parent Provider',+ runtimes: {+ codex: {+ baseUrl: 'https://collab-parent.invalid/v1',+ models: [{ id: 'shared-collab-model', name: 'Shared Collab Model' }],+ },+ },+ }),+ buildUserProvider({+ id: 'collab-owner-provider',+ name: 'Collab Owner Provider',+ runtimes: {+ codex: {+ baseUrl: 'https://collab-owner.invalid/v1',+ models: [{ id: 'shared-collab-model', name: 'Shared Collab Model' }],+ },+ },+ }),+ ]);+ setCustomProviderKeyReader((providerId) => `test-invalid-${providerId}-key`);+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-collab-parent', 'thread-collab-parent', 'PARENT_PROMPT');+ host.registerComposed('session-collab-owner', 'thread-collab-owned', 'OWNER_PROMPT');+ setSessionProvider('session-collab-parent', 'collab-parent-provider');+ setSessionProvider('session-collab-owner', 'collab-owner-provider');+ host.setCodexProxyAuthInjection('env-key');++ try {+ const decision = await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'shared-collab-model', input: [] },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-collab-owned',+ 'x-openai-subagent': 'collab_spawn',+ 'x-codex-parent-thread-id': 'thread-collab-parent',+ },+ },+ ));++ expect(decision).toEqual({+ upstreamOverride: 'https://collab-owner.invalid/v1',+ headerOverride: { authorization: 'Bearer test-invalid-collab-owner-provider-key' },+ headerDelete: ['chatgpt-account-id', 'openai-beta', 'originator', 'session_id'],+ });+ expect(mockState.capturedRegistry?.get('thread-collab-owned')).toBe('OWNER_PROMPT');+ } finally {+ host.unregister('session-collab-parent');+ host.unregister('session-collab-owner');+ clearSessionProvider('session-collab-parent');+ clearSessionProvider('session-collab-owner');+ setCustomProviderKeyReader(() => null);+ setCustomProviders([]);+ }+ });++ const rejectedLazyInheritanceRequests: Array<{+ name: string;+ childThreadId: string;+ headers: Readonly<Record<string, string>>;+ }> = [+ {+ name: 'non-spawn request',+ childThreadId: 'thread-review-child',+ headers: {+ 'thread-id': 'thread-review-child',+ 'x-openai-subagent': 'review',+ 'x-codex-parent-thread-id': 'thread-collab-parent',+ },+ },+ {+ name: 'request id without a thread id',+ childThreadId: 'request-collab-child',+ headers: {+ 'x-client-request-id': 'request-collab-child',+ 'x-openai-subagent': 'collab_spawn',+ 'x-codex-parent-thread-id': 'thread-collab-parent',+ },+ },+ ];++ it.each(rejectedLazyInheritanceRequests)(+ 'does not lazily inherit the parent for a $name',+ async ({ childThreadId, headers }) => {+ const host = await freshCodexProxyHost();+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-collab-parent', 'thread-collab-parent', 'PARENT_PROMPT');++ try {+ await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'gpt-5.6', input: [] },+ { reqId: 1, method: 'POST', url: '/responses', headers },+ ));++ expect(mockState.capturedRegistry?.get(childThreadId)).toBeUndefined();+ } finally {+ host.unregister('session-collab-parent');+ }+ },+ );++ it('does not register a Guardian request as a prompt-inheriting child thread', async () => {+ const host = await freshCodexProxyHost();+ mockState.createAnthropicCompatProxy.mockResolvedValueOnce({+ url: 'http://127.0.0.1:43210',+ dispose: vi.fn(async () => undefined),+ });+ await host.ensureCodexProxyReady();+ host.registerComposed('session-guardian-parent', 'thread-guardian-parent', 'PRODUCT_PROMPT');++ try {+ await Promise.resolve(host.createModelRoutingTransform()(+ { model: 'codex-auto-review', input: [] },+ {+ reqId: 1,+ method: 'POST',+ url: '/responses',+ headers: {+ 'thread-id': 'thread-guardian-child',+ 'x-openai-subagent': 'guardian',+ 'x-codex-parent-thread-id': 'thread-guardian-parent',+ },+ },+ ));++ expect(mockState.capturedRegistry?.get('thread-guardian-child')).toBeUndefined();+ } finally {+ host.unregister('session-guardian-parent');+ }+ });+it('does not overwrite a child thread that is already owned by another session', async () => {const host = await freshCodexProxyHost();host.registerComposed('session-parent', 'thread-parent', 'PARENT_PROMPT');diff --git a/apps/desktop/src/main/maker-host/codex-proxy-host.ts b/apps/desktop/src/main/maker-host/codex-proxy-host.tsindex b185afb200..aa1ffecca6 100644--- a/apps/desktop/src/main/maker-host/codex-proxy-host.ts+++ b/apps/desktop/src/main/maker-host/codex-proxy-host.ts@@ -87,6 +87,8 @@ const httpRecoveryReasonByThread = new Map<string, string>();const CODEX_AUTO_REVIEW_MODEL = 'codex-auto-review';const CODEX_GUARDIAN_SUBAGENT = 'guardian';+const CODEX_COLLAB_SPAWN_SUBAGENT = 'collab_spawn';+const CODEX_COLLAB_ROUTE_UNAVAILABLE_CODE = 'cindy_codex_parent_route_unavailable';let _handle: ProxyHandle | null = null;let _startPromise: Promise<void> | null = null;@@ -242,12 +244,53 @@ function guardianParentThreadIdFromHeaders(return headerValue(headers, 'x-codex-parent-thread-id');}+function isCollabSpawnRequest(headers: Readonly<Record<string, string>>): boolean {+ return headerValue(headers, 'x-openai-subagent').toLowerCase() === CODEX_COLLAB_SPAWN_SUBAGENT;+}+function sessionIdFromHeaders(headers: Readonly<Record<string, string>>,): string | undefined {const parentThreadId = guardianParentThreadIdFromHeaders(headers);if (parentThreadId) return threadToSession.get(parentThreadId);- return threadToSession.get(selectedThreadIdFromHeaders(headers));++ const collabSpawn = isCollabSpawnRequest(headers);+ const selectedThreadId = collabSpawn+ ? headerValue(headers, 'thread-id')+ : selectedThreadIdFromHeaders(headers);+ const existingSessionId = threadToSession.get(selectedThreadId);+ if (existingSessionId) return existingSessionId;++ // Codex can send a spawned child's first request before thread/started reaches+ // the host. Only that explicit spawn request may lazily inherit its parent;+ // request ids and unrelated parent headers are not stable thread identities.+ if (!collabSpawn) {+ return undefined;+ }+ const childThreadId = selectedThreadId;+ const collabParentThreadId = headerValue(headers, 'x-codex-parent-thread-id');+ if (!childThreadId || !collabParentThreadId) return undefined;++ registerChildThread(collabParentThreadId, childThreadId);+ return threadToSession.get(childThreadId);+}++function unresolvedCollabSpawnRouteDecision(): RoutingDecision {+ return {+ localHandler: async ({ res }) => {+ res.writeHead(503, {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': 'no-store',+ });+ res.end(JSON.stringify({+ error: {+ type: 'server_error',+ code: CODEX_COLLAB_ROUTE_UNAVAILABLE_CODE,+ message: 'Cindy could not resolve the parent Provider route for this spawned Codex agent.',+ },+ }));+ },+ };}function safeDumpName(threadId: string): string {@@ -2102,6 +2145,9 @@ export function createModelRoutingTransform(requestModel;const threadId = selectedThreadIdFromHeaders(ctx.headers);const sessionId = sessionIdFromHeaders(ctx.headers);+ if (!sessionId && isCollabSpawnRequest(ctx.headers)) {+ return unresolvedCollabSpawnRouteDecision();+ }const explicitProviderId = sessionId ? getSessionProvider(sessionId) : null;const selectedRouting = sessionId? getSessionRoutingDescriptor(sessionId, 'codex', model || undefined)@@ -2569,7 +2615,8 @@ export function registerReviewerRouteContext(/*** 让 Codex 子 Agent thread 继承父 thread 的业务 session、桥接路由和产品 prompt。- * app-server 的 thread/started 通知在子 thread 首个请求前同步调用这里。+ * app-server 的 thread/started 通知和子 thread 首个 collab_spawn 请求都可以+ * 幂等地调用这里,避免两者乱序时丢失路由。*/export function registerChildThread(parentThreadId: string, childThreadId: string): boolean {if (!parentThreadId || !childThreadId || parentThreadId === childThreadId) return false;