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。

fix(desktop): 修复 DeepSeek 图片失败后会话无法恢复 (#1329)

lilsnake9ebc411fd18a
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
index 44211cf932..51736f262b 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/agent-input-coordinator.test.ts
@@ -152,6 +152,13 @@ function sessionRunningError(): Error & { code: string } {
});
}
+function unsupportedChatBridgeImageError(
+ feature = "input content part 'input_image'",
+): string {
+ return 'unexpected status 400 Bad Request: Responses feature is not supported by the '
+ + `Chat Completions bridge: ${feature}, url: http://127.0.0.1/v1/responses`;
+}
+
function createHarness() {
let running = false;
let turnGeneration = 0;
@@ -2102,6 +2109,201 @@ describe('AgentInputCoordinator send transaction', () => {
expect(h.onUiRetry).toHaveBeenCalledWith(sid, expect.any(String), 'manual');
});
+ it('removes unsupported image blocks but preserves GIF and PDF files on retry', async () => {
+ const h = createHarness();
+ const sid = 'retry-unsupported-image-with-text';
+ h.setHasAssistantProgressAfter(async () => false);
+ const item = makeItem('q-first', 'describe this');
+ item.files = [
+ {
+ id: 'image-1',
+ name: 'image.png',
+ path: 'clipboard://image.png',
+ ext: '.png',
+ size: 4,
+ category: 'image',
+ mimeType: 'image/png',
+ url: 'data:image/png;base64,aW1hZ2U=',
+ },
+ {
+ id: 'gif-1',
+ name: 'clip.gif',
+ path: '/repo/clip.gif',
+ ext: '.gif',
+ size: 6,
+ category: 'image',
+ mimeType: 'image/gif',
+ url: 'xdt-image://session/clip.gif',
+ },
+ {
+ id: 'file-1',
+ name: 'notes.pdf',
+ path: '/repo/notes.pdf',
+ ext: '.pdf',
+ size: 8,
+ category: 'pdf',
+ mimeType: 'application/pdf',
+ },
+ ];
+ item.persistedContent = JSON.stringify({
+ text: item.text,
+ images: [{
+ url: 'data:image/png;base64,aW1hZ2U=',
+ mimeType: 'image/png',
+ originalName: 'image.png',
+ }, {
+ url: 'xdt-image://session/clip.gif',
+ mimeType: 'image/gif',
+ originalName: 'clip.gif',
+ }],
+ files: [{ name: 'notes.pdf', path: '/repo/notes.pdf' }],
+ });
+ item.chatMessage = {
+ ...item.chatMessage,
+ images: [{
+ url: 'data:image/png;base64,aW1hZ2U=',
+ mimeType: 'image/png',
+ originalName: 'image.png',
+ }, {
+ url: 'xdt-image://session/clip.gif',
+ mimeType: 'image/gif',
+ originalName: 'clip.gif',
+ }],
+ files: [{ name: 'notes.pdf', path: '/repo/notes.pdf' }],
+ };
+ (item.chatMessage as typeof item.chatMessage & {
+ retryFiles?: AgentInputQueuedMessage['files'];
+ }).retryFiles = item.files;
+
+ h.coordinator.enqueue(sid, item);
+ await flush();
+ h.setRunning(false);
+ const error = unsupportedChatBridgeImageError();
+ h.coordinator.onTurnEvent(sid, 'error', error);
+ await flush();
+
+ await h.coordinator.retryLastError(sid);
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({
+ type: 'user',
+ content: [
+ { type: 'text', text: 'describe this' },
+ { type: 'file', path: 'xdt-image://session/clip.gif', mimeType: 'image/gif' },
+ { type: 'file', path: '/repo/notes.pdf', mimeType: 'application/pdf' },
+ ],
+ });
+ const retried = h.onDispatchedUserTurn.mock.calls[1]?.[1];
+ expect(retried?.files).toEqual([
+ expect.objectContaining({ id: 'gif-1', ext: '.gif', category: 'image' }),
+ expect.objectContaining({ id: 'file-1', category: 'pdf' }),
+ ]);
+ expect(retried?.chatMessage.images).toEqual([{
+ url: 'xdt-image://session/clip.gif',
+ mimeType: 'image/gif',
+ originalName: 'clip.gif',
+ }]);
+ expect(retried?.chatMessage.files).toEqual([{ name: 'notes.pdf', path: '/repo/notes.pdf' }]);
+ expect((retried?.chatMessage as typeof retried.chatMessage & {
+ retryFiles?: AgentInputQueuedMessage['files'];
+ }).retryFiles).toEqual([
+ expect.objectContaining({ id: 'gif-1', ext: '.gif', category: 'image' }),
+ expect.objectContaining({ id: 'file-1', category: 'pdf' }),
+ ]);
+ expect(JSON.parse(retried?.persistedContent ?? '{}')).toEqual({
+ text: 'describe this',
+ images: [{
+ url: 'xdt-image://session/clip.gif',
+ mimeType: 'image/gif',
+ originalName: 'clip.gif',
+ }],
+ files: [{ name: 'notes.pdf', path: '/repo/notes.pdf' }],
+ });
+ });
+
+ it('keeps an unsupported image-only retry recoverable without fabricating text', async () => {
+ const h = createHarness();
+ const sid = 'retry-unsupported-image-only';
+ h.setHasAssistantProgressAfter(async () => false);
+ const item = makeItem('q-first', '');
+ item.files = [{
+ id: 'image-1',
+ name: 'image.png',
+ path: 'clipboard://image.png',
+ ext: '.png',
+ size: 4,
+ category: 'image',
+ mimeType: 'image/png',
+ url: 'data:image/png;base64,aW1hZ2U=',
+ }];
+ item.persistedContent = JSON.stringify({
+ text: '',
+ images: [{
+ url: 'data:image/png;base64,aW1hZ2U=',
+ mimeType: 'image/png',
+ originalName: 'image.png',
+ }],
+ files: [],
+ });
+ item.chatMessage = {
+ ...item.chatMessage,
+ images: [{
+ url: 'data:image/png;base64,aW1hZ2U=',
+ mimeType: 'image/png',
+ originalName: 'image.png',
+ }],
+ };
+
+ h.coordinator.enqueue(sid, item);
+ await flush();
+ h.setRunning(false);
+ const error = unsupportedChatBridgeImageError();
+ h.coordinator.onTurnEvent(sid, 'error', error);
+ await flush();
+
+ await h.coordinator.retryLastError(sid);
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(1);
+ expect(latestProjection(h.projections).error).toBe(error);
+ expect(latestProjection(h.projections).recovery?.kind).toBe('active-turn');
+
+ h.coordinator.enqueue(sid, makeItem('q-next', 'continue in text'));
+ await flush();
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'continue in text' });
+ });
+
+ it('keeps retry recovery compatible with the legacy bridge image error', async () => {
+ const h = createHarness();
+ const sid = 'retry-unsupported-image-legacy-error';
+ h.setHasAssistantProgressAfter(async () => false);
+ const item = makeItem('q-first', 'describe this');
+ item.files = [{
+ id: 'image-1',
+ name: 'image.png',
+ path: 'clipboard://image.png',
+ ext: '.png',
+ size: 4,
+ category: 'image',
+ mimeType: 'image/png',
+ url: 'data:image/png;base64,aW1hZ2U=',
+ }];
+
+ h.coordinator.enqueue(sid, item);
+ await flush();
+ h.setRunning(false);
+ h.coordinator.onTurnEvent(sid, 'error', unsupportedChatBridgeImageError('input_image'));
+ await flush();
+
+ await h.coordinator.retryLastError(sid);
+ await flush();
+
+ expect(h.sendToAgent).toHaveBeenCalledTimes(2);
+ expect(h.sendToAgent.mock.calls[1]?.[1]).toEqual({ type: 'user', content: 'describe this' });
+ });
+
it('zero-progress retry supersedes the failed user row once the clone is dispatched', async () => {
// retry-supersede:零产出克隆重发会在历史里留下两条一模一样的 user 行
// (旧行 + 克隆行)。克隆行落库并派发成功后必须软删旧行,且锚定的是
diff --git a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
index ab728a29c5..690076b529 100644
--- a/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
+++ b/apps/desktop/src/main/maker-ipc/agent-input-coordinator.ts
@@ -24,6 +24,7 @@
* 它只提交 intent payload;排序、投递模式、回滚和持久化由本模块决定。
*/
+import { isUnsupportedResponsesImageErrorPayload } from '@cindy/responses-chat-bridge';
import { createLogger } from '../logger.js';
import { createMessage as createDbMessage } from '../localDb/ipc/messages.js';
import { touchUserSendInDb } from '../localDb/ipc/sessions.js';
@@ -41,6 +42,7 @@ import type {
} from '../../shared/agentInputQueue.js';
import {
buildMakerUserMessage,
+ getAgentInputAttachmentBlockType,
getAgentFacingText,
projectionRetryText,
sanitizeQueuedMessageForPersistence,
@@ -66,6 +68,90 @@ const CREDENTIAL_SWITCH_RETRY_DELAY_MS = 10_000;
const TERMINAL_DONE_FALLBACK_DELAY_MS = 250;
const REWIND_BOUNDARY_POLL_INTERVAL_MS = 100;
+type QueuedAttachment = NonNullable<AgentInputQueuedMessage['files']>[number];
+
+function isMakerImageAttachment(file: Pick<QueuedAttachment, 'category' | 'ext'>): boolean {
+ return getAgentInputAttachmentBlockType(file.category, file.ext) === 'image';
+}
+
+function attachmentSourceKey(value: unknown): string | null {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
+ const record = value as Record<string, unknown>;
+ if (typeof record.url === 'string') return `url:${record.url}`;
+ if (typeof record.base64 === 'string') return `base64:${record.base64}`;
+ return null;
+}
+
+function stripQueuedMessageImages(item: AgentInputQueuedMessage): AgentInputQueuedMessage {
+ const remainingFiles = item.files?.filter((file) => !isMakerImageAttachment(file));
+ const remainingImageSources = new Set(
+ (remainingFiles ?? [])
+ .filter((file) => file.category === 'image')
+ .map(attachmentSourceKey)
+ .filter((source): source is string => source !== null),
+ );
+ const chatMessage = { ...item.chatMessage };
+ const remainingChatImages = chatMessage.images?.filter((image) => {
+ const source = attachmentSourceKey(image);
+ return source !== null && remainingImageSources.has(source);
+ });
+ if (remainingChatImages && remainingChatImages.length > 0) {
+ chatMessage.images = remainingChatImages;
+ } else {
+ delete chatMessage.images;
+ }
+
+ // Renderer queue objects historically carry retryFiles as an extra presentation field even
+ // though it is not part of the main-process wire contract. Strip only attachments that become
+ // maker image blocks: GIF keeps category=image for preview, but is sent as a file block.
+ const compatibleChatMessage = chatMessage as typeof chatMessage & {
+ retryFiles?: QueuedAttachment[];
+ };
+ if (Array.isArray(compatibleChatMessage.retryFiles)) {
+ const retryFiles = compatibleChatMessage.retryFiles.filter(
+ (file) => !isMakerImageAttachment(file),
+ );
+ if (retryFiles.length > 0) compatibleChatMessage.retryFiles = retryFiles;
+ else delete compatibleChatMessage.retryFiles;
+ }
+
+ let persistedContent = item.persistedContent;
+ try {
+ const parsed = JSON.parse(persistedContent) as unknown;
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
+ const record = parsed as Record<string, unknown>;
+ const remainingPersistedImages = Array.isArray(record.images)
+ ? record.images.filter((image) => {
+ const source = attachmentSourceKey(image);
+ return source !== null && remainingImageSources.has(source);
+ })
+ : [];
+ persistedContent = JSON.stringify({
+ ...record,
+ images: remainingPersistedImages,
+ });
+ }
+ } catch {
+ // Historical plain-text queue payloads contain no persisted image references.
+ }
+
+ const stripped: AgentInputQueuedMessage = {
+ ...item,
+ persistedContent,
+ chatMessage,
+ };
+ if (remainingFiles && remainingFiles.length > 0) stripped.files = remainingFiles;
+ else delete stripped.files;
+ return stripped;
+}
+
+function hasRetryableQueuedContent(item: AgentInputQueuedMessage): boolean {
+ return getAgentFacingText(item).trim().length > 0
+ || (item.files?.length ?? 0) > 0
+ || (item.mentions?.length ?? 0) > 0
+ || (item.sessionRefs?.length ?? 0) > 0;
+}
+
export interface AgentInputSendOpts {
messageUuid?: string;
userName?: string;
@@ -1671,6 +1757,20 @@ export class AgentInputCoordinator {
log.debug('auto retry skipped — no assistant progress to continue from', { sessionId });
return { projection: this.getProjection(sessionId), outcome: 'no-progress' };
}
+ let retryItem = recovery.kind === 'active-turn' ? recovery.item : null;
+ if (
+ !continueItem
+ && retryItem
+ && isUnsupportedResponsesImageErrorPayload(state.error ?? state.stickyError)
+ ) {
+ retryItem = stripQueuedMessageImages(retryItem);
+ if (!hasRetryableQueuedContent(retryItem)) {
+ // An image-only turn has no truthful fallback. Keep the error/recovery intact so a later
+ // text message or model switch can take over instead of inventing replacement text.
+ log.debug('image-only retry skipped for unsupported Chat bridge input', { sessionId });
+ return { projection: this.getProjection(sessionId), outcome: 'no-progress' };
+ }
+ }
state.error = null;
state.stickyError = null;
// 接管态在补发这一刻结束:聊天流里的「重新连接中」活动行交棒给落库的
@@ -1682,7 +1782,7 @@ export class AgentInputCoordinator {
if (!item) {
const clientId = crypto.randomUUID();
item = {
- ...recovery.item,
+ ...(retryItem ?? recovery.item),
clientId,
// retry-supersede:零产出克隆重发 —— 旧 user 行已落库但模型从未收到,
// 本条落库成功后 host 把旧行(与其后的 error 行)软删,历史只留这一条。
@@ -1690,7 +1790,7 @@ export class AgentInputCoordinator {
// (连环失败时指向更早的行),窗口必须锚定在本轮被取代的那条上。
supersedesUserClientId: recovery.item.clientId,
chatMessage: {
- ...recovery.item.chatMessage,
+ ...(retryItem ?? recovery.item).chatMessage,
clientId,
createdAt: new Date().toISOString(),
},
diff --git a/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts b/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts
index 7b887dadb0..2f3040155f 100644
--- a/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts
+++ b/packages/responses-chat-bridge/src/__tests__/translate-request.test.ts
@@ -491,6 +491,88 @@ describe('translateResponsesRequest', () => {
]);
});
+ it('drops unsupported images from replayed user history so a later text turn can recover', () => {
+ const imageUrl = 'data:image/png;base64,aW1hZ2U=';
+ const out = translateResponsesRequest(base({
+ input: [
+ {
+ type: 'message',
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'describe this' },
+ { type: 'input_image', image_url: imageUrl },
+ ],
+ },
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'continue in text' }] },
+ ],
+ }));
+
+ expect(out.messages).toEqual([
+ { role: 'user', content: 'describe this' },
+ { role: 'user', content: 'continue in text' },
+ ]);
+ });
+
+ it('drops untranslatable file_id images from replayed history on image-url routes', () => {
+ const out = translateResponsesRequest(base({
+ input: [
+ {
+ type: 'message',
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'describe this' },
+ { type: 'input_image', file_id: 'file_1' },
+ ],
+ },
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'continue in text' }] },
+ ],
+ }), { capabilities: { imageInput: 'image_url' } });
+
+ expect(out.messages).toEqual([
+ { role: 'user', content: 'describe this' },
+ { role: 'user', content: 'continue in text' },
+ ]);
+ });
+
+ it('drops image-only replayed turns but keeps the newest unsupported image fail-closed', () => {
+ const imageUrl = 'data:image/png;base64,aW1hZ2U=';
+ const out = translateResponsesRequest(base({
+ input: [
+ {
+ type: 'message',
+ role: 'user',
+ content: [{ type: 'input_image', image_url: imageUrl }],
+ },
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'continue in text' }] },
+ ],
+ }));
+
+ expect(out.messages).toEqual([{ role: 'user', content: 'continue in text' }]);
+ expect(() => translateResponsesRequest(base({
+ input: [
+ { type: 'message', role: 'user', content: [{ type: 'input_text', text: 'history' }] },
+ {
+ type: 'message',
+ role: 'user',
+ content: [
+ { type: 'input_text', text: 'describe this' },
+ { type: 'input_image', image_url: imageUrl },
+ ],
+ },
+ ],
+ }))).toThrow("input content part 'input_image'");
+ expect(() => translateResponsesRequest(base({
+ input: [
+ {
+ type: 'message',
+ role: 'user',
+ content: [{ type: 'input_image', image_url: imageUrl }],
+ },
+ { type: 'message', role: 'latest_reminder', content: 'current-turn reminder' },
+ ],
+ }))).toThrow("input content part 'input_image'");
+ });
+
it('drops empty user messages produced by auto-compact collapsing image-only turns', () => {
// Codex auto-compact 的 replacement_history 把「无文字纯图片」用户消息折叠成单个
// 空 input_text;桥接层若原样透传,Moonshot/Kimi 会以
diff --git a/packages/responses-chat-bridge/src/__tests__/types.test.ts b/packages/responses-chat-bridge/src/__tests__/types.test.ts
new file mode 100644
index 0000000000..6a65269dbb
--- /dev/null
+++ b/packages/responses-chat-bridge/src/__tests__/types.test.ts
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ isUnsupportedResponsesImageErrorPayload,
+ UnsupportedResponsesFeatureError,
+} from '../types.js';
+
+function unsupportedFeaturePayload(feature: string, code = 'unsupported_feature'): string {
+ return JSON.stringify({
+ error: {
+ type: 'invalid_request_error',
+ code,
+ message: new UnsupportedResponsesFeatureError(feature).message,
+ },
+ });
+}
+
+function codexUnexpectedResponse(messageOrBody: string): string {
+ return `unexpected status 400 Bad Request: ${messageOrBody}, url: http://127.0.0.1/v1/responses`;
+}
+
+describe('isUnsupportedResponsesImageErrorPayload', () => {
+ it.each([
+ "input content part 'input_image'",
+ "input content part 'image_url'",
+ "input content part 'image'",
+ 'input_image',
+ 'input_image.file_id',
+ ])('accepts current and compatible image feature shapes: %s', (feature) => {
+ expect(isUnsupportedResponsesImageErrorPayload(unsupportedFeaturePayload(feature))).toBe(true);
+ });
+
+ it('accepts the bridge message rendered by the pinned Codex runtime', () => {
+ const message =
+ "Responses feature is not supported by the Chat Completions bridge: input content part 'input_image'";
+
+ expect(isUnsupportedResponsesImageErrorPayload(codexUnexpectedResponse(message))).toBe(true);
+ });
+
+ it('accepts a Codex error that retains the serialized bridge response body', () => {
+ const payload = unsupportedFeaturePayload("input content part 'input_image'");
+
+ expect(isUnsupportedResponsesImageErrorPayload(codexUnexpectedResponse(payload))).toBe(true);
+ });
+
+ it.each([
+ unsupportedFeaturePayload("input content part 'input_file'"),
+ unsupportedFeaturePayload("input content part 'input_image'", 'invalid_request'),
+ JSON.stringify({ error: { code: 'unsupported_feature', message: 'input_image' } }),
+ codexUnexpectedResponse(
+ "Responses feature is not supported by the Chat Completions bridge: input content part 'input_file'",
+ ),
+ 'unexpected status 401 Unauthorized: Responses feature is not supported by the Chat Completions bridge: input_image',
+ 'not json',
+ '',
+ ])('rejects unrelated or malformed payloads: %s', (payload) => {
+ expect(isUnsupportedResponsesImageErrorPayload(payload)).toBe(false);
+ });
+});
diff --git a/packages/responses-chat-bridge/src/index.ts b/packages/responses-chat-bridge/src/index.ts
index 16f4e9ff0e..dfe936c408 100644
--- a/packages/responses-chat-bridge/src/index.ts
+++ b/packages/responses-chat-bridge/src/index.ts
@@ -8,6 +8,8 @@ export {
} from './translate-request.js';
export { ChatBridgeToolContext, type ChatBridgeToolKind, type ChatBridgeToolSpec } from './tool-context.js';
export {
+ isResponsesImageContentPartType,
+ isUnsupportedResponsesImageErrorPayload,
UnsupportedResponsesFeatureError,
type ChatBridgeCapabilities,
type ChatBridgeHandleArgs,
diff --git a/packages/responses-chat-bridge/src/translate-request.ts b/packages/responses-chat-bridge/src/translate-request.ts
index 27be2db28d..3031ec4188 100644
--- a/packages/responses-chat-bridge/src/translate-request.ts
+++ b/packages/responses-chat-bridge/src/translate-request.ts
@@ -1,4 +1,5 @@
import {
+ isResponsesImageContentPartType,
UnsupportedResponsesFeatureError,
type ChatAssistantMessage,
type ChatAudioInput,
@@ -95,6 +96,13 @@ function hasImageSource(part: Record<string, unknown>): boolean {
);
}
+function isImagePartTranslatable(
+ part: Record<string, unknown>,
+ capabilities: ChatMediaCapabilities,
+): boolean {
+ return capabilities.imageInput === 'image_url' && part.file_id === undefined;
+}
+
function hasFileSource(part: Record<string, unknown>): boolean {
const source = isPlainObject(part.file) ? part.file : part;
return source.file_id !== undefined
@@ -112,7 +120,7 @@ function mediaPart(
capabilities: ChatMediaCapabilities,
failClosed = false,
): ChatUserContentPart | undefined {
- if (part.type === 'input_image' || part.type === 'image_url' || part.type === 'image') {
+ if (isResponsesImageContentPartType(part.type)) {
if (!hasImageSource(part)) return undefined;
if (capabilities.imageInput !== 'image_url') {
if (failClosed) throw new UnsupportedResponsesFeatureError(String(part.type));
@@ -144,6 +152,7 @@ function messageContent(
itemIndex: number,
developerRole: ChatDeveloperRole,
mediaCapabilities: ChatMediaCapabilities,
+ dropUnsupportedHistoricalImages = false,
): string | ChatUserContentPart[] {
if (typeof item.content === 'string') return item.content;
if (!Array.isArray(item.content)) {
@@ -173,6 +182,19 @@ function messageContent(
content.push({ type: 'text', text: rawPart.refusal });
continue;
}
+ if (
+ dropUnsupportedHistoricalImages
+ && normalizedRole === 'user'
+ && isResponsesImageContentPartType(rawPart.type)
+ && hasImageSource(rawPart)
+ && !isImagePartTranslatable(rawPart, mediaCapabilities)
+ ) {
+ // Codex replays failed user input in later Responses requests. A Chat-only provider that
+ // rejected that image once would otherwise reject every subsequent text turn as well.
+ // Provider-scoped file IDs remain untranslatable even when the route accepts image URLs.
+ // Only replayed images are removed: the newest user turn remains fail-closed below.
+ continue;
+ }
const translatedMedia = mediaPart(rawPart, mediaCapabilities);
if (normalizedRole !== 'user' || !translatedMedia) {
throw new UnsupportedResponsesFeatureError(`input content part '${rawPart.type}'`);
@@ -318,6 +340,27 @@ function translateInput(input: ResponsesRequest['input'], opts: TranslateInputOp
if (typeof input === 'string') return [{ role: 'user', content: input }];
if (!Array.isArray(input)) throw new UnsupportedResponsesFeatureError('input');
+ let newestNormalizedUserMessageIndex = -1;
+ let newestUserMessageIndex = -1;
+ for (let index = input.length - 1; index >= 0; index -= 1) {
+ const item = input[index];
+ if (!isPlainObject(item)) continue;
+ const role = (item as Record<string, unknown>).role;
+ if (typeof role !== 'string') continue;
+ if (role === 'user') {
+ newestUserMessageIndex = index;
+ break;
+ }
+ if (
+ newestNormalizedUserMessageIndex < 0
+ && role !== 'assistant'
+ && normalizeRole(role, opts.developerRole) === 'user'
+ ) newestNormalizedUserMessageIndex = index;
+ }
+ // Codex can append user-like synthetic reminders after the real user item. Treat the latest
+ // explicit user item as the current-turn boundary so a fresh image is never silently discarded.
+ if (newestUserMessageIndex < 0) newestUserMessageIndex = newestNormalizedUserMessageIndex;
+
const messages: ChatMessage[] = [];
let assistant: ChatAssistantMessage | null = null;
let pendingReasoning = '';
@@ -474,6 +517,7 @@ function translateInput(input: ResponsesRequest['input'], opts: TranslateInputOp
index,
opts.developerRole,
opts.mediaCapabilities,
+ index < newestUserMessageIndex,
);
if (item.role === 'assistant') {
if (typeof content !== 'string') {
diff --git a/packages/responses-chat-bridge/src/types.ts b/packages/responses-chat-bridge/src/types.ts
index 46f6a9865a..2d35cfed2b 100644
--- a/packages/responses-chat-bridge/src/types.ts
+++ b/packages/responses-chat-bridge/src/types.ts
@@ -360,11 +360,104 @@ export interface ResponsesChatBridgeHandler {
handle(args: ChatBridgeHandleArgs): Promise<void>;
}
+const UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX =
+ 'Responses feature is not supported by the Chat Completions bridge: ';
+const RESPONSES_IMAGE_CONTENT_PART_TYPES = new Set(['input_image', 'image_url', 'image']);
+const CODEX_UNEXPECTED_BAD_REQUEST_PREFIX = /^unexpected status 400(?: Bad Request)?: /;
+const CODEX_ERROR_METADATA_MARKERS = [
+ ', url: ',
+ ', cf-ray: ',
+ ', request id: ',
+ ', auth error: ',
+ ', auth error code: ',
+] as const;
+
+export function isResponsesImageContentPartType(
+ value: unknown,
+): value is 'input_image' | 'image_url' | 'image' {
+ return typeof value === 'string' && RESPONSES_IMAGE_CONTENT_PART_TYPES.has(value);
+}
+
+function unsupportedResponsesFeatureFromMessage(message: string): string | null {
+ return message.startsWith(UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX)
+ ? message.slice(UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX.length)
+ : null;
+}
+
+function isUnsupportedResponsesImageFeature(feature: string): boolean {
+ const contentPartMatch = /^input content part '([^']+)'$/.exec(feature);
+ const contentPartType = contentPartMatch?.[1] ?? feature;
+ return isResponsesImageContentPartType(contentPartType)
+ || contentPartType.startsWith('input_image.');
+}
+
+function isUnsupportedResponsesImageErrorObject(value: unknown): boolean {
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
+ const error = (value as Record<string, unknown>).error;
+ if (typeof error !== 'object' || error === null || Array.isArray(error)) return false;
+ const { code, message } = error as Record<string, unknown>;
+ if (code !== 'unsupported_feature' || typeof message !== 'string') return false;
+ const feature = unsupportedResponsesFeatureFromMessage(message);
+ return feature !== null && isUnsupportedResponsesImageFeature(feature);
+}
+
+function parseJson(value: string): unknown {
+ try {
+ return JSON.parse(value) as unknown;
+ } catch {
+ return null;
+ }
+}
+
+function parseCodexWrappedJson(value: string): unknown {
+ const jsonStart = value.indexOf('{');
+ if (jsonStart < 0) return null;
+
+ // Codex may append transport metadata after the serialized response body. Walk closing braces
+ // from right to left so braces in that metadata cannot prevent recovery of the response object.
+ let jsonEnd = value.lastIndexOf('}');
+ while (jsonEnd > jsonStart) {
+ const parsed = parseJson(value.slice(jsonStart, jsonEnd + 1));
+ if (parsed !== null) return parsed;
+ jsonEnd = value.lastIndexOf('}', jsonEnd - 1);
+ }
+ return null;
+}
+
+function stripCodexErrorMetadata(value: string): string {
+ let end = value.length;
+ for (const marker of CODEX_ERROR_METADATA_MARKERS) {
+ const index = value.indexOf(marker);
+ if (index >= 0 && index < end) end = index;
+ }
+ return value.slice(0, end);
+}
+
+/**
+ * Classifies an unsupported-image error emitted by this bridge. Direct OpenAI-style response
+ * bodies and Codex's `unexpected status 400 ...` rendering are both accepted; current Codex
+ * extracts `error.message`, while older/future runtimes may retain the serialized body. Both the
+ * current content-part feature and the legacy direct `input_image` feature remain recoverable.
+ */
+export function isUnsupportedResponsesImageErrorPayload(payload: string | null): boolean {
+ if (!payload) return false;
+ if (isUnsupportedResponsesImageErrorObject(parseJson(payload))) return true;
+
+ const codexPrefix = CODEX_UNEXPECTED_BAD_REQUEST_PREFIX.exec(payload);
+ if (!codexPrefix) return false;
+ const renderedBody = payload.slice(codexPrefix[0].length);
+ if (isUnsupportedResponsesImageErrorObject(parseCodexWrappedJson(renderedBody))) return true;
+
+ const message = stripCodexErrorMetadata(renderedBody);
+ const feature = unsupportedResponsesFeatureFromMessage(message);
+ return feature !== null && isUnsupportedResponsesImageFeature(feature);
+}
+
export class UnsupportedResponsesFeatureError extends Error {
readonly feature: string;
constructor(feature: string) {
- super(`Responses feature is not supported by the Chat Completions bridge: ${feature}`);
+ super(`${UNSUPPORTED_RESPONSES_FEATURE_MESSAGE_PREFIX}${feature}`);
this.name = 'UnsupportedResponsesFeatureError';
this.feature = feature;
}