Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复 ChatGPT 订阅图片通道的宿主模型依赖 (#6103)
nanacoa0eac6cbeaa1
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.tsindex 8bdf3fc2c4..8260f78b0a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/codexImageClient.test.ts@@ -1,235 +1,343 @@-import { describe, expect, it, vi } from 'vitest';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { afterEach, 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' } });+const image = 'iVBORw0KGgo=';+const params = { model: 'openai/gpt-image-2', prompt: 'a blue circle' };+const directories: string[] = [];+afterEach(async () => {+ await Promise.all(+ directories.splice(0).map((dir) => fs.rm(dir, { recursive: true, force: true })),+ );+});+function response(body: unknown = { data: [{ b64_json: image }], size: '1254x1254' }) {+ return Response.json(body);}--function makeChannel(+function channel(fetchImplementation: typeof fetch,- beforeDispatch?: (model: string) => void,- onAuthFailure?: Parameters<typeof createCodexImageChannel>[0]['onAuthFailure'],+ overrides: Partial<Parameters<typeof createCodexImageChannel>[0]> = {},) {return createCodexImageChannel({hasOAuthLogin: () => true,- getAuth: async () => ({ accessToken: 'oauth-token', accountId: 'account-id' }),+ getAuth: async () => ({ accessToken: 'test-token', accountId: 'test-account' }),fetchImplementation,- beforeDispatch,- onAuthFailure,+ ...overrides,});}-describe('codexImageClient', () => {- it('does not dispatch if the selected account changes while preparing an image', async () => {- const doFetch = vi.fn<typeof fetch>();- const channel = createCodexImageChannel({- providerId: 'openai-account-a',- hasOAuthLogin: () => true,- getAuth: vi.fn()- .mockResolvedValueOnce({ accessToken: 'old', accountId: 'account-a' })- .mockResolvedValueOnce({ accessToken: 'new', accountId: 'account-b' }),- fetchImplementation: doFetch,+describe('Codex standalone Images API', () => {+ it('generates with the image model, without a Responses host or hosted tool', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => response());+ const result = await channel(fetch).generateImage({+ ...params,+ size: '1024x1024',+ quality: 'low',+ });+ const [url, init] = fetch.mock.calls[0]!;+ expect(url).toBe('https://chatgpt.com/backend-api/codex/images/generations');+ expect(JSON.parse(String(init?.body))).toEqual({+ model: 'gpt-image-2',+ prompt: params.prompt,+ size: '1024x1024',+ quality: 'low',+ background: 'opaque',+ });+ expect(init?.headers).toMatchObject({+ Authorization: 'Bearer test-token',+ 'ChatGPT-Account-Id': 'test-account',+ Accept: 'application/json',});- await expect(channel.generateImage({ model: 'openai-account-a/gpt-image-2', prompt: 'p' })).rejects.toThrow('Codex image account changed before dispatch');- expect(doFetch).not.toHaveBeenCalled();+ expect(init?.headers).not.toHaveProperty('OpenAI-Beta');+ expect(result.data).toEqual([{ b64_json: image }]);+ // Preserve the returned bytes; requested size is not authoritative output metadata.+ expect(result).not.toHaveProperty('size');+ expect(fetch).toHaveBeenCalledTimes(1);});- it('dispatches custom account image models using only that account credentials', async () => {- const doFetch = vi.fn<typeof fetch>(async () => sseResponse([{ type: 'image_generation_call', result: 'aW1hZ2U=' }]));- const channel = createCodexImageChannel({- providerId: 'openai-account-a',- hasOAuthLogin: () => true,- getAuth: async () => ({ accessToken: 'account-a-token', accountId: 'account-a' }),- fetchImplementation: doFetch,- });- await channel.generateImage({ model: 'openai-account-a/gpt-image-2', prompt: 'p' });- expect(JSON.parse(String(doFetch.mock.calls[0]?.[1]?.body)).tools[0]).not.toHaveProperty('model');- expect(doFetch.mock.calls[0]?.[1]?.headers).toMatchObject({ Authorization: 'Bearer account-a-token', 'ChatGPT-Account-Id': 'account-a' });- await expect(channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' })).rejects.toThrow('不支持模型');- expect(doFetch).toHaveBeenCalledTimes(1);- });- it('uses the hosted image tool without an image model selector', 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',- quality: 'medium',+ it('edits using JSON images with sniffed MIME, not Responses input or multipart', async () => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-image-edit-'));+ directories.push(dir);+ const png = path.join(dir, 'reference.dat');+ const jpeg = path.join(dir, 'other.dat');+ await fs.writeFile(png, Buffer.from(image, 'base64'));+ await fs.writeFile(jpeg, Buffer.from([0xff, 0xd8, 0xff, 0xe0]));+ const fetch = vi.fn<typeof globalThis.fetch>(async () => response());+ await channel(fetch).editImage({ ...params, imagePaths: [png, jpeg], aspectRatio: '3:2' });+ expect(fetch.mock.calls[0]?.[0]).toBe('https://chatgpt.com/backend-api/codex/images/edits');+ expect(JSON.parse(String(fetch.mock.calls[0]?.[1]?.body))).toEqual({+ model: 'gpt-image-2',+ prompt: params.prompt,+ background: 'opaque',+ size: '1536x1024',+ images: [+ { image_url: 'data:image/png;base64,' + image },+ { image_url: 'data:image/jpeg;base64,/9j/4A==' },+ ],});+ await expect(channel(fetch).editImage({ ...params, imagePaths: [] })).rejects.toThrow();+ expect(fetch).toHaveBeenCalledTimes(1);+ });- 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',- size: '1536x1024',- quality: 'medium',- }),- );- expect(body.tools[0]).not.toHaveProperty('model');- expect(body).toMatchObject({ model: 'gpt-5.5' });- expect(body.tool_choice).toBeUndefined();+ it('keeps compatibility handles local and respects selected account credentials', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => response());+ const beforeDispatch = vi.fn();+ const c = channel(fetch, { providerId: 'openai-account-a', beforeDispatch });+ await c.generateImage({ ...params, model: 'openai-account-a/future-image' });+ expect(JSON.parse(String(fetch.mock.calls[0]?.[1]?.body)).model).toBe('gpt-image-2');+ expect(beforeDispatch).toHaveBeenCalledWith('openai-account-a/future-image');+ await expect(c.generateImage(params)).rejects.toThrow('不支持模型');+ expect(fetch).toHaveBeenCalledTimes(1);});- it('forwards custom dimensions and highest quality without downgrading', async () => {- const doFetch = vi.fn<typeof fetch>(async () => sseResponse([{ type: 'image_generation_call', result: 'final' }]));- await makeChannel(doFetch).generateImage({- model: 'openai/gpt-image-2.5-sunburst', prompt: 'wallpaper', size: '1760x3824', quality: 'max',+ it('preserves explicit options and leaves unspecified options omitted', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => response());+ await channel(fetch).generateImage({+ ...params,+ model: 'openai/gpt-image-2.5-sunburst',+ size: '1760x3824',+ quality: 'max',});- expect(JSON.parse(String(doFetch.mock.calls[0]?.[1]?.body)).tools[0]).toMatchObject({ size: '1760x3824', quality: 'max' });- await expect(makeChannel(doFetch).generateImage({ model: 'openai/gpt-image-2.5-sunburst', prompt: 'p', size: '1320x2868' })).rejects.toThrow('divisible by 16');- expect(doFetch).toHaveBeenCalledTimes(1);+ expect(JSON.parse(String(fetch.mock.calls[0]?.[1]?.body))).toMatchObject({+ size: '1760x3824',+ quality: 'max',+ });+ await channel(fetch).generateImage(params);+ const body = JSON.parse(String(fetch.mock.calls[1]?.[1]?.body));+ expect(body).not.toHaveProperty('size');+ expect(body).not.toHaveProperty('quality');+ await expect(channel(fetch).generateImage({ ...params, size: '1320x2868' })).rejects.toThrow(+ 'divisible by 16',+ );+ expect(fetch).toHaveBeenCalledTimes(2);});- it.each(['eof', 'response.failed', 'response.incomplete'])('never delivers a preview as a completed high-resolution image (%s)', async (ending) => {- const tail = ending === 'eof' ? [] : [{ type: ending }];- const channel = makeChannel(vi.fn<typeof fetch>(async () => sseResponse([{ partial_image_b64: 'preview' }, ...tail])));- await expect(channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' })).rejects.toThrow(ending === 'eof' ? '没有图片' : 'did not complete');+ it('does not dispatch if the selected account changes during preparation', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const getAuth = vi+ .fn()+ .mockResolvedValueOnce({ accessToken: 'old', accountId: 'a' })+ .mockResolvedValueOnce({ accessToken: 'new', accountId: 'b' });+ await expect(channel(fetch, { getAuth }).generateImage(params)).rejects.toThrow(+ 'account changed',+ );+ expect(fetch).not.toHaveBeenCalled();});- it('未指定画幅时保留 auto 语义;拒绝目录外模型', async () => {- const doFetch = vi.fn<typeof fetch>(async () =>- sseResponse([{ type: 'image_generation_call', result: 'aW1hZ2U=' }]),+ it('checks model availability again immediately before dispatch', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const beforeDispatch = vi+ .fn()+ .mockImplementationOnce(() => {})+ .mockImplementationOnce(() => {+ throw new Error('disabled');+ });+ await expect(channel(fetch, { beforeDispatch }).generateImage(params)).rejects.toThrow(+ 'disabled',);- 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');- expect(body.tools[0]).not.toHaveProperty('quality');+ expect(fetch).not.toHaveBeenCalled();+ });- await expect(- channel.generateImage({ model: 'another/future-image', prompt: 'p' }),- ).rejects.toThrow('不支持模型');- expect(doFetch).toHaveBeenCalledTimes(1);+ it.each([400, 401, 403, 429, 500])(+ 'preserves HTTP %s without retrying or switching providers',+ async (status) => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>+ Response.json({ error: { message: 'upstream failure' } }, { status }),+ );+ const onAuthFailure = vi.fn(async () => {+ throw new Error('coordinator failed');+ });+ await expect(channel(fetch, { onAuthFailure }).generateImage(params)).rejects.toThrow(+ 'HTTP ' + status,+ );+ expect(onAuthFailure).toHaveBeenCalledWith({+ status,+ body: JSON.stringify({ error: { message: 'upstream failure' } }),+ failedAccessToken: 'test-token',+ });+ expect(fetch).toHaveBeenCalledTimes(1);+ },+ );++ it.each([+ null,+ {},+ { data: [] },+ { data: [{}] },+ { data: [{ b64_json: '' }] },+ { data: [{ b64_json: 123 }] },+ { partial_image_b64: image },+ ])('rejects incomplete result %j', async (body) => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => response(body));+ await expect(channel(fetch).generateImage(params)).rejects.toThrow();+ expect(fetch).toHaveBeenCalledTimes(1);});- it('keeps legacy catalog handles local and checks availability before dispatch', async () => {- const doFetch = vi.fn<typeof fetch>(async () => sseResponse([{ type: 'image_generation_call', result: 'aW1hZ2U=' }]));- const beforeDispatch = vi.fn();- await makeChannel(doFetch, beforeDispatch).generateImage({ model: 'openai/future-image', prompt: 'p' });- expect(JSON.parse(String(doFetch.mock.calls[0]?.[1]?.body)).tools[0]).not.toHaveProperty('model');- expect(beforeDispatch).toHaveBeenCalledWith('openai/future-image');+ it('rejects truncated JSON and network failures without resubmission', async () => {+ for (const impl of [+ async () => new Response('{"data":['),+ async () => {+ throw new Error('network interrupted');+ },+ ]) {+ const fetch = vi.fn<typeof globalThis.fetch>(impl);+ await expect(channel(fetch).generateImage(params)).rejects.toThrow();+ expect(fetch).toHaveBeenCalledTimes(1);+ }});- it('只交付最终图片;派发前重查可阻止出网', async () => {- const doFetch = vi.fn<typeof fetch>(async () =>- sseResponse([{ partial_image_b64: 'first' }, { type: 'image_generation_call', result: 'final' }, { partial_image_b64: 'late-preview' }]),- );- 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('模型已停用');+ it('forwards cancellation and does not submit an already cancelled request', async () => {+ const controller = new AbortController();+ const fetch = vi.fn<typeof globalThis.fetch>(async (_url, init) => {+ expect(init?.signal).toBe(controller.signal);+ controller.abort();+ throw new DOMException('aborted', 'AbortError');});- 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' } }),- ),- );+ const c = channel(fetch);+ await expect(c.generateImage({ ...params, signal: controller.signal })).rejects.toThrow();+ await expect(c.generateImage({ ...params, signal: controller.signal })).rejects.toThrow();+ expect(fetch).toHaveBeenCalledTimes(1);+ });- 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('keeps readiness and missing credentials within the existing auth boundary', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const c = channel(fetch, {+ hasOAuthLogin: () => false,+ getAuth: async () => {+ throw new Error('login required');+ },+ });+ expect(c.ready()).toBe(false);+ await expect(c.generateImage(params)).rejects.toThrow('login required');+ expect(fetch).not.toHaveBeenCalled();+ });+ it.each(['account', 'token'])('blocks a change to only the %s before dispatch', async (field) => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const first = { accessToken: 'token-a', accountId: 'account-a' };+ const second =+ field === 'account'+ ? { ...first, accountId: 'account-b' }+ : { ...first, accessToken: 'token-b' };+ const getAuth = vi.fn().mockResolvedValueOnce(first).mockResolvedValueOnce(second);+ await expect(channel(fetch, { getAuth }).generateImage(params)).rejects.toThrow(+ 'account changed',+ );+ expect(fetch).not.toHaveBeenCalled();});- it('兼容单 CR 的 SSE 事件与行结束符', async () => {- const body = [- 'data: {bad json}\r\r',- `data: ${JSON.stringify({ type: 'image_generation_call', result: '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' } }),- ),+ it('stops before reading credentials when the model is disabled initially', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const getAuth = vi.fn();+ const beforeDispatch = () => {+ throw new Error('disabled initially');+ };+ await expect(channel(fetch, { getAuth, beforeDispatch }).generateImage(params)).rejects.toThrow(+ 'disabled initially',);+ expect(getAuth).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();+ });+ it('stops when cancelled during credential preparation, before fetch', async () => {+ const controller = new AbortController();+ const fetch = vi.fn<typeof globalThis.fetch>();+ const getAuth = vi.fn(async () => {+ controller.abort();+ return { accessToken: 'test-token', accountId: 'test-account' };+ });await expect(- channel.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),- ).resolves.toMatchObject({ data: [{ b64_json: 'cr-only' }] });+ channel(fetch, { getAuth }).generateImage({ ...params, signal: controller.signal }),+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(fetch).not.toHaveBeenCalled();});- it('把认证失败与本次 token 交给失效协调器,且不让协调器异常覆盖 HTTP 错误', async () => {- const raw = '{"error":{"code":"token_invalidated"}}';- const onAuthFailure = vi.fn(async () => {- throw new Error('invalidation failed');+ it('does not deliver a complete response if cancellation arrives while parsing it', async () => {+ const controller = new AbortController();+ const res = response();+ vi.spyOn(res, 'json').mockImplementation(async () => {+ controller.abort();+ return { data: [{ b64_json: image }] };});- const channel = makeChannel(- vi.fn<typeof fetch>(async () => new Response(raw, { status: 401 })),- undefined,- onAuthFailure,- );+ const fetch = vi.fn<typeof globalThis.fetch>(async () => res);+ await expect(+ channel(fetch).generateImage({ ...params, signal: controller.signal }),+ ).rejects.toMatchObject({ name: 'AbortError' });+ expect(fetch).toHaveBeenCalledTimes(1);+ });+ it('rejects unreadable and non-image references before sending any edit', async () => {+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'codex-image-invalid-'));+ directories.push(dir);+ const invalid = path.join(dir, 'not-an-image.png');+ await fs.writeFile(invalid, '<html>not an image</html>');+ const fetch = vi.fn<typeof globalThis.fetch>();+ const c = channel(fetch);+ await expect(c.editImage({ ...params, imagePaths: [invalid] })).rejects.toThrow('格式不支持');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',- });+ c.editImage({ ...params, imagePaths: [path.join(dir, 'missing.png')] }),+ ).rejects.toMatchObject({ code: 'ENOENT' });+ expect(fetch).not.toHaveBeenCalled();});- it('登录态决定 ready;缺 token 与空图片响应明确失败', async () => {- const unavailable = createCodexImageChannel({- hasOAuthLogin: () => false,- getAuth: async () => {- throw new Error('OpenAI 订阅登录已失效,请重新登录');- },- fetchImplementation: vi.fn<typeof fetch>(),+ it('rejects empty edit input and wrong provider before obtaining credentials', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>();+ const getAuth = vi.fn();+ const c = channel(fetch, { getAuth });+ await expect(c.editImage({ ...params, imagePaths: [] })).rejects.toThrow('reference image');+ for (const model of ['xd/gpt-image-2', 'openai/', 'openai/ ']) {+ await expect(c.generateImage({ ...params, model })).rejects.toThrow('不支持模型');+ }+ expect(getAuth).not.toHaveBeenCalled();+ expect(fetch).not.toHaveBeenCalled();+ });++ it('omits an absent account header and gives independent requests distinct turn IDs', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => response());+ const c = channel(fetch, {+ getAuth: async () => ({ accessToken: 'test-token', accountId: null }),});- expect(unavailable.ready()).toBe(false);- await expect(- unavailable.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' }),- ).rejects.toThrow('重新登录');+ await c.generateImage(params);+ await c.generateImage(params);+ const headers = fetch.mock.calls.map((call) => call[1]?.headers as Record<string, string>);+ expect(headers[0]).not.toHaveProperty('ChatGPT-Account-Id');+ expect(headers[0]['x-codex-image-turn-id']).toMatch(/^[0-9a-f-]{36}$/);+ expect(headers[0]['x-codex-image-turn-id']).not.toBe(headers[1]['x-codex-image-turn-id']);+ });- const empty = makeChannel(- vi.fn<typeof fetch>(async () => sseResponse([{ type: 'response.completed' }])),+ it('retains multiple complete images and rejects a partially valid batch', async () => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () =>+ response({ data: [{ b64_json: image }, { b64_json: image }] }),);- await expect(empty.generateImage({ model: 'openai/gpt-image-2', prompt: 'p' })).rejects.toThrow(- '没有图片',+ expect((await channel(fetch).generateImage(params)).data).toHaveLength(2);+ const incomplete = vi.fn<typeof globalThis.fetch>(async () =>+ response({ data: [{ b64_json: image }, null] }),);+ await expect(channel(incomplete).generateImage(params)).rejects.toThrow('没有图片');+ expect(incomplete).toHaveBeenCalledTimes(1);+ });++ it.each([+ 'plain-text upstream failure',+ '',+ JSON.stringify({ error: { message: 'x'.repeat(1000) } }),+ ])('bounds error detail without an auth callback (%#)', async (body) => {+ const fetch = vi.fn<typeof globalThis.fetch>(async () => new Response(body, { status: 502 }));+ const error = await channel(fetch)+ .generateImage(params)+ .catch((reason: unknown) => reason);+ expect(error).toBeInstanceOf(Error);+ expect((error as Error).message).toContain('HTTP 502');+ expect((error as Error).message.length).toBeLessThan(550);+ expect(fetch).toHaveBeenCalledTimes(1);+ });++ it('keeps the HTTP failure if reading its body fails', async () => {+ const res = new Response('', { status: 503 });+ vi.spyOn(res, 'text').mockRejectedValue(new Error('body interrupted'));+ const fetch = vi.fn<typeof globalThis.fetch>(async () => res);+ await expect(channel(fetch).generateImage(params)).rejects.toThrow('HTTP 503');+ expect(fetch).toHaveBeenCalledTimes(1);});});diff --git a/apps/desktop/src/main/cindy-brain/codexImageClient.ts b/apps/desktop/src/main/cindy-brain/codexImageClient.tsindex 0bfbc25f4b..ecebce5e5d 100644--- a/apps/desktop/src/main/cindy-brain/codexImageClient.ts+++ b/apps/desktop/src/main/cindy-brain/codexImageClient.ts@@ -1,11 +1,10 @@/*** ChatGPT/Codex OAuth image channel.*- * The subscription token cannot call the public Platform Images API. It can,- * however, call the Codex Responses surface's hosted `image_generation` tool.- * The catalog ID is a compatibility handle, not an upstream image model selector.- * Keep the token in Main and parse the raw- * SSE stream because image-generation events may be newer than SDK typings.+ * Use the Codex standalone Images API with the selected ChatGPT account.+ * No Responses host model is needed. Catalog IDs remain compatibility handles;+ * the wire image model follows the upstream Codex image-generation extension.+ * Core validates and persists the returned image bytes through the existing path.*/import { randomUUID } from 'node:crypto';@@ -17,11 +16,9 @@ import { mediaRequestParamsForLog, mediaRequestUrlForLog } from '../cindy-media/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 CODEX_IMAGES_URL = 'https://chatgpt.com/backend-api/codex/images';+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');export interface CreateCodexImageChannelOptions {providerId?: string;@@ -37,84 +34,13 @@ export interface CreateCodexImageChannelOptions {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;- // Preview frames are not final assets: never return one after a failed/truncated stream.- if (typeof item.partial_image_b64 === 'string') return null;- 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;- let event: Record<string, unknown>;- try {- event = JSON.parse(data) as Record<string, unknown>;- } catch {- // Unknown/malformed SSE frames may precede a valid completed result.- return;- }- if (event?.type === 'error' || event?.type === 'response.failed' || event?.type === 'response.incomplete') {- throw new Error('Codex image generation did not complete; preview images are not final results');- }- const found = extractImageB64(event);- if (found) latest = found;- };-- 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 {- await reader.cancel().catch(() => undefined);- reader.releaseLock();- }- return latest;-}--async function inputImage(path: string): Promise<{ type: 'input_image'; image_url: string }> {+async function inputImage(path: string): Promise<{ 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')}` };+ return { image_url: `data:${mime};base64,${bytes.toString('base64')}` };}async function httpError(@@ -144,12 +70,19 @@ async function httpError(export function createCodexImageChannel(opts: CreateCodexImageChannelOptions): ImageChannel {const doFetch = opts.fetchImplementation ?? fetch;- async function generate(params: ImageParameters & {- model: string;- prompt: string;- imagePaths?: string[];- signal?: AbortSignal;- }): Promise<ImageChannelResult> {+ async function generate(+ params: ImageParameters & {+ model: string;+ prompt: string;+ imagePaths?: string[];+ signal?: AbortSignal;+ },+ operation: 'generations' | 'edits',+ ): Promise<ImageChannelResult> {+ params.signal?.throwIfAborted();+ if (operation === 'edits' && !params.imagePaths?.length) {+ throw new Error('Codex image edit requires at least one reference image');+ }const options = normalizeImageParameters('openai', params.model, params);const modelPrefix = `${opts.providerId ?? 'openai'}/`;if (!params.model.startsWith(modelPrefix) || !params.model.slice(modelPrefix.length).trim()) {@@ -167,25 +100,14 @@ export function createCodexImageChannel(opts: CreateCodexImageChannelOptions): Ithrow new Error('Codex image account changed before dispatch');}opts.beforeDispatch?.(params.model);- const content: Array<Record<string, unknown>> = [- { type: 'input_text', text: params.prompt },- ...images,- ];+ params.signal?.throwIfAborted();+ const url = CODEX_IMAGES_URL + '/' + operation;const body = {- 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',- ...options,- output_format: 'png',- background: 'opaque',- partial_images: 1,- },- ],+ model: IMAGE_MODEL,+ prompt: params.prompt,+ ...options,+ background: 'opaque',+ ...(operation === 'edits' ? { images } : {}),};const requestId = randomUUID();const startedAt = Date.now();@@ -194,7 +116,7 @@ export function createCodexImageChannel(opts: CreateCodexImageChannelOptions): IproviderId: opts.providerId ?? 'openai',modelId: params.model,method: 'POST',- url: mediaRequestUrlForLog(CODEX_RESPONSES_URL),+ url: mediaRequestUrlForLog(url),};log.info('media request dispatch', {...requestLog,@@ -202,13 +124,13 @@ export function createCodexImageChannel(opts: CreateCodexImageChannelOptions): I});let response: Response;try {- response = await doFetch(CODEX_RESPONSES_URL, {+ response = await doFetch(url, {method: 'POST',headers: {Authorization: `Bearer ${auth.accessToken}`,'Content-Type': 'application/json',- Accept: 'text/event-stream',- 'OpenAI-Beta': 'responses=experimental',+ Accept: 'application/json',+ 'x-codex-image-turn-id': requestId,originator: 'codex_cli_rs','User-Agent': USER_AGENT,...(auth.accountId ? { 'ChatGPT-Account-Id': auth.accountId } : {}),@@ -230,15 +152,25 @@ export function createCodexImageChannel(opts: CreateCodexImageChannelOptions): Ithrow error;}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' };+ const result = (await response.json()) as { data?: Array<{ b64_json?: unknown }> } | null;+ params.signal?.throwIfAborted();+ if (+ !Array.isArray(result?.data) ||+ !result.data.length ||+ result.data.some(+ (item) => !item || typeof item.b64_json !== 'string' || !item.b64_json.trim(),+ )+ ) {+ throw new Error('Codex 返回中没有图片,请重试或改用 OpenAI Platform API key');+ }+ // Do not infer output dimensions or format from the request. Core sniffs the bytes.+ return { data: result.data.map((item) => ({ b64_json: item.b64_json as string })) };}return {imageProtocol: 'openai',ready: opts.hasOAuthLogin,- generateImage: generate,- editImage: generate,+ generateImage: (params) => generate(params, 'generations'),+ editImage: (params) => generate(params, 'edits'),};}diff --git a/docs/model-registry-v4-media.md b/docs/model-registry-v4-media.mdindex bc3f3e1aba..b18ee21e91 100644--- a/docs/model-registry-v4-media.md+++ b/docs/model-registry-v4-media.md@@ -118,15 +118,42 @@ Server 正本和本离线副本以相同 revision 整表同步;未增加供应## 执行与兼容边界-OpenAI 授权登录的图像能力统一显示为 **GPT Image Gen**,由托管 `image_generation` 工具选择底层型号,-不从公共 API 目录推导订阅型号。内部保留各连接原有的 `gpt-image-2` ID,兼容 Art/Core-已有选择与显示开关;该 ID 不再作为图像 `model` 参数发送。Responses 顶层的宿主模型-仍保留。配置 Images API key 时,内置 OpenAI 连接继续使用公共 API 的真实模型名单和+OpenAI 授权登录的图像能力统一显示为 **GPT Image Gen**,不从公共 API 目录推导订阅型号。+内部保留各连接原有的 `gpt-image-2` ID,兼容 Art/Core 已有选择与显示开关;目录 ID+仍是本地兼容句柄。执行使用 ChatGPT Codex 独立的 `images/generations` / `images/edits`+JSON 接口,图片模型按上游 Codex 实现使用 `gpt-image-2`,不再依赖 Responses 宿主模型。+编辑输入为 `images: [{ image_url: "data:…" }]`,返回 `data[].b64_json` 交现有 Core 校验入库;+实际图片尺寸以结果字节为准,不把请求尺寸当成生成结果。+配置 Images API key 时,内置 OpenAI 连接继续使用公共 API 的真实模型名单和`model` 参数;独立订阅账号不受该 key 影响。切换凭证后重算活动目录,发现失败也不改变用户选择的接入方式。实现见 `active-catalog.ts`、`codexImageClient.ts`。其它媒体执行器及 Gateway Guide 保持各自协议与凭证边界,不添加新认证方式。+### ChatGPT 订阅图片接口迁移验证(2026-10-15)++- 原因:旧 Responses 请求固定使用 `gpt-5.5` 宿主,部分 ChatGPT 账号返回 HTTP 400,+ 提示该模型不受支持。迁移只改订阅图片适配器,不改 Art、模型目录或公共 API key 路由。+- 上游依据:[Codex Images 客户端](https://github.com/openai/codex/blob/160b2b1ef62114eeb41e41e5e3be0000d944b713/codex-rs/codex-api/src/endpoint/images.rs)+ 与 [独立出图工具](https://github.com/openai/codex/blob/160b2b1ef62114eeb41e41e5e3be0000d944b713/codex-rs/ext/image-generation/src/tool.rs)。+- 继续使用所选账号的 OAuth Bearer / `ChatGPT-Account-Id`,派发前复核账号、模型启用状态+ 和取消信号。失败不自动换供应商或重新提交;保留现有 Core 结果未知与付费重提保护。+- 自动回归覆盖 JSON 文生图、多参考图编辑、旧目录 ID、多账号隔离、参数透传、取消、+ HTTP 错误、断网、截断 JSON 和空结果;上游不再返回 SSE,旧 SSE 解析随协议一起移除。+- 实际适配器验证:从当前源码编译,仅替换日志输出,注入当前已绑定账号的只读鉴权;+ 文生图与改图均 HTTP 200,分别约 14 秒和 18 秒,目检确认蓝圆改成红圆。凭证未入仓。+- 尺寸限制:请求 `1024x1024` 实测返回 `1272x1236` / `1273x1236`。适配器不缩放,+ 不以请求尺寸伪造产物元数据;要求精确尺寸的流程仍需单独处理。+- 未验证:打包 Desktop 中 Art → Core → 媒体入库的完整交互、Windows 真实运行,以及+ 其它订阅套餐/账号权限。接口级实测与自动回归不代替这些验收。+- 回滚可还原本次适配器修改;但旧固定宿主的账号兼容问题会重新出现。+- 白盒补测:适配器从 21 项扩至 34 项,覆盖独立 token/account 变化、准备与解析阶段+ 的取消、无效参考图、混合有效/无效结果、错误体读取失败等;连同鉴权、参数、注册表及+ Core 调用状态/作品路径共 283 项通过。未使用覆盖率工具,不宣称 100% 分支覆盖。+- 主干既有限制:订阅适配器抛出的明确 HTTP 4xx 仍由 Core 的第三方通道统一映射为+ `SUBMISSION_OUTCOME_UNKNOWN`(`invocationService.ts` 的 provider 提交 catch)。+ 重复提交保护保留,但错误分类不够准确;本次迁移未扩大到跨通道错误协议改造。+V1–V3 解析保持原有契约;新媒体字段、媒体原生协议和空 Agent 路由属于 V4。服务端以后按这套本地规范维护下发数据;旧消费者需要其既有媒体列表投影,不能直接接收严格解析器不认识的字段。客户端实现不构成 Server 已实现或已部署的证明。@@ -168,6 +195,6 @@ Registry 不因这项能力标识递增 schema 版本,已有 V4/V5 语义保也不会让尚未实现的音频协议自动变得可调用。验证覆盖 V4 全类型解析和投影、用户配置持久化、实报与覆盖优先级、目录刷新、-停用展示、旧版拒绝新字段、订阅图像请求省略工具级 `model`、Art 旧选择的生成/编辑兼容性,+停用展示、旧版拒绝新字段、订阅图像请求不依赖宿主模型、Art 旧选择的生成/编辑兼容性,以及 API key 与订阅目录切换时保留各自的型号语义。真实账号作图、服务端热下发及正式版 UI 验收不能用本地测试替代。