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。

feat(desktop): 复用 ChatGPT 订阅账号生成图片 (#1249)

Chris Zhang1d83a7149a90
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.ts
index b400923d92..bc2721f142 100644
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@ -432,6 +432,10 @@ import {
hasGrokOAuthLogin,
} from './maker-host/grok-oauth-login.js';
import { setXaiAuthInvalidatedHandler } from './maker-host/xai-auth-invalidation-host.js';
+import {
+ getChatgptBridgeAuth,
+ invalidateChatgptBridgeAuth,
+} from './maker-host/anthropic-responses-bridge-host.js';
import {
readSilentEncryptedRetrySettingsState,
resetSilentEncryptedRetrySettings,
@@ -621,6 +625,7 @@ import {
suspendAllGhosts,
waitForGhostMutations,
} from './cindy-brain/index.js';
+import { setCodexImageAuthBinding } from './cindy-brain/codexImageAuthBinding.js';
import { listActiveClaudeBackgroundActivitySessions } from './maker-host/claude-session-background-activity.js';
import { registerRelaunchBusyActivityIpc } from './relaunchBusyActivityIpc.js';
import { getGhostSetupChangeBus } from './cindy-brain/ghostSetupChangeBus.js';
@@ -1223,6 +1228,12 @@ registerLayoutIpc();
// ── 意识仓库 IPC──────────────────────────────────────────────────────
// renderer 首帧 sendSync 拉已装意识清单(意识面板与内置面板同帧注册,规则 7
// 无跳变)、install/uninstall 写路径、changed 广播。见 main/cindy-brain/。
+// 图片通道的 ChatGPT 鉴权必须由 Main 静态装配;禁止在请求时 import maker-host
+// 生成延迟 chunk(Main bundle 反向 require 会重复执行启动副作用)。
+setCodexImageAuthBinding({
+ getAuth: getChatgptBridgeAuth,
+ onAuthFailure: invalidateChatgptBridgeAuth,
+});
registerGhostIpc();
registerPluginMarketIpc();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.ts
new file mode 100644
index 0000000000..d7e37f08a0
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/codexImageAuthBinding.test.ts
@@ -0,0 +1,52 @@
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { getCodexImageAuthBinding, setCodexImageAuthBinding } from '../codexImageAuthBinding.js';
+
+afterEach(() => setCodexImageAuthBinding(null));
+
+describe('codexImageAuthBinding', () => {
+ it('fail closed before assembly and returns the statically injected callbacks', async () => {
+ expect(() => getCodexImageAuthBinding()).toThrow('not configured');
+
+ const getAuth = vi.fn(async () => ({ accessToken: 'fake-token', accountId: 'fake-account' }));
+ const onAuthFailure = vi.fn(async () => true);
+ setCodexImageAuthBinding({ getAuth, onAuthFailure });
+
+ await expect(getCodexImageAuthBinding().getAuth()).resolves.toEqual({
+ accessToken: 'fake-token',
+ accountId: 'fake-account',
+ });
+ expect(getAuth).toHaveBeenCalledOnce();
+ await getCodexImageAuthBinding().onAuthFailure({
+ status: 401,
+ body: 'token_invalidated',
+ failedAccessToken: 'fake-token',
+ });
+ expect(onAuthFailure).toHaveBeenCalledOnce();
+ });
+
+ it('bootstrap statically injects auth before Ghost IPC registration', () => {
+ const bootstrap = fs.readFileSync(
+ path.resolve(process.cwd(), 'src/main/bootstrap-electron.ts'),
+ 'utf-8',
+ );
+ const brain = fs.readFileSync(
+ path.resolve(process.cwd(), 'src/main/cindy-brain/index.ts'),
+ 'utf-8',
+ );
+
+ expect(bootstrap).toContain("from './maker-host/anthropic-responses-bridge-host.js';");
+ expect(bootstrap).toContain('getChatgptBridgeAuth,');
+ expect(bootstrap).toContain('invalidateChatgptBridgeAuth,');
+ expect(bootstrap.indexOf('setCodexImageAuthBinding({')).toBeGreaterThan(-1);
+ expect(bootstrap.indexOf('setCodexImageAuthBinding({')).toBeLessThan(
+ bootstrap.indexOf('registerGhostIpc();'),
+ );
+ expect(brain).not.toMatch(
+ /import\(\s*['"]\.\.\/maker-host\/anthropic-responses-bridge-host\.js['"]\s*\)/,
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.ts
new file mode 100644
index 0000000000..681edee4b8
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.ts
@@ -0,0 +1,180 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createCodexImageChannel } from '../codexImageClient.js';
+
+function sseResponse(events: unknown[], status = 200): Response {
+ const body =
+ events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join('') + 'data: [DONE]\n\n';
+ return new Response(body, { status, headers: { 'Content-Type': 'text/event-stream' } });
+}
+
+function makeChannel(
+ fetchImplementation: typeof fetch,
+ beforeDispatch?: (model: string) => void,
+ onAuthFailure?: Parameters<typeof createCodexImageChannel>[0]['onAuthFailure'],
+) {
+ return createCodexImageChannel({
+ hasOAuthLogin: () => true,
+ getAuth: async () => ({ accessToken: 'oauth-token', accountId: 'account-id' }),
+ fetchImplementation,
+ beforeDispatch,
+ onAuthFailure,
+ });
+}
+
+describe('codexImageClient', () => {
+ it('用 Codex OAuth hosted image_generation tool 生成 gpt-image-2', async () => {
+ const doFetch = vi.fn<typeof fetch>(async () =>
+ sseResponse([
+ {
+ type: 'response.output_item.done',
+ item: { type: 'image_generation_call', result: 'aW1hZ2U=' },
+ },
+ ]),
+ );
+ const channel = makeChannel(doFetch);
+ const result = await channel.generateImage({
+ model: 'openai/gpt-image-2',
+ prompt: '一只猫',
+ aspectRatio: '3:2',
+ });
+
+ expect(result.data[0]?.b64_json).toBe('aW1hZ2U=');
+ const [url, init] = doFetch.mock.calls[0]!;
+ expect(String(url)).toBe('https://chatgpt.com/backend-api/codex/responses');
+ expect((init?.headers as Record<string, string>)['ChatGPT-Account-Id']).toBe('account-id');
+ const body = JSON.parse(String(init?.body)) as {
+ tools: Array<Record<string, unknown>>;
+ tool_choice?: unknown;
+ };
+ expect(body.tools).toContainEqual(
+ expect.objectContaining({
+ type: 'image_generation',
+ model: 'gpt-image-2',
+ size: '1536x1024',
+ quality: 'medium',
+ }),
+ );
+ expect(body.tool_choice).toBeUndefined();
+ });
+
+ it('未指定画幅时保留 auto 语义;拒绝目录外模型', async () => {
+ const doFetch = vi.fn<typeof fetch>(async () =>
+ sseResponse([{ type: 'image_generation_call', result: 'aW1hZ2U=' }]),
+ );
+ const channel = makeChannel(doFetch);
+ await channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' });
+ const body = JSON.parse(String(doFetch.mock.calls[0]?.[1]?.body)) as {
+ tools: Array<Record<string, unknown>>;
+ };
+ expect(body.tools[0]).not.toHaveProperty('size');
+
+ await expect(
+ channel.generateImage({ model: 'openai/future-image', prompt: 'p' }),
+ ).rejects.toThrow('不支持模型');
+ expect(doFetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('保留流中最新 partial image;派发前重查可阻止出网', async () => {
+ const doFetch = vi.fn<typeof fetch>(async () =>
+ sseResponse([{ partial_image_b64: 'first' }, { partial_image_b64: 'final' }]),
+ );
+ const channel = makeChannel(doFetch);
+ expect(
+ (await channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' })).data[0]?.b64_json,
+ ).toBe('final');
+
+ const blockedFetch = vi.fn<typeof fetch>();
+ const blocked = makeChannel(blockedFetch, () => {
+ throw new Error('模型已停用');
+ });
+ await expect(
+ blocked.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),
+ ).rejects.toThrow('模型已停用');
+ expect(blockedFetch).not.toHaveBeenCalled();
+ });
+
+ it('兼容 CRLF、无尾空行和坏帧,并释放 reader lock', async () => {
+ const releaseLock = vi.spyOn(ReadableStreamDefaultReader.prototype, 'releaseLock');
+ const body = [
+ 'data: {bad json}\r\n\r\n',
+ `data: ${JSON.stringify({ partial_image_b64: 'crlf' })}\r\n\r\n`,
+ `data: ${JSON.stringify({ type: 'image_generation_call', result: 'unterminated' })}`,
+ ].join('');
+ const channel = makeChannel(
+ vi.fn<typeof fetch>(
+ async () =>
+ new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
+ ),
+ );
+
+ try {
+ await expect(
+ channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),
+ ).resolves.toMatchObject({ data: [{ b64_json: 'unterminated' }] });
+ expect(releaseLock).toHaveBeenCalled();
+ } finally {
+ releaseLock.mockRestore();
+ }
+ });
+
+ it('兼容单 CR 的 SSE 事件与行结束符', async () => {
+ const body = [
+ 'data: {bad json}\r\r',
+ `data: ${JSON.stringify({ partial_image_b64: 'cr-only' })}\r\r`,
+ 'data: [DONE]\r\r',
+ ].join('');
+ const channel = makeChannel(
+ vi.fn<typeof fetch>(
+ async () =>
+ new Response(body, { status: 200, headers: { 'Content-Type': 'text/event-stream' } }),
+ ),
+ );
+
+ await expect(
+ channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),
+ ).resolves.toMatchObject({ data: [{ b64_json: 'cr-only' }] });
+ });
+
+ it('把认证失败与本次 token 交给失效协调器,且不让协调器异常覆盖 HTTP 错误', async () => {
+ const raw = '{"error":{"code":"token_invalidated"}}';
+ const onAuthFailure = vi.fn(async () => {
+ throw new Error('invalidation failed');
+ });
+ const channel = makeChannel(
+ vi.fn<typeof fetch>(async () => new Response(raw, { status: 401 })),
+ undefined,
+ onAuthFailure,
+ );
+
+ await expect(
+ channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),
+ ).rejects.toThrow('HTTP 401');
+ expect(onAuthFailure).toHaveBeenCalledWith({
+ status: 401,
+ body: raw,
+ failedAccessToken: 'oauth-token',
+ });
+ });
+
+ it('登录态决定 ready;缺 token 与空图片响应明确失败', async () => {
+ const unavailable = createCodexImageChannel({
+ hasOAuthLogin: () => false,
+ getAuth: async () => {
+ throw new Error('OpenAI 订阅登录已失效,请重新登录');
+ },
+ fetchImplementation: vi.fn<typeof fetch>(),
+ });
+ expect(unavailable.ready()).toBe(false);
+ await expect(
+ unavailable.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),
+ ).rejects.toThrow('重新登录');
+
+ const empty = makeChannel(
+ vi.fn<typeof fetch>(async () => sseResponse([{ type: 'response.completed' }])),
+ );
+ await expect(empty.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' })).rejects.toThrow(
+ '没有图片',
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/codexImageAuthBinding.ts b/apps/desktop/src/main/cindy-brain/codexImageAuthBinding.ts
new file mode 100644
index 0000000000..02b8d88374
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/codexImageAuthBinding.ts
@@ -0,0 +1,30 @@
+/**
+ * Static assembly seam for the ChatGPT subscription image channel.
+ *
+ * cindy-brain must not runtime-import the full maker-host auth graph: Rollup would
+ * emit a lazy chunk that can re-enter the Desktop Main bundle. bootstrap-electron
+ * wires these callbacks from its existing static maker-host imports before IPC
+ * registration, while tests can exercise the image channel without that graph.
+ */
+
+export interface CodexImageAuthBinding {
+ getAuth(): Promise<{ accessToken: string; accountId: string | null }>;
+ onAuthFailure(failure: {
+ status: number;
+ body: string;
+ failedAccessToken: string;
+ }): unknown | Promise<unknown>;
+}
+
+let binding: CodexImageAuthBinding | null = null;
+
+export function setCodexImageAuthBinding(next: CodexImageAuthBinding | null): void {
+ binding = next;
+}
+
+export function getCodexImageAuthBinding(): CodexImageAuthBinding {
+ if (!binding) {
+ throw new Error('Codex image auth binding is not configured');
+ }
+ return binding;
+}
diff --git a/apps/desktop/src/main/cindy-brain/codexImageClient.ts b/apps/desktop/src/main/cindy-brain/codexImageClient.ts
new file mode 100644
index 0000000000..527ccc13da
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/codexImageClient.ts
@@ -0,0 +1,204 @@
+/**
+ * ChatGPT/Codex OAuth image channel.
+ *
+ * The subscription token cannot call the public Platform Images API. It can,
+ * however, call the Codex Responses surface and expose `gpt-image-2` through
+ * the hosted `image_generation` tool. Keep the token in Main and parse the raw
+ * SSE stream because image-generation events may be newer than SDK typings.
+ */
+
+import fs from 'node:fs/promises';
+
+import type { ImageChannel, ImageChannelResult } from './imageChannelRegistry.js';
+import { sniffMediaMime } from '../cindy-media/sniffMediaMime.js';
+import { createLogger } from '../logger.js';
+
+const CODEX_RESPONSES_URL = 'https://chatgpt.com/backend-api/codex/responses';
+const HOST_MODEL = 'gpt-5.5';
+const IMAGE_MODEL = 'gpt-image-2';
+const USER_AGENT = `codex_cli_rs/cindy (${process.platform}; ${process.arch})`;
+const SSE_EVENT_BOUNDARY = /(?:\r\n|\r|\n){2}/;
+const SSE_LINE_ENDING = /\r\n|\r|\n/;
+const log = createLogger('codex-image');
+const SIZE_BY_ASPECT = {
+ '1:1': '1024x1024',
+ '3:2': '1536x1024',
+ '2:3': '1024x1536',
+} as const;
+
+export interface CreateCodexImageChannelOptions {
+ hasOAuthLogin(): boolean;
+ getAuth(): Promise<{ accessToken: string; accountId: string | null }>;
+ /** Best-effort handoff to the shared token-aware invalidation coordinator. */
+ onAuthFailure?(failure: {
+ status: number;
+ body: string;
+ failedAccessToken: string;
+ }): void | Promise<void>;
+ fetchImplementation?: typeof fetch;
+ beforeDispatch?(model: string): void;
+}
+
+function extractImageB64(value: unknown): string | null {
+ if (Array.isArray(value)) {
+ for (const item of value) {
+ const found = extractImageB64(item);
+ if (found) return found;
+ }
+ return null;
+ }
+ if (!value || typeof value !== 'object') return null;
+ const item = value as Record<string, unknown>;
+ if (item.type === 'image_generation_call' && typeof item.result === 'string') return item.result;
+ if (typeof item.partial_image_b64 === 'string') return item.partial_image_b64;
+ for (const child of Object.values(item)) {
+ const found = extractImageB64(child);
+ if (found) return found;
+ }
+ return null;
+}
+
+async function collectImageB64(response: Response): Promise<string | null> {
+ if (!response.body) return null;
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ let buffer = '';
+ let latest: string | null = null;
+
+ const consume = (block: string): void => {
+ const data = block
+ .split(SSE_LINE_ENDING)
+ .filter((line) => line.startsWith('data:'))
+ .map((line) => line.slice(5).trimStart())
+ .join('\n');
+ if (!data || data === '[DONE]') return;
+ try {
+ const found = extractImageB64(JSON.parse(data) as unknown);
+ if (found) latest = found;
+ } catch {
+ // SSE 允许夹杂未知事件;坏帧不能让后续合法图片结果一起丢失。
+ }
+ };
+
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (value) buffer += decoder.decode(value, { stream: !done });
+ if (done) buffer += decoder.decode();
+ let match = SSE_EVENT_BOUNDARY.exec(buffer);
+ while (match?.index !== undefined) {
+ consume(buffer.slice(0, match.index));
+ buffer = buffer.slice(match.index + match[0].length);
+ match = SSE_EVENT_BOUNDARY.exec(buffer);
+ }
+ if (done) {
+ if (buffer.trim()) consume(buffer);
+ break;
+ }
+ }
+ } finally {
+ reader.releaseLock();
+ }
+ return latest;
+}
+
+async function inputImage(path: string): Promise<{ type: 'input_image'; image_url: string }> {
+ const bytes = await fs.readFile(path);
+ const mime = sniffMediaMime(bytes);
+ if (!mime || !['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(mime)) {
+ throw new Error(`OpenAI 参考图格式不支持:${mime ?? '未知格式'}`);
+ }
+ return { type: 'input_image', image_url: `data:${mime};base64,${bytes.toString('base64')}` };
+}
+
+async function httpError(
+ response: Response,
+ failedAccessToken: string,
+ onAuthFailure: CreateCodexImageChannelOptions['onAuthFailure'],
+): Promise<never> {
+ const raw = await response.text().catch(() => '');
+ try {
+ await onAuthFailure?.({ status: response.status, body: raw, failedAccessToken });
+ } catch (err) {
+ // 失效态协调失败不能覆盖用户真正收到的上游 HTTP 错误,也不能记录 token。
+ log.warn('Codex image auth invalidation failed', {
+ error: err instanceof Error ? err.message : String(err),
+ });
+ }
+ let detail = raw.slice(0, 500);
+ try {
+ const parsed = JSON.parse(raw) as { error?: { message?: unknown } };
+ if (typeof parsed.error?.message === 'string') detail = parsed.error.message.slice(0, 500);
+ } catch {
+ /* keep bounded raw body */
+ }
+ throw new Error(`Codex 图像请求失败(HTTP ${response.status}):${detail || '未知错误'}`);
+}
+
+export function createCodexImageChannel(opts: CreateCodexImageChannelOptions): ImageChannel {
+ const doFetch = opts.fetchImplementation ?? fetch;
+
+ async function generate(params: {
+ model: string;
+ prompt: string;
+ imagePaths?: string[];
+ aspectRatio?: '1:1' | '3:2' | '2:3';
+ }): Promise<ImageChannelResult> {
+ if (params.model !== `openai/${IMAGE_MODEL}`) {
+ throw new Error(`Codex 图像通道不支持模型:${params.model}`);
+ }
+ // 先在 token 刷新 / 本地参考图读取之前拦停,后面的二次检查继续覆盖
+ // 准备请求期间发生的模型停用。
+ opts.beforeDispatch?.(params.model);
+ const [auth, images] = await Promise.all([
+ opts.getAuth(),
+ Promise.all((params.imagePaths ?? []).map(inputImage)),
+ ]);
+ opts.beforeDispatch?.(params.model);
+ const content: Array<Record<string, unknown>> = [
+ { type: 'input_text', text: params.prompt },
+ ...images,
+ ];
+ const response = await doFetch(CODEX_RESPONSES_URL, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${auth.accessToken}`,
+ 'Content-Type': 'application/json',
+ Accept: 'text/event-stream',
+ 'OpenAI-Beta': 'responses=experimental',
+ originator: 'codex_cli_rs',
+ 'User-Agent': USER_AGENT,
+ ...(auth.accountId ? { 'ChatGPT-Account-Id': auth.accountId } : {}),
+ },
+ body: JSON.stringify({
+ model: HOST_MODEL,
+ store: false,
+ stream: true,
+ instructions: 'Use the image_generation tool to fulfill this image request.',
+ input: [{ type: 'message', role: 'user', content }],
+ tools: [
+ {
+ type: 'image_generation',
+ model: IMAGE_MODEL,
+ ...(params.aspectRatio ? { size: SIZE_BY_ASPECT[params.aspectRatio] } : {}),
+ quality: 'medium',
+ output_format: 'png',
+ background: 'opaque',
+ partial_images: 1,
+ },
+ ],
+ }),
+ });
+ if (!response.ok) await httpError(response, auth.accessToken, opts.onAuthFailure);
+ const b64 = await collectImageB64(response);
+ if (!b64) throw new Error('Codex 返回中没有图片,请重试或改用 OpenAI Platform API key');
+ return { data: [{ b64_json: b64 }], output_format: 'png' };
+ }
+
+ return {
+ ready: opts.hasOAuthLogin,
+ generateImage: ({ model, prompt, aspectRatio }) => generate({ model, prompt, aspectRatio }),
+ editImage: ({ model, prompt, imagePaths, aspectRatio }) =>
+ generate({ model, prompt, imagePaths, aspectRatio }),
+ };
+}
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index bfd105944e..730f36b7f0 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -183,6 +183,7 @@ import { projectProviderCatalogForBuildRegion } from '../maker-host/provider-acc
import { isModelDisabled, isProviderDisabled } from '@cindy/model-providers';
import { readModelDisableOverrides } from '../maker-host/model-disable-store.js';
import { outboundFetch } from '../maker-host/outbound-fetch.js';
+import { hasCodexOAuthLoginReadOnly } from '../maker-host/codex-oauth-readiness.js';
import { getUtilityModelChainProfiles } from '../utility-model/UtilityModelSelection.js';
import { utilityModelPinOptions } from '../../shared/utilityModelProfiles.js';
import {
@@ -205,6 +206,8 @@ import {
import { getCindyProxyMediaService } from '../mcp-integrations/cindyProxyMedia.js';
import { ImageChannelRegistry, decodeImageResponse } from './imageChannelRegistry.js';
import { createGeminiImageChannel } from './geminiImageClient.js';
+import { createCodexImageChannel } from './codexImageClient.js';
+import { getCodexImageAuthBinding } from './codexImageAuthBinding.js';
import { createGatewayImageClient } from '../cindy-proxy-media/api/gatewayImageClient.js';
import * as blobStore from '../cindy-media/blobStore.js';
import * as ledger from '../cindy-media/ledger.js';
@@ -1957,10 +1960,9 @@ function getImageChannelRegistry(): ImageChannelRegistry {
fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),
}));
- // OpenAI 平台 images API(BYO 平台 key;ChatGPT 订阅 OAuth 调不了平台面,实测
- // 401/403 缺 scope):与 xd 网关同 wire(OpenAI-images 兼容面),整个客户端复用,
- // 只换 baseUrl/品牌话术/凭证读取。目录 id 带 openai/ 前缀(跨供应商契约),
- // 上游只认裸 id,适配层剥前缀。
+ // OpenAI public Images API(BYO 平台 key):与 xd 网关同 wire,整个客户端复用,
+ // 只换 baseUrl/品牌话术/凭证读取。ChatGPT/Codex 订阅走下方独立的 hosted-tool
+ // 通道;目录 id 带 openai/ 前缀,public API 适配层剥前缀。
const openaiImagesClient = createGatewayImageClient({
getApiKey: () => getProviderSecretStore().get('openai-images'),
// 境外端点吃系统代理(outboundFetch):main 的裸 fetch 不读系统代理设置,
@@ -1979,22 +1981,38 @@ function getImageChannelRegistry(): ImageChannelRegistry {
});
const stripOpenaiPrefix = (id: string) =>
id.startsWith('openai/') ? id.slice('openai/'.length) : id;
+ const hasOpenaiPlatformKey = () =>
+ (getProviderSecretStore().get('openai-images')?.trim() ?? '') !== '';
+ const codexImagesClient = createCodexImageChannel({
+ hasOAuthLogin: hasCodexOAuthLoginReadOnly,
+ getAuth: () => getCodexImageAuthBinding().getAuth(),
+ onAuthFailure: async (failure) => {
+ await getCodexImageAuthBinding().onAuthFailure(failure);
+ },
+ fetchImplementation: ((url, init) => outboundFetch(url as string, init)) as typeof fetch,
+ beforeDispatch: (model) => assertMediaModelStillEnabled('image', model),
+ });
registry.register('openai', {
- // trim-nonempty 与 gemini 通道同口径:空白 key 不算就绪。
- ready: () => (getProviderSecretStore().get('openai-images')?.trim() ?? '') !== '',
- generateImage: ({ model, prompt, aspectRatio }) =>
- openaiImagesClient.generateImage({
- model: stripOpenaiPrefix(model),
- prompt,
- ...(aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[aspectRatio] } : {}),
- }),
- editImage: ({ model, prompt, imagePaths, aspectRatio }) =>
- openaiImagesClient.editImage({
- model: stripOpenaiPrefix(model),
- prompt,
- imagePaths,
- ...(aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[aspectRatio] } : {}),
- }),
+ // 用户明确配置 Platform key 时优先走确定性的 public Images API;否则复用
+ // 已连接的 ChatGPT/Codex 订阅 OAuth hosted tool,不要求再付一份 API 费。
+ ready: () => hasOpenaiPlatformKey() || codexImagesClient.ready(),
+ generateImage: (params) =>
+ hasOpenaiPlatformKey()
+ ? openaiImagesClient.generateImage({
+ model: stripOpenaiPrefix(params.model),
+ prompt: params.prompt,
+ ...(params.aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[params.aspectRatio] } : {}),
+ })
+ : codexImagesClient.generateImage(params),
+ editImage: (params) =>
+ hasOpenaiPlatformKey()
+ ? openaiImagesClient.editImage({
+ model: stripOpenaiPrefix(params.model),
+ prompt: params.prompt,
+ imagePaths: params.imagePaths,
+ ...(params.aspectRatio ? { size: GHOST_ASPECT_TO_GATEWAY_SIZE[params.aspectRatio] } : {}),
+ })
+ : codexImagesClient.editImage(params),
});
imageChannelRegistrySingleton = registry;
}
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
index 993377657d..fd9e225f54 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codexAuthInvalidation.test.ts
@@ -150,6 +150,24 @@ describe('Codex system credential suppression marker', () => {
expect(fs.existsSync(localAuth)).toBe(false);
});
+ it('suppresses a matching local credential after server-side token invalidation', () => {
+ const { codexHome, systemAuth, localAuth } = fixture();
+ fs.mkdirSync(codexHome, { recursive: true });
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'invalid-token' } }));
+ expect(
+ writeInvalidatedSystemCodexAuthMarker(
+ codexHome,
+ systemAuth,
+ 'token_invalidated',
+ localAuth,
+ ),
+ ).toBe(true);
+
+ expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(true);
+ fs.writeFileSync(localAuth, JSON.stringify({ tokens: { access_token: 'new-token' } }));
+ expect(shouldSuppressLocalCodexAuth(codexHome, localAuth)).toBe(false);
+ });
+
it('blocks every token read when a Windows lock leaves the disconnected local file behind', async () => {
const { codexHome: fixtureCodexHome, systemAuth } = fixture();
h.userDataDir = path.join(path.dirname(fixtureCodexHome), 'user-data');
diff --git a/apps/desktop/src/main/maker-host/__tests__/codexOauthReadiness.test.ts b/apps/desktop/src/main/maker-host/__tests__/codexOauthReadiness.test.ts
new file mode 100644
index 0000000000..a969200f99
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/__tests__/codexOauthReadiness.test.ts
@@ -0,0 +1,57 @@
+import fs from 'node:fs/promises';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const h = vi.hoisted(() => ({
+ bound: true,
+ suppressed: false,
+ userData: '',
+}));
+
+vi.mock('electron', () => ({ app: { getPath: () => h.userData } }));
+vi.mock('../nativeProviderAuthBinding.js', () => ({
+ isNativeProviderAuthBound: () => h.bound,
+}));
+vi.mock('../codex-auth-invalidation.js', () => ({
+ shouldSuppressLocalCodexAuth: () => h.suppressed,
+}));
+
+import { hasCodexOAuthLoginReadOnly } from '../codex-oauth-readiness.js';
+
+const authPath = () => path.join(h.userData, 'codex-home', 'auth.json');
+
+beforeEach(async () => {
+ h.bound = true;
+ h.suppressed = false;
+ h.userData = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-codex-oauth-readiness-'));
+ await fs.mkdir(path.dirname(authPath()), { recursive: true });
+ await fs.writeFile(authPath(), JSON.stringify({ tokens: { access_token: 'oauth-token' } }));
+});
+
+afterEach(async () => {
+ await fs.rm(h.userData, { recursive: true, force: true });
+ h.userData = '';
+});
+
+describe('hasCodexOAuthLoginReadOnly', () => {
+ it('仅在当前 owner 已绑定且本地 token 未被抑制时返回 true', () => {
+ expect(hasCodexOAuthLoginReadOnly()).toBe(true);
+
+ h.bound = false;
+ expect(hasCodexOAuthLoginReadOnly()).toBe(false);
+ h.bound = true;
+ h.suppressed = true;
+ expect(hasCodexOAuthLoginReadOnly()).toBe(false);
+ });
+
+ it('auth 文件缺失、损坏或 token 为空时 fail-closed', async () => {
+ await fs.writeFile(authPath(), '{bad json');
+ expect(hasCodexOAuthLoginReadOnly()).toBe(false);
+ await fs.writeFile(authPath(), JSON.stringify({ tokens: { access_token: '' } }));
+ expect(hasCodexOAuthLoginReadOnly()).toBe(false);
+ await fs.rm(authPath());
+ expect(hasCodexOAuthLoginReadOnly()).toBe(false);
+ });
+});
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 ec6ab30089..eec7efbaa7 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
@@ -210,7 +210,7 @@ export function clearChatgptBridgeCredentialCache(): void {
_authCache = null;
}
-const invalidateChatgptBridgeAuth = createChatgptBridgeAuthInvalidator({
+export const invalidateChatgptBridgeAuth = createChatgptBridgeAuthInvalidator({
getCurrentAccessToken: () => desktopCodexAuthAdapter.getAccessToken(),
invalidate: async (reason) => {
clearChatgptBridgeCredentialCache();
diff --git a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
index 57cf426e3f..8e3fd0ba74 100644
--- a/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
+++ b/apps/desktop/src/main/maker-host/codex-auth-invalidation.ts
@@ -263,17 +263,13 @@ export function writeInvalidatedSystemCodexAuthMarker(
}
}
-/** durable marker 记录的正是当前残留 local auth 时,该文件属于未完成登出的旧凭证。 */
+/** marker 记录的正是当前残留 local auth 时,该文件属于已断开或已失效的旧凭证。 */
export function shouldSuppressLocalCodexAuth(
codexHome: string,
localAuthPath: string,
): boolean {
const marker = readInvalidatedSystemCodexAuthMarker(codexHome);
- return Boolean(
- marker &&
- isDurableDisconnectMarker(marker) &&
- localFileMatchesInvalidatedMarker(marker, localAuthPath),
- );
+ return Boolean(marker && localFileMatchesInvalidatedMarker(marker, localAuthPath));
}
/** 删标记 (幂等)。 */
diff --git a/apps/desktop/src/main/maker-host/codex-oauth-readiness.ts b/apps/desktop/src/main/maker-host/codex-oauth-readiness.ts
new file mode 100644
index 0000000000..7ebe259823
--- /dev/null
+++ b/apps/desktop/src/main/maker-host/codex-oauth-readiness.ts
@@ -0,0 +1,27 @@
+import { app } from 'electron';
+import fs from 'node:fs';
+import path from 'node:path';
+
+import { shouldSuppressLocalCodexAuth } from './codex-auth-invalidation.js';
+import { isNativeProviderAuthBound } from './nativeProviderAuthBinding.js';
+
+/**
+ * 同步、只读地判断当前 owner 是否有可用的 Codex OAuth 登录态。
+ *
+ * 独立于 auth-adapters 的完整运行时依赖图,供模型目录 / 媒体通道做同步 ready 判定;
+ * 真正派发仍必须走 getChatgptBridgeAuth(),以刷新临期 token 并返回同一份 account id。
+ */
+export function hasCodexOAuthLoginReadOnly(): boolean {
+ if (!isNativeProviderAuthBound('openai')) return false;
+ const codexHome = path.join(app.getPath('userData'), 'codex-home');
+ const authPath = path.join(codexHome, 'auth.json');
+ if (shouldSuppressLocalCodexAuth(codexHome, authPath)) return false;
+ try {
+ const parsed = JSON.parse(fs.readFileSync(authPath, 'utf-8')) as {
+ tokens?: { access_token?: unknown };
+ };
+ return typeof parsed.tokens?.access_token === 'string' && parsed.tokens.access_token.length > 0;
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/model-providers/src/builtin.ts b/packages/model-providers/src/builtin.ts
index 22addc4717..3248b85c56 100644
--- a/packages/model-providers/src/builtin.ts
+++ b/packages/model-providers/src/builtin.ts
@@ -105,11 +105,10 @@ const OPENAI_PROVIDER: Provider = {
auth: { method: 'oauth' },
access: { kind: 'subscription', product: 'ChatGPT' },
titleModel: 'gpt-5.4-mini',
- // 图像通道(2026-07 图像多来源):OpenAI 平台 images API。ChatGPT 订阅 OAuth token
- // 调不了平台面(实测 401/403 缺 api.model.images.request scope),执行凭证是独立的
- // BYO 平台 API key('openai-images' secret,OpenAiHeader 配置);未配置时经
- // imageChannelRegistry 就绪过滤不进白名单。id 带 openai/ 前缀(跨供应商数据契约,
- // 防 first-wins 归属漂移);不声明 imageDefaults(xd 默认地位不动)。
+ // 图像通道:已登录 ChatGPT/Codex 时走 Codex Responses 的 hosted
+ // image_generation tool;用户另配 `openai-images` Platform key 时优先走 public
+ // Images API。id 带 openai/ 前缀(跨供应商数据契约,防 first-wins 归属漂移);
+ // 不声明 imageDefaults(xd 默认地位不动)。
imageModels: [{ id: 'openai/gpt-image-2', name: 'GPT Image 2' }],
routing: {
codex: {